Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ ALLOWED_EMAILS=
# (SES, or a PostShiba tenant of their own), from EMAIL_FROM. Without either, development prints sign-in codes
# in the server console; production can't send them.
RESEND_API_KEY=
# Set to ses to explicitly send platform mail through SES while retaining a Resend key for rollback.
PLATFORM_EMAIL_PROVIDER=
# From address of those emails, on a domain Resend or the email provider verified. Required on a self-hosted
# server; FlockStack Cloud's default is "FlockStack <hello@r.flockstack.io>". On PostShiba it needs a domain no
# newsletter sends from: a domain belongs to one tenant there.
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,8 @@ Use one AWS region for everything below (the examples use `us-east-1`). An AWS a
4. **Add the variables** and redeploy: `SES_REGION`, `SES_ACCESS_KEY_ID`, `SES_SECRET_ACCESS_KEY`, `SES_AWS_ACCOUNT_ID` (the 12-digit account ID) and `SES_SNS_TOPIC_ARN`. Each account's configuration set publishes its events to that topic.
5. **Optional: tenant pauses.** SES pauses tenants that send badly. To block the account in FlockStack too, send SES's tenant status and reputation finding events from EventBridge to a second SNS topic, subscribe `https://<your-app>/api/webhooks/ses-tenants` to it, and set `SES_TENANT_SNS_TOPIC_ARN`.

For an AWS account migration, `SES_SNS_ADDITIONAL_TOPIC_ARNS` accepts a comma-separated list of additional event-topic ARNs while delayed events drain from the old account. It does not change the publishing topic or sending credentials. See [Moving an SES account](docs/SES-ACCOUNT-MIGRATION.md) before a cutover.

Sign-in codes and alerts go out through SES from `EMAIL_FROM`, outside every tenant, so its domain has to be verified in the AWS account before your first sign-in: **Identities > Create identity > Domain**, with Easy DKIM. In the sandbox, the addresses you sign in with have to be verified too.

#### PostShiba
Expand Down
3 changes: 2 additions & 1 deletion app/api/webhooks/ses/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ import { handleSnsRequest } from "@/lib/sns-webhook";

// Bounces, complaints and deliveries from every account's configuration set.
export async function POST(request) {
return handleSnsRequest(request, { topicArn: process.env.SES_SNS_TOPIC_ARN, label: "ses-webhook", handle: handleSesEvent });
const topics = [process.env.SES_SNS_TOPIC_ARN, ...(process.env.SES_SNS_ADDITIONAL_TOPIC_ARNS ?? "").split(",")];
return handleSnsRequest(request, { topicArn: topics, label: "ses-webhook", handle: handleSesEvent });
}
20 changes: 20 additions & 0 deletions docs/SES-ACCOUNT-MIGRATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Moving an SES account

Production approval and a quota do not move existing tenants, domains, configuration sets or suppressions.

Before changing sending credentials:

1. Confirm production access, account health, region and quota in the destination. Inventory each region separately.
2. Recreate the active customer tenants, configuration sets and identity associations. Preserve the tenant/configuration-set names the database uses, then prepare a mapping from the old tenant ARNs to the new ARNs. Do not update the live database during preparation.
3. Verify each sender identity using new DKIM CNAMEs alongside the old records. Configure the same regional MAIL FROM after checking its DNS. Keep the existing identities and records for rollback.
4. Create the destination SNS topic and grant SES publish access restricted to the destination account and intended configuration-set ARNs. Recreate event destinations for sends, rejections, rendering failures, delivery, delivery delays, bounces and complaints.
5. Deploy webhook support before subscribing the new topic. Keep `SES_SNS_TOPIC_ARN` pointed at the current publisher during preparation and set `SES_SNS_ADDITIONAL_TOPIC_ARNS` to the new topic ARN. It accepts comma-separated explicit ARNs; signatures are still required. Raw SNS delivery must stay off. Confirm the HTTPS subscription without sending an email.
6. Privately reconcile suppressions from the app and old SES account/tenant. Attribute them using message and customer records, not the recipient's domain. Preserve unsubscribes and the suppression hash key. Do not copy recipient data into this repository.
7. New SES resources carry `managed_by=flockstack` so runtime IAM can restrict management and sending by ownership. Tag existing destination identities, configuration sets and tenants before using a policy that requires this tag.
8. Prepare scoped destination credentials securely. The app and API Worker need consistent settings. Match the rate limiter to the destination quota with headroom; do not change platform sign-in mail or another region incidentally.

The current SES client and customer metadata select one AWS account. Changing the credentials alone does not implement a percentage rollout. Prepare explicit per-customer/message routing and rollback, including any platform mail that uses SES, before the planned staged cutover. Never retry a timed-out send through the other account: the first send may have succeeded.

After an authorized cutover, make the new topic primary and keep the old topic in `SES_SNS_ADDITIONAL_TOPIC_ARNS` while delayed events drain. Only remove old resources and DNS records after the observation period and a separate cleanup decision.

To move platform mail explicitly, set `PLATFORM_EMAIL_PROVIDER=ses` with `EMAIL_PROVIDER=ses` after the destination identity and feedback are ready. This keeps a configured Resend key available for rollback, but never falls back to it on an SES error. Existing templates and signing/suppression secrets stay unchanged.
3 changes: 2 additions & 1 deletion lib/auth-keyring.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,9 @@ export function createJwksKeyring({ model = "jwks", log = console } = {}) {
const { symmetricDecrypt, symmetricEncrypt } = await import("better-auth/crypto");
const plain = typeof stored === "string" ? await readPrivateKey({ symmetricDecrypt, secretConfig, secrets: getAppSecrets() }, stored) : null;
if (plain === null) {
retired.add(row.id);
row.expiresAt = new Date(now - 1);
if (retired.has(row.id)) continue;
retired.add(row.id);
log.error(`[auth] The OAuth signing key ${row.id} can't be decrypted with BETTER_AUTH_SECRET or BETTER_AUTH_SECRET_PREVIOUS: it is retired and a new one is made. Its public key stays listed for 30 days, so tokens already issued keep verifying. Rotate with BETTER_AUTH_SECRET_PREVIOUS set to avoid this (docs/AUTH-ROTATION.md).`);
await adapter.update({ model, where: [{ field: "id", value: row.id }], update: { expiresAt: row.expiresAt } }).catch((error) => log.error("[auth] Could not retire the signing key:", error?.message ?? error));
continue;
Expand Down
9 changes: 7 additions & 2 deletions lib/platform-email.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { escapeHtml } from "@/lib/escape-html";

const RESEND_URL = "https://api.resend.com/emails";

function shouldUseResend() {
return process.env.PLATFORM_EMAIL_PROVIDER !== "ses" && Boolean(process.env.RESEND_API_KEY);
}

async function sendWithResend({ from, to, subject, text, html, replyTo = getEmailReplyTo() }) {
const response = await fetch(RESEND_URL, {
method: "POST",
Expand All @@ -15,22 +19,23 @@ async function sendWithResend({ from, to, subject, text, html, replyTo = getEmai
if (!response.ok) throw new Error(`Resend answered ${response.status}: ${(await response.text()).slice(0, 200)}`);
}

// PLATFORM_EMAIL_PROVIDER=ses explicitly selects SES and preserves the Resend key for rollback. Otherwise,
// FlockStack's own emails (sign-in codes, alerts) go through Resend when RESEND_API_KEY is set, apart from
// customers' emails; without it they go through the email provider (SES), from EMAIL_FROM. replyTo replaces where a reply
// goes: a support chat's transcript is answered to the customer.
export async function sendPlatformEmail({ to, subject, text, html, replyTo }) {
const from = getEmailFrom();
if (!from) throw new Error("EMAIL_FROM is not set: FlockStack's own emails need a from address on a domain Resend or the email provider verified");
const reply = replyTo ? { replyTo } : {};
if (process.env.RESEND_API_KEY) return sendWithResend({ from, to, subject, text, html, ...reply });
if (shouldUseResend()) return sendWithResend({ from, to, subject, text, html, ...reply });
if (!isEmailProviderConfigured()) throw new Error("FlockStack's own emails have no way out: set RESEND_API_KEY, or the email provider's keys");
await getEmailProvider().sendPlatformEmail({ from, to, subject, text, html, ...reply });
}

// Without a way out, alerts are only logged.
export function canSendPlatformEmail() {
if (!getEmailFrom()) return false;
return Boolean(process.env.RESEND_API_KEY) || isEmailProviderConfigured();
return shouldUseResend() || isEmailProviderConfigured();
}

// Whether a code by email can sign someone in here: an email can go out, or development prints the code (sendCode).
Expand Down
5 changes: 3 additions & 2 deletions lib/ses.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ async function loadSesAccount() {
export async function createConfigurationSet(name) {
const topicArn = process.env.SES_SNS_TOPIC_ARN;
if (!topicArn) throw new Error("SES is not configured (SES_SNS_TOPIC_ARN)");
await writeOnce(new CreateConfigurationSetCommand({ ConfigurationSetName: name, ReputationOptions: { ReputationMetricsEnabled: true } }));
await writeOnce(new CreateConfigurationSetCommand({ ConfigurationSetName: name, ReputationOptions: { ReputationMetricsEnabled: true }, Tags: [{ Key: "managed_by", Value: "flockstack" }] }));
await writeOnce(
new CreateConfigurationSetEventDestinationCommand({
ConfigurationSetName: name,
Expand All @@ -172,7 +172,7 @@ export async function createTenant(name, { accountId }) {
await writeOnce(
new CreateTenantCommand({
TenantName: name,
Tags: [{ Key: "account_id", Value: String(accountId) }],
Tags: [{ Key: "account_id", Value: String(accountId) }, { Key: "managed_by", Value: "flockstack" }],
SuppressionAttributes: { SuppressionScope: "TENANT", SuppressedReasons: ["BOUNCE", "COMPLAINT"] },
})
);
Expand Down Expand Up @@ -280,6 +280,7 @@ export async function createDomainIdentity(domain, { configurationSet, mailFromD
EmailIdentity: domain,
DkimSigningAttributes: { NextSigningKeyLength: "RSA_2048_BIT" },
ConfigurationSetName: configurationSet,
Tags: [{ Key: "managed_by", Value: "flockstack" }],
})
);
await write(
Expand Down
8 changes: 5 additions & 3 deletions lib/sns-webhook.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,17 @@ async function handleNotification(message, { label, handle }) {
}
}

// One SNS topic per route. Needs an HTTPS subscription with raw message delivery off, so the envelope is signed.
// Keep the old topic allowed while an account migration's in-flight events drain. Every topic still needs
// an explicit ARN and a signed envelope (raw message delivery off).
export async function handleSnsRequest(request, { topicArn, label, handle }) {
if (!topicArn) return reply(503, { error: "Webhook is not configured" });
const topics = (Array.isArray(topicArn) ? topicArn : [topicArn]).filter((arn) => typeof arn === "string" && arn.trim()).map((arn) => arn.trim());
if (!topics.length) return reply(503, { error: "Webhook is not configured" });

const body = await request.text();
if (body.length > MAX_BODY_LENGTH) return reply(413, { error: "Body is too large" });
const message = parseJson(body);
if (!isPlainObject(message)) return reply(400, { error: "Invalid JSON" });
if (message.TopicArn !== topicArn) return reply(403, { error: "Unknown topic" });
if (!topics.includes(message.TopicArn)) return reply(403, { error: "Unknown topic" });
if (!(await verifySnsMessage(message))) return reply(400, { error: "Invalid signature" });

if (message.Type === "SubscriptionConfirmation") return confirmSubscription(message, label);
Expand Down
Loading
Loading