From b5a600d1dc4c66ad123164a8cf6c70f04d0e93dc Mon Sep 17 00:00:00 2001 From: ankurmans <12939357+ankurmans@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:28:19 +0300 Subject: [PATCH 1/3] Prepare signed SES feedback during account migration --- README.md | 2 ++ app/api/webhooks/ses/route.js | 3 ++- docs/SES-ACCOUNT-MIGRATION.md | 17 +++++++++++++++++ lib/sns-webhook.js | 8 +++++--- tests/region-webhooks.test.mjs | 32 ++++++++++++++++++++++++++++++++ 5 files changed, 58 insertions(+), 4 deletions(-) create mode 100644 docs/SES-ACCOUNT-MIGRATION.md diff --git a/README.md b/README.md index 2db22c25..9e7ba1dd 100644 --- a/README.md +++ b/README.md @@ -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:///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 diff --git a/app/api/webhooks/ses/route.js b/app/api/webhooks/ses/route.js index 1cfa4107..46adaa6e 100644 --- a/app/api/webhooks/ses/route.js +++ b/app/api/webhooks/ses/route.js @@ -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 }); } diff --git a/docs/SES-ACCOUNT-MIGRATION.md b/docs/SES-ACCOUNT-MIGRATION.md new file mode 100644 index 00000000..a6281782 --- /dev/null +++ b/docs/SES-ACCOUNT-MIGRATION.md @@ -0,0 +1,17 @@ +# 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. 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. diff --git a/lib/sns-webhook.js b/lib/sns-webhook.js index d6575ce2..7c366ced 100644 --- a/lib/sns-webhook.js +++ b/lib/sns-webhook.js @@ -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); diff --git a/tests/region-webhooks.test.mjs b/tests/region-webhooks.test.mjs index bb336ac5..c6745736 100644 --- a/tests/region-webhooks.test.mjs +++ b/tests/region-webhooks.test.mjs @@ -297,6 +297,38 @@ describe("Amazon SES through SNS", () => { assert.equal(wrongTopic.result.status, 403); assert.equal(wrongTopic.alerts, 0); }); + + test("an account migration accepts explicitly allowed old and new topics, while rejecting other topics and forged events", async () => { + const nextTopic = "arn:aws:sns:eu-west-1:222222222222:flockstack-next-ses-events"; + process.env.SES_SNS_ADDITIONAL_TOPIC_ARNS = ` , ${nextTopic}, `; + try { + for (const topic of [SES_TOPIC, nextTopic]) { + const observed = await observe(() => post(m.sesRoute, "/api/webhooks/ses", notification(topic, bounceFor(OTHER_ACCOUNT)))); + assert.equal(observed.result.status, 200); + assertAcknowledged(observed, "email-events"); + } + const unknown = notification(`${nextTopic}-unknown`, bounceFor(OTHER_ACCOUNT)); + assert.equal((await post(m.sesRoute, "/api/webhooks/ses", unknown)).status, 403); + const forged = { ...notification(nextTopic, bounceFor(OTHER_ACCOUNT)), Message: "{}" }; + assert.equal((await post(m.sesRoute, "/api/webhooks/ses", forged)).status, 400); + assert.equal((await post(m.tenantRoute, "/api/webhooks/ses-tenants", notification(nextTopic, {}))).status, 403); + } finally { + delete process.env.SES_SNS_ADDITIONAL_TOPIC_ARNS; + } + assert.equal((await post(m.sesRoute, "/api/webhooks/ses", notification(nextTopic, {}))).status, 403); + }); + + test("empty topic configuration fails closed without accepting an unsigned envelope", async () => { + const previous = process.env.SES_SNS_TOPIC_ARN; + delete process.env.SES_SNS_TOPIC_ARN; + process.env.SES_SNS_ADDITIONAL_TOPIC_ARNS = " , "; + try { + assert.equal((await post(m.sesRoute, "/api/webhooks/ses", {})).status, 503); + } finally { + process.env.SES_SNS_TOPIC_ARN = previous; + delete process.env.SES_SNS_ADDITIONAL_TOPIC_ARNS; + } + }); }); describe("PostShiba", () => { From 6f448474ad16da2e5762ae825584b2dd6624bfed Mon Sep 17 00:00:00 2001 From: ankurmans <12939357+ankurmans@users.noreply.github.com> Date: Thu, 12 Nov 2026 02:49:38 +0300 Subject: [PATCH 2/3] Prepare scoped SES ownership and explicit platform routing --- .env.example | 2 ++ docs/SES-ACCOUNT-MIGRATION.md | 5 ++++- lib/auth-keyring.js | 3 ++- lib/platform-email.js | 9 +++++++-- lib/ses.js | 5 +++-- scripts/readers-env.mjs | 1 + tests/auth-rotation.test.mjs | 14 ++++++++++++++ tests/platform-email.test.mjs | 13 +++++++++++++ tests/ses-lazy.test.mjs | 11 +++++++++++ 9 files changed, 57 insertions(+), 6 deletions(-) diff --git a/.env.example b/.env.example index 84598324..e4b1bab3 100644 --- a/.env.example +++ b/.env.example @@ -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 ". On PostShiba it needs a domain no # newsletter sends from: a domain belongs to one tenant there. diff --git a/docs/SES-ACCOUNT-MIGRATION.md b/docs/SES-ACCOUNT-MIGRATION.md index a6281782..fd68aa1d 100644 --- a/docs/SES-ACCOUNT-MIGRATION.md +++ b/docs/SES-ACCOUNT-MIGRATION.md @@ -10,8 +10,11 @@ Before changing sending credentials: 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. 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. +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. diff --git a/lib/auth-keyring.js b/lib/auth-keyring.js index 8df0d546..c1815d70 100644 --- a/lib/auth-keyring.js +++ b/lib/auth-keyring.js @@ -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; diff --git a/lib/platform-email.js b/lib/platform-email.js index db2535c8..da37a570 100644 --- a/lib/platform-email.js +++ b/lib/platform-email.js @@ -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", @@ -15,6 +19,7 @@ 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. @@ -22,7 +27,7 @@ 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 }); } @@ -30,7 +35,7 @@ export async function sendPlatformEmail({ to, subject, text, html, replyTo }) { // 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). diff --git a/lib/ses.js b/lib/ses.js index 149799f9..0d35697d 100644 --- a/lib/ses.js +++ b/lib/ses.js @@ -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, @@ -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"] }, }) ); @@ -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( diff --git a/scripts/readers-env.mjs b/scripts/readers-env.mjs index aa6d0c61..a5316d54 100644 --- a/scripts/readers-env.mjs +++ b/scripts/readers-env.mjs @@ -73,6 +73,7 @@ export const NOT_NEEDED = { POSTSHIBA_TEAM_ID: "the other email provider", POSTSHIBA_TRANSACTIONAL_CLUSTER_ID: "the other email provider", RESEND_API_KEY: "the app's own platform emails (sign-in codes), sent by the app", + PLATFORM_EMAIL_PROVIDER: "selects how the app sends its own sign-in codes and alerts, which the readers Worker never sends", STRIPE_CONNECT_SECRET_KEY: "creators' payments", STRIPE_PAYMENTS_WEBHOOK_SECRET: "creators' payments", STRIPE_SECRET_KEY: "billing", diff --git a/tests/auth-rotation.test.mjs b/tests/auth-rotation.test.mjs index ef2eb724..d8f32dfe 100644 --- a/tests/auth-rotation.test.mjs +++ b/tests/auth-rotation.test.mjs @@ -5,6 +5,7 @@ import { activate, startTestApp, withEnv } from "./helpers/app.mjs"; import { AGENT, APP_URL, MCP_URL, createOAuthHarness, loadOAuthRoutes } from "./helpers/oauth-flow.mjs"; import { forgetAuth } from "../lib/auth.js"; import { getSecretVersion } from "../lib/auth-secrets.js"; +import { createJwksKeyring } from "../lib/auth-keyring.js"; // Rotating BETTER_AUTH_SECRET under MCP clients (Claude Code, Codex, ChatGPT): what keeps working with the old value in // BETTER_AUTH_SECRET_PREVIOUS, and what happens to an OAuth signing key nobody can decrypt (docs/AUTH-ROTATION.md). @@ -194,3 +195,16 @@ describe("when something fails", () => { deploy({ current: A }); }); }); + +// Two requests may discover the same unreadable key before either asynchronous read finishes. +test("concurrent requests retire and report an unreadable signing key only once", async () => { + let writes = 0; + const errors = []; + const row = { id: "concurrent-fixture", privateKey: "invalid-json", createdAt: new Date() }; + const adapter = { findMany: async () => [{ ...row }], update: async () => { writes++; } }; + const read = createJwksKeyring({ log: { error: (...args) => errors.push(args), info() {} } }); + const results = await Promise.all(Array.from({ length: 4 }, () => read({ context: { adapter } }))); + assert.equal(writes, 1); + assert.equal(errors.length, 1); + for (const rows of results) assert.ok(rows[0].expiresAt.getTime() < Date.now()); +}); diff --git a/tests/platform-email.test.mjs b/tests/platform-email.test.mjs index 8d826ac4..983a2ecb 100644 --- a/tests/platform-email.test.mjs +++ b/tests/platform-email.test.mjs @@ -70,6 +70,19 @@ describe("FlockStack Cloud", () => { assert.equal(platformEmails.at(-2).subject, "[FlockStack] Cloud alert"); }); + test("an explicit SES selection uses SES with the Resend key retained for rollback and fails closed without SES keys", async () => { + const before = counts(); + await withEnv({ PLATFORM_EMAIL_PROVIDER: "ses" }, async () => { + await m.platform.sendPlatformEmail({ to: "reader@example.com", subject: "Delivery check", text: "Unchanged content" }); + assert.equal(platformSent.at(-1).text, "Unchanged content"); + await withEnv({ SES_ACCESS_KEY_ID: "", SES_SECRET_ACCESS_KEY: "" }, async () => { + assert.equal(m.platform.canSendPlatformEmail(), false); + await assert.rejects(m.platform.sendPlatformEmail({ to: "reader@example.com", subject: "No fallback", text: "Check" })); + }); + }); + assert.deepEqual(added(before), { resend: 0, ses: 1, postshiba: 0, customer: 0 }); + }); + test("without RESEND_API_KEY the cloud sends its own emails through the email provider", async () => { const before = counts(); await withEnv({ RESEND_API_KEY: "" }, async () => { diff --git a/tests/ses-lazy.test.mjs b/tests/ses-lazy.test.mjs index 172f5c59..e8c55f22 100644 --- a/tests/ses-lazy.test.mjs +++ b/tests/ses-lazy.test.mjs @@ -24,6 +24,9 @@ before(async () => { response.setHeader("content-type", "application/json"); if (request.url === "/v2/email/account") response.end(JSON.stringify({ ProductionAccessEnabled: true, SendingEnabled: true, EnforcementStatus: "HEALTHY", SendQuota: { Max24HourSend: 50000, MaxSendRate: 14, SentLast24Hours: 12 } })); else if (request.url.startsWith("/v2/email/identities/")) response.end(JSON.stringify({ VerifiedForSendingStatus: true, DkimAttributes: { Status: "SUCCESS", Tokens: ["abc"] }, MailFromAttributes: { MailFromDomain: "bounce.example.com", MailFromDomainStatus: "SUCCESS" } })); + else if (request.method === "POST" && ["/v2/email/configuration-sets", "/v2/email/tenants"].includes(request.url) && /tag-check/.test(body)) response.end("{}"); + else if (request.method === "POST" && request.url === "/v2/email/identities" && /tag-check/.test(body)) response.end("{}"); + else if (request.method === "GET" && request.url === "/v2/email/tenants/mc-tag-check") response.end(JSON.stringify({ Tenant: { TenantArn: "arn:aws:ses:eu-west-1:111122223333:tenant/mc-tag-check/test" } })); else if (request.url === "/v2/email/outbound-emails") response.end(JSON.stringify({ MessageId: "ses-123" })); else { response.statusCode = 404; @@ -81,6 +84,14 @@ describe("lib/ses.js and the AWS SDK", () => { assert.equal(request.body.Content.Simple.Body.Html.Data, "

Hello

"); }); + test("new customer identities carry the ownership tag required by runtime access", async () => { + const ses = await import("../lib/ses.js"); + await ses.createDomainIdentity("tag-check.example.com", { configurationSet: "mc-tag-check", mailFromDomain: "bounce.tag-check.example.com" }); + const identity = requests.find((request) => request.method === "POST" && request.url === "/v2/email/identities"); + assert.deepEqual(identity.body.Tags, [{ Key: "managed_by", Value: "flockstack" }]); + assert.equal(identity.body.ConfigurationSetName, "mc-tag-check"); + }); + test("creating what exists counts as done, and a missing thing on delete too", async () => { const ses = await import("../lib/ses.js"); // The local server answers 404 for anything else: deleting something gone is fine, other failures are not hidden. From 80d425e1e49faa1b835571b8a235ea94c98d82f2 Mon Sep 17 00:00:00 2001 From: ankurmans <12939357+ankurmans@users.noreply.github.com> Date: Thu, 12 Nov 2026 02:55:08 +0300 Subject: [PATCH 3/3] Account for the shipped provider size in the API budget --- perf-budgets.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/perf-budgets.json b/perf-budgets.json index 59a26042..cdf4ebc9 100644 --- a/perf-budgets.json +++ b/perf-budgets.json @@ -1,5 +1,5 @@ { - "_about": "Sizes the Workers must stay under (scripts/perf-budget.mjs, tests/perf-budget.test.mjs). Measured on 2026-10-23 with a little room (the app grew 0.6 MB when the SDKs and schemas became lazy: each `import()` is a chunk of its own, in both of Next.js's layers, and the dashboard evaluates 1.5 MB less of it); The content calendar (2026-10-24) took the app 0.6 MB (handler 28.60 to 29.19 MB): its three dashboard pages, a docs page, 24 actions and their schemas, in both of Next.js's layers, of which the pages' client reference manifests are 0.26 MB. Raise one only in a change that says why a Worker had to grow. Bytes. The 2026-10-25 remaining handover builds add 11 public actions and four dashboard-only actions, owner claim and team pages, replies and reader settings, Stripe import, Markdown endpoints and six reader language catalogs. Measured handler 30.585 MB and app upload 32.876 MB versus brand-fleet 29.454/31.729 MB. Keep new services lazy and the inbound MIME parser in its own optional Worker. Raise only the app limits to 31.0/33.4 MB; API/readers limits stay unchanged. The next 2026-10-25 product batch adds seven registry actions, two owner pages, author/reader-preview panels, private perk downloads, code/contents blocks, selectable overview ranges and 17 ID-only event types. Measured app handler 31.389 MB, app upload 33.689 MB and API 8.594 MB, versus reader-language build 30.960/33.254/8.27 MB. These are added product routes and schemas; no new SDK was placed on dashboard imports. Set handler/upload/API limits to 31.8/34.1/8.8 MB with modest remaining room. Other limits stay unchanged. The 2026-10-25 mailing-list/meter build measured 31.73/34.03 MB. HTML source snippets, audience-block filtering and controls, the [[ link picker and private links panel, and two link-index actions bring handler/upload to 31.809/34.115 MB. No new SDK was added. Set only those limits to 32.2/34.5 MB; API and other limits stay unchanged. The supporter badge, creator matches/private inbox and short web post batch adds two creator dashboard routes, three small creator forms, one short-post editor and nine public actions. Measured handler 32261848 bytes and app upload 34574957 bytes, versus paid-trial 31.99/34.30 MB; API is 8.71 MB. Reuses the campaign and platform email engines and adds no SDK. Set only app handler/upload limits to 32.6/34.9 MB, with modest room for the remaining accepted builds. API/readers and other limits stay unchanged. AI images and the owner-only account assistant (2026-10-25) added public-image generation, guarded draft/segment/calendar tool orchestration and review UI: measured handler 32641968 bytes and app upload 34961404 bytes. App limits are 32.90 and 35.20 MB, leaving modest room above this measured feature batch; API and other limits are unchanged. Reader billing-language parity adds 107 six-language phrases, full account billing summaries and localized pledge/gift mail and known validation patterns. Measured API Worker 8817044 bytes versus 8773068 at the AI checkpoint. Raise only API to8.95 MB; other limits stay unchanged. No SDK added. The combined reader billing language and Reply Rules build measured app handler33516993 and upload35841500 bytes. Reply Rules adds owner settings, reader consent/decision UI, classifier, current-access/session checks, export metadata and public/privacy docs; the six-language catalogs grew107+9 phrases. AI-checkpoint versus current server chunks grow806393 bytes, with node_modules chunks unchanged8031669 bytes: no new SDK dependency. Client manifests grew only3326 bytes. Preserve lazy model/job imports (Contacts closure1.471MB); set app limits33.8/36.1MB after this measured feature batch. API8.840088MB remains under8.95MB; other limits unchanged. Local byte counts do not measure production latency. Group subscriptions (2026-10-25) add three page modules (owner list/detail and public buyer/manager/invite), three small form/billing components, 11 actions and their schemas, current-invoice funding and source reconciliation, private capabilities, export/privacy coverage and 73 six-language interface/email phrases. Measured handler34192236 and upload36523328 bytes versus reader-event33500k/35830k baseline; API8932704 and readers2512667 bytes stay within existing limits. No dependency was added. The two group compile runs have identical node_modules chunk bytes7327681 under the same basename-prefix measure; 42 weight/query/purge checks and final page-closure rerun preserve lazy common dashboard imports. Raise only app handler/upload to34.5/36.85MB with modest room for this feature. This is local source-size evidence, not production latency. Direct sponsorships add 24 registry actions (one human-only), inventory and verified booking, private image storage, invoice creation and recovery, approved editor snapshots, actual containing-message reports, export/privacy integration and 79 six-language interface/email phrases. No dependency was added. API measured 9059675 bytes versus the group checkpoint 8932704 bytes; increase its source budget to 9.15 MB. The accidental reader catalog import through newsletter defaults was removed: layout closure falls from 1.39 MB to 1.19 MB, retaining its 1.35 MB cap. Fresh sponsorship compile measures app handler 35515685 bytes and upload 37859574 bytes, versus group 34192236/36523328. Next server JS grows 1133659 bytes (25575680 to 26709339), of which node_modules basename-prefix chunks grow 15705 (7327681 to 7343386); no package was added. Added source, schemas, six-language copy, six public/owner page routes, editor snapshot block and client/server manifests account for the feature batch. Raise only app handler/upload to 35.8/38.15 MB with modest headroom; API/readers remain within 9.15/2.8 MB. All values measure local source size, not latency. Reader billing choices (2026-10-25) add nine creator actions, two dashboard/private reader routes, native Stripe pause/resume/save/cancel services and 46 six-language control/status phrases. Measured handler35878134 and upload38225032 bytes versus sponsorship35515685/37859574; dedicated feature source89991 bytes compiles in both Next layers. package.json and package-lock.json are byte-identical to the sponsorship checkpoint: no new dependency. API9147785 and readers2572927 stay within existing limits. Set only app handler/upload to36.15/38.50MB with modest room over this measured feature. Local source sizes do not measure production latency. Realtime collaboration adds six public private-editor actions and two dashboard-only ticket/checkpoint actions, a current-session/team/draft service authority and content-CAS fields. Early measured API9181978 versus reader-billing9147785 bytes; no Yjs, Tiptap or DOM parser enters the API. Set API9.30MB with modest room for the feature. The new optional collaboration Worker is separately measured1194343 bytes with a1.50MB budget; its native runtime tests use its compiled output. The first combined app compile measured handler36248885 and upload38599123, versus reader billing35878134/38225032: +370751/+374091 bytes for the collaborative client route, shared-schema checkpoint and private discussion code, schemas and manifests. The DOM parser remains in the separately bundled optional Worker; existing dashboard closure guards pass. Set app limits36.50/38.85MB with modest room; final verified bytes are recorded in docs/PERFORMANCE.md. Final handover after compatibility/copy/billing race followups measured handler36260231, upload38610476, API9186272, readers2575539 and optional collaboration1194911 bytes. All eight budgets pass; app full suite3470passed/0failed/3existing skips, plus12native passes. Final source-size evidence is local only. QA release fixes (2026-10-27) lower the budgets: the Cloud build (FLOCKSTACK_CLOUD_BUILD=true, set by scripts/deploy-all.mjs) replaces the S3, CloudFront and Vercel Blob clients with a stub and loads a narrowed mingo only where SQL cannot answer. Measured app handler 33267648 (from 36261626), upload 35572983 (from 38611873), API 8017027 (from 9187110), readers 2520388 (from 2575539). Limits are 33.6/35.95/8.15/2.65 MB; they only go down. The 2026-10-27 sprint wrap adds, on top of the QA size cuts, share buttons, custom headers, image crop and GIFs, random cohort sends, the tag filter and archive bulk action, held signups and private archives, Mailchimp import, gift links, the upsell template, per-issue schema and device split, and 17 registry actions. Measured app handler 33748560 and upload 36057862 versus the QA checkpoint 33267648/35572983 (+0.48 MB). No dependency was added. Limits are 34.0/36.3 MB, still about 2.3 MB under the build in production before the cuts. The optional briefings Worker (2026-10-28, docs/BRIEFINGS-DESIGN.md) is built like the readers Worker from workers/briefings/index.js: the engine in lib/briefings (66 KB), the shared docdb with its narrowed mingo (500 KB of the 608 KB), the AI key store and three models, no Next.js, React, SES or auth code. Measured 608225 bytes, the same in the Cloud and self-hosted builds; limit 0.75 MB (1.23 times) for the engine work still to come in its first runs. The same change adds the BriefingsDelivery entrypoint to the API Worker, loaded only on its first RPC call: lib/briefings-delivery.js is 4.5 KB of the API Worker, which measured 8139972 bytes in the Cloud build with the Briefings actions, under its unchanged 8.15 MB. Briefings (2026-10-28, main 4ffd4e0): the app measured handler 34273082 and upload 36590421 bytes, +524 KB and +533 KB on the sprint wrap. It is the Briefings registry actions and their schemas, AI keys, the briefing, run and AI key pages, the public verdict page and the briefings-bot docs page; the engine is not in the app (it runs in the briefings Worker; the hourly cron imports it only when self-hosted). No dependency was added. Limits 34.5/36.85 MB; trimming the Briefings schemas from the app bundle is the next size task. Subfolder hosting and briefing sections (2026-10-28, main 2e46231): handler 34614985 and upload 36946238 bytes, about +0.34 MB on the Briefings measurement: the mount actions, routing and HTMLRewriter step, the subfolder docs page with its five recipes, and the section editor and run tables. No dependency was added. Limits 34.75/37.1 MB. This is the second raise in a day: the next change to the app must take the Briefings and mount schemas and docs recipes out of the app handler (they are only needed by the API Worker and the public pages) before anything else is added. Mingo ESM (2026-10-28): every bundle now takes mingo's ESM build (scripts/mingo-esm.mjs), so its unused operators drop out: app handler 34,615,958 to 34,003,661 bytes, upload 36,947,202 to 36,125,410, API Worker 7,908,694 to 7,552,868, readers 2,252,348 to 1,898,736, briefings 749,241 to 396,140. Limits unchanged. This replaces the earlier note that Briefings and mount code must leave the app first: measured at about 0.31 MB, they cannot leave it without breaking the dashboard, self-hosting or the public pages render (docs/PERFORMANCE.md). Short chunk names (2026-10-28): scripts/short-chunk-names.mjs, after dedupe-chunks in the build command, gives every server chunk but the runtime and the [externals] chunks a base-36 name, so the 83,507 places the build names a chunk (the loaders' lists of nested async chunking, routes' entries, client reference manifests, OpenNext's modules and requireChunk) are shorter: app handler 34,243,892 to 30,716,983 bytes, upload 36,367,927 to 32,752,997. Nothing else changes (docs/PERFORMANCE.md). Limits unchanged, so the app has 4 MB of room again.", + "_about": "Sizes the Workers must stay under (scripts/perf-budget.mjs, tests/perf-budget.test.mjs). Measured on 2026-10-23 with a little room (the app grew 0.6 MB when the SDKs and schemas became lazy: each `import()` is a chunk of its own, in both of Next.js's layers, and the dashboard evaluates 1.5 MB less of it); The content calendar (2026-10-24) took the app 0.6 MB (handler 28.60 to 29.19 MB): its three dashboard pages, a docs page, 24 actions and their schemas, in both of Next.js's layers, of which the pages' client reference manifests are 0.26 MB. Raise one only in a change that says why a Worker had to grow. Bytes. The 2026-10-25 remaining handover builds add 11 public actions and four dashboard-only actions, owner claim and team pages, replies and reader settings, Stripe import, Markdown endpoints and six reader language catalogs. Measured handler 30.585 MB and app upload 32.876 MB versus brand-fleet 29.454/31.729 MB. Keep new services lazy and the inbound MIME parser in its own optional Worker. Raise only the app limits to 31.0/33.4 MB; API/readers limits stay unchanged. The next 2026-10-25 product batch adds seven registry actions, two owner pages, author/reader-preview panels, private perk downloads, code/contents blocks, selectable overview ranges and 17 ID-only event types. Measured app handler 31.389 MB, app upload 33.689 MB and API 8.594 MB, versus reader-language build 30.960/33.254/8.27 MB. These are added product routes and schemas; no new SDK was placed on dashboard imports. Set handler/upload/API limits to 31.8/34.1/8.8 MB with modest remaining room. Other limits stay unchanged. The 2026-10-25 mailing-list/meter build measured 31.73/34.03 MB. HTML source snippets, audience-block filtering and controls, the [[ link picker and private links panel, and two link-index actions bring handler/upload to 31.809/34.115 MB. No new SDK was added. Set only those limits to 32.2/34.5 MB; API and other limits stay unchanged. The supporter badge, creator matches/private inbox and short web post batch adds two creator dashboard routes, three small creator forms, one short-post editor and nine public actions. Measured handler 32261848 bytes and app upload 34574957 bytes, versus paid-trial 31.99/34.30 MB; API is 8.71 MB. Reuses the campaign and platform email engines and adds no SDK. Set only app handler/upload limits to 32.6/34.9 MB, with modest room for the remaining accepted builds. API/readers and other limits stay unchanged. AI images and the owner-only account assistant (2026-10-25) added public-image generation, guarded draft/segment/calendar tool orchestration and review UI: measured handler 32641968 bytes and app upload 34961404 bytes. App limits are 32.90 and 35.20 MB, leaving modest room above this measured feature batch; API and other limits are unchanged. Reader billing-language parity adds 107 six-language phrases, full account billing summaries and localized pledge/gift mail and known validation patterns. Measured API Worker 8817044 bytes versus 8773068 at the AI checkpoint. Raise only API to8.95 MB; other limits stay unchanged. No SDK added. The combined reader billing language and Reply Rules build measured app handler33516993 and upload35841500 bytes. Reply Rules adds owner settings, reader consent/decision UI, classifier, current-access/session checks, export metadata and public/privacy docs; the six-language catalogs grew107+9 phrases. AI-checkpoint versus current server chunks grow806393 bytes, with node_modules chunks unchanged8031669 bytes: no new SDK dependency. Client manifests grew only3326 bytes. Preserve lazy model/job imports (Contacts closure1.471MB); set app limits33.8/36.1MB after this measured feature batch. API8.840088MB remains under8.95MB; other limits unchanged. Local byte counts do not measure production latency. Group subscriptions (2026-10-25) add three page modules (owner list/detail and public buyer/manager/invite), three small form/billing components, 11 actions and their schemas, current-invoice funding and source reconciliation, private capabilities, export/privacy coverage and 73 six-language interface/email phrases. Measured handler34192236 and upload36523328 bytes versus reader-event33500k/35830k baseline; API8932704 and readers2512667 bytes stay within existing limits. No dependency was added. The two group compile runs have identical node_modules chunk bytes7327681 under the same basename-prefix measure; 42 weight/query/purge checks and final page-closure rerun preserve lazy common dashboard imports. Raise only app handler/upload to34.5/36.85MB with modest room for this feature. This is local source-size evidence, not production latency. Direct sponsorships add 24 registry actions (one human-only), inventory and verified booking, private image storage, invoice creation and recovery, approved editor snapshots, actual containing-message reports, export/privacy integration and 79 six-language interface/email phrases. No dependency was added. API measured 9059675 bytes versus the group checkpoint 8932704 bytes; increase its source budget to 9.15 MB. The accidental reader catalog import through newsletter defaults was removed: layout closure falls from 1.39 MB to 1.19 MB, retaining its 1.35 MB cap. Fresh sponsorship compile measures app handler 35515685 bytes and upload 37859574 bytes, versus group 34192236/36523328. Next server JS grows 1133659 bytes (25575680 to 26709339), of which node_modules basename-prefix chunks grow 15705 (7327681 to 7343386); no package was added. Added source, schemas, six-language copy, six public/owner page routes, editor snapshot block and client/server manifests account for the feature batch. Raise only app handler/upload to 35.8/38.15 MB with modest headroom; API/readers remain within 9.15/2.8 MB. All values measure local source size, not latency. Reader billing choices (2026-10-25) add nine creator actions, two dashboard/private reader routes, native Stripe pause/resume/save/cancel services and 46 six-language control/status phrases. Measured handler35878134 and upload38225032 bytes versus sponsorship35515685/37859574; dedicated feature source89991 bytes compiles in both Next layers. package.json and package-lock.json are byte-identical to the sponsorship checkpoint: no new dependency. API9147785 and readers2572927 stay within existing limits. Set only app handler/upload to36.15/38.50MB with modest room over this measured feature. Local source sizes do not measure production latency. Realtime collaboration adds six public private-editor actions and two dashboard-only ticket/checkpoint actions, a current-session/team/draft service authority and content-CAS fields. Early measured API9181978 versus reader-billing9147785 bytes; no Yjs, Tiptap or DOM parser enters the API. Set API9.30MB with modest room for the feature. The new optional collaboration Worker is separately measured1194343 bytes with a1.50MB budget; its native runtime tests use its compiled output. The first combined app compile measured handler36248885 and upload38599123, versus reader billing35878134/38225032: +370751/+374091 bytes for the collaborative client route, shared-schema checkpoint and private discussion code, schemas and manifests. The DOM parser remains in the separately bundled optional Worker; existing dashboard closure guards pass. Set app limits36.50/38.85MB with modest room; final verified bytes are recorded in docs/PERFORMANCE.md. Final handover after compatibility/copy/billing race followups measured handler36260231, upload38610476, API9186272, readers2575539 and optional collaboration1194911 bytes. All eight budgets pass; app full suite3470passed/0failed/3existing skips, plus12native passes. Final source-size evidence is local only. QA release fixes (2026-10-27) lower the budgets: the Cloud build (FLOCKSTACK_CLOUD_BUILD=true, set by scripts/deploy-all.mjs) replaces the S3, CloudFront and Vercel Blob clients with a stub and loads a narrowed mingo only where SQL cannot answer. Measured app handler 33267648 (from 36261626), upload 35572983 (from 38611873), API 8017027 (from 9187110), readers 2520388 (from 2575539). Limits are 33.6/35.95/8.15/2.65 MB; they only go down. The 2026-10-27 sprint wrap adds, on top of the QA size cuts, share buttons, custom headers, image crop and GIFs, random cohort sends, the tag filter and archive bulk action, held signups and private archives, Mailchimp import, gift links, the upsell template, per-issue schema and device split, and 17 registry actions. Measured app handler 33748560 and upload 36057862 versus the QA checkpoint 33267648/35572983 (+0.48 MB). No dependency was added. Limits are 34.0/36.3 MB, still about 2.3 MB under the build in production before the cuts. The optional briefings Worker (2026-10-28, docs/BRIEFINGS-DESIGN.md) is built like the readers Worker from workers/briefings/index.js: the engine in lib/briefings (66 KB), the shared docdb with its narrowed mingo (500 KB of the 608 KB), the AI key store and three models, no Next.js, React, SES or auth code. Measured 608225 bytes, the same in the Cloud and self-hosted builds; limit 0.75 MB (1.23 times) for the engine work still to come in its first runs. The same change adds the BriefingsDelivery entrypoint to the API Worker, loaded only on its first RPC call: lib/briefings-delivery.js is 4.5 KB of the API Worker, which measured 8139972 bytes in the Cloud build with the Briefings actions, under its unchanged 8.15 MB. Briefings (2026-10-28, main 4ffd4e0): the app measured handler 34273082 and upload 36590421 bytes, +524 KB and +533 KB on the sprint wrap. It is the Briefings registry actions and their schemas, AI keys, the briefing, run and AI key pages, the public verdict page and the briefings-bot docs page; the engine is not in the app (it runs in the briefings Worker; the hourly cron imports it only when self-hosted). No dependency was added. Limits 34.5/36.85 MB; trimming the Briefings schemas from the app bundle is the next size task. Subfolder hosting and briefing sections (2026-10-28, main 2e46231): handler 34614985 and upload 36946238 bytes, about +0.34 MB on the Briefings measurement: the mount actions, routing and HTMLRewriter step, the subfolder docs page with its five recipes, and the section editor and run tables. No dependency was added. Limits 34.75/37.1 MB. This is the second raise in a day: the next change to the app must take the Briefings and mount schemas and docs recipes out of the app handler (they are only needed by the API Worker and the public pages) before anything else is added. Mingo ESM (2026-10-28): every bundle now takes mingo's ESM build (scripts/mingo-esm.mjs), so its unused operators drop out: app handler 34,615,958 to 34,003,661 bytes, upload 36,947,202 to 36,125,410, API Worker 7,908,694 to 7,552,868, readers 2,252,348 to 1,898,736, briefings 749,241 to 396,140. Limits unchanged. This replaces the earlier note that Briefings and mount code must leave the app first: measured at about 0.31 MB, they cannot leave it without breaking the dashboard, self-hosting or the public pages render (docs/PERFORMANCE.md). Short chunk names (2026-10-28): scripts/short-chunk-names.mjs, after dedupe-chunks in the build command, gives every server chunk but the runtime and the [externals] chunks a base-36 name, so the 83,507 places the build names a chunk (the loaders' lists of nested async chunking, routes' entries, client reference manifests, OpenNext's modules and requireChunk) are shorter: app handler 34,243,892 to 30,716,983 bytes, upload 36,367,927 to 32,752,997. Nothing else changes (docs/PERFORMANCE.md). Limits unchanged, so the app has 4 MB of room again. SES account migration (2026-11-12): the already-shipped Anthropic/Groq main (#39, 71b69da) builds an 8,852,582-byte API Worker, above its stale 8,150,000-byte budget. The migration build is 8,827,410 bytes and adds no SDK. Reconcile only the API budget to 8,950,000 bytes, recording the existing provider cost rather than removing a shipped provider during an email migration.", "budgets": { "app-handler": { "label": "app handler.mjs (OpenNext)", @@ -16,8 +16,8 @@ "api-worker": { "label": "API Worker (workers/api/dist/index.js)", "file": "workers/api/dist/index.js", - "maxBytes": 8150000, - "measured": 8017027, + "maxBytes": 8950000, + "measured": 8827410, "build": "api" }, "readers-worker": {