diff --git a/.github/workflows/platform-deploy-staging.yml b/.github/workflows/platform-deploy-staging.yml index ed00db967..93bdcd999 100644 --- a/.github/workflows/platform-deploy-staging.yml +++ b/.github/workflows/platform-deploy-staging.yml @@ -63,6 +63,7 @@ jobs: CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} STAGING_DATABASE_URL: ${{ secrets.STAGING_DATABASE_URL }} + EMAIL_SIGNING_SECRET: ${{ secrets.EMAIL_SIGNING_SECRET }} smoke-test: if: ${{ vars.VOID_PLATFORM_DEPLOY_ENABLED == 'true' && github.ref == 'refs/heads/main' }} diff --git a/.github/workflows/platform-deploy.yml b/.github/workflows/platform-deploy.yml index b997d58f6..e7be65426 100644 --- a/.github/workflows/platform-deploy.yml +++ b/.github/workflows/platform-deploy.yml @@ -57,3 +57,4 @@ jobs: CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} DATABASE_URL: ${{ secrets.DATABASE_URL }} + EMAIL_SIGNING_SECRET: ${{ secrets.EMAIL_SIGNING_SECRET }} diff --git a/docs/guide/platform-development.md b/docs/guide/platform-development.md index c40677b4e..b9b5cba7a 100644 --- a/docs/guide/platform-development.md +++ b/docs/guide/platform-development.md @@ -231,7 +231,7 @@ node packages/void/dist/cli/cli.mjs platform upgrade "$VOID_PLATFORM_INSTALLATIO Omit the installation selector only if the account has one discoverable installation. Run one deployment per installation at a time, and let it finish before starting the next. Cancelling during migrations or Worker rollout can leave an installation waiting for recovery. -Keep the management token, database URL, JWT signing secret, and complete project-encryption keyring in a protected CI environment. Upgrades inherit deployed Worker secrets. The original values are needed when recreating a missing Worker; configuration credentials are also needed when explicitly rotating them. +Keep the management token, database URL, JWT signing secret, email signing secret for email-enabled installations, and complete project-encryption keyring in a protected CI environment. Upgrades inherit deployed Worker secrets. The original values are needed when recreating a missing Worker; configuration credentials are also needed when explicitly rotating them. ::: diff --git a/docs/guide/self-hosted-platform.md b/docs/guide/self-hosted-platform.md index 875d8d43c..d7502fd41 100644 --- a/docs/guide/self-hosted-platform.md +++ b/docs/guide/self-hosted-platform.md @@ -170,6 +170,8 @@ Paste it into your password manager as **JWT signing key**. Run the command agai ::: +When email is enabled, Void also creates an independent **Email signing key** for confirmation links and service-to-service email requests. The installer keeps it in encrypted recovery state. Set `VOID_PLATFORM_EMAIL_SIGNING_SECRET` to a separate value of at least 32 random bytes when you need an externally custodied copy, including a headless installation whose local recovery files will not persist. + ## 5. Install and Connect GitHub {#install} For workers.dev testing, start the interactive install and continue to the GitHub setup below: @@ -575,7 +577,7 @@ void platform discover --account --installation Discovery restores local installation records after verifying the resources belong to your platform. It also works for interrupted or disabled installations. If infrastructure is missing, run `void platform repair [id]` after discovery. If ownership cannot be verified, the command stops without changing resources. -After discovery, provide `VOID_PLATFORM_DATABASE_URL` for migrations and to coordinate administrator commands. You don't need to re-enter the other secrets for an upgrade that preserves every deployed Worker. If an upgrade adds the email gateway for the first time, or repair recreates only that Worker, restore `VOID_PLATFORM_JWT_SECRET`; the gateway does not need the Cloudflare runtime token. If repair must recreate the API or proxy Worker, restore `VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN` and `VOID_PLATFORM_JWT_SECRET`. Recreating the API also requires its original GitHub, R2, and project-encryption secrets through the `VOID_PLATFORM_*` variables. Cloudflare can't return those values, so keep them in your organization's secret manager. +After discovery, provide `VOID_PLATFORM_DATABASE_URL` for migrations and to coordinate administrator commands. You don't need to re-enter the other secrets for an upgrade that preserves every deployed Worker. For an email-enabled installation without its encrypted recovery file, restore `VOID_PLATFORM_EMAIL_SIGNING_SECRET`; recreating only the email gateway needs that key and no Cloudflare runtime token or JWT signing key. Recreating the API or proxy also requires the email key when email is enabled, in addition to their normal secrets. Recreating the API requires its original runtime token (`VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN`), GitHub, R2, JWT, and project-encryption values through the `VOID_PLATFORM_*` variables; recreating the proxy requires the runtime token and JWT signing key. Cloudflare can't return these values, so keep them in your organization's secret manager. If you have not rotated the project-encryption key, restore it with `VOID_PLATFORM_PROJECT_SECRET_KEY`. After rotation, supply `VOID_PLATFORM_PROJECT_SECRET_KEYS_JSON` with all retained keys and `VOID_PLATFORM_PROJECT_SECRET_ACTIVE_KEY_VERSION` with the active key's name. Keep older keys needed to decrypt existing project secrets. These values are used to recreate a missing API Worker; they do not replace the live keys during an ordinary upgrade. Supply them from your secret manager. @@ -586,7 +588,7 @@ If you have not rotated the project-encryption key, restore it with `VOID_PLATFO Keep a coordinated recovery set for each installation: - a PostgreSQL backup; -- the installation identity—the JWT signing secret and complete project-encryption keyring—in a secret manager; +- the installation identity—the JWT signing secret, the email signing secret when email is enabled, and the complete project-encryption keyring—in a secret manager; - provider-supported backups or exports for every data-bearing provider resource; - the immutable runtime artifacts and manifest for the installed version or custom source revision. @@ -598,7 +600,7 @@ During a restore, keep platform and application traffic disabled before changing Installation records live in `~/.void/platforms/`. Credentials are stored separately in encrypted recovery files, with the encryption key in your operating system's keychain. Keep your original secrets in a password manager for recovery on another machine. -If the keychain isn't available, Void stops before writing secrets. Headless environments can supply `VOID_PLATFORM_RECOVERY_KEY`: a canonical base64-encoded 32-byte key from a secret manager. A temporary CI runner can use a new recovery-encryption key for each run only when every original credential remains available in protected CI secrets, including `VOID_PLATFORM_JWT_SECRET` and either the original `VOID_PLATFORM_PROJECT_SECRET_KEY` or the complete rotated keyring and active-version pair. +If the keychain isn't available, Void stops before writing secrets. Headless environments can supply `VOID_PLATFORM_RECOVERY_KEY`: a canonical base64-encoded 32-byte key from a secret manager. A temporary CI runner can use a new recovery-encryption key for each run only when every original credential remains available in protected CI secrets, including `VOID_PLATFORM_JWT_SECRET`, `VOID_PLATFORM_EMAIL_SIGNING_SECRET` for an email-enabled installation, and either the original `VOID_PLATFORM_PROJECT_SECRET_KEY` or the complete rotated keyring and active-version pair. ::: details Ownership and interrupted maintenance @@ -627,6 +629,7 @@ Inject the following values from protected CI secrets. Do not commit them in a w | `VOID_PLATFORM_R2_ACCESS_KEY_ID` | R2 Access Key ID | | `VOID_PLATFORM_R2_SECRET_ACCESS_KEY` | R2 Secret Access Key | | `VOID_PLATFORM_JWT_SECRET` | Original JWT signing secret | +| `VOID_PLATFORM_EMAIL_SIGNING_SECRET` | Dedicated email signing secret when email is enabled | | `VOID_PLATFORM_PROJECT_SECRET_KEY` | Original base64-encoded project-encryption key | | `VOID_PLATFORM_RECOVERY_KEY` | Base64-encoded 32-byte key for local encrypted recovery state when no keychain is available | | `VOID_EMAIL_SENDER_DOMAIN` | Optional shared mail domain; requires `VOID_EMAIL_SHARED_ZONE_ID` | diff --git a/docs/reference/cli.md b/docs/reference/cli.md index bb7016652..c5646b181 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -762,7 +762,7 @@ void platform uninstall [id] [--plan] [--purge-data] [--keep-zone] [--yes] Omit `id` when only one installation is configured, or choose from the interactive picker. Non-interactive commands need an ID when several installations exist. Commands that make changes also require `--yes`; `--plan` only previews changes. -After discovery on another machine, set `VOID_PLATFORM_DATABASE_URL`. An upgrade that preserves every deployed Worker also preserves its secrets. If an upgrade adds the email gateway for the first time, or repair recreates only that Worker, restore `VOID_PLATFORM_JWT_SECRET`; the gateway does not need the Cloudflare runtime token. If repair recreates the API or proxy Worker, restore `VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN` and `VOID_PLATFORM_JWT_SECRET`. Recreating the API also requires its original GitHub, R2, and project-encryption values. +After discovery on another machine, set `VOID_PLATFORM_DATABASE_URL`. An upgrade that preserves every deployed Worker also preserves its secrets. For an email-enabled installation without its encrypted recovery file, restore `VOID_PLATFORM_EMAIL_SIGNING_SECRET`; recreating only the email gateway needs that key and does not need the Cloudflare runtime token or JWT signing key. Recreating the API or proxy also requires the email key when email is enabled, in addition to their normal secrets. Recreating the API requires its original runtime-token, GitHub, R2, JWT, and project-encryption values; recreating the proxy requires the runtime token and JWT signing key. | Command | Behavior | | ----------- | --------------------------------------------------------------------------------------------- | diff --git a/packages/platform/README.md b/packages/platform/README.md index d615e0983..1c59f5110 100644 --- a/packages/platform/README.md +++ b/packages/platform/README.md @@ -38,6 +38,8 @@ Interactive lifecycle operations authenticate the human operator through Cloudfl Fresh installations require a unique JWT signing secret with at least 32 bytes of random material and a unique, canonical base64-encoded 32-byte project-encryption key from the operator's durable secret manager. The installer never makes an ephemeral workstation or CI registry the only custodian of these installation identity keys. Existing Workers preserve their deployed values during routine lifecycle operations. +Email-enabled installations also need an independent email signing key. The installer generates it in encrypted recovery state, or accepts `VOID_PLATFORM_EMAIL_SIGNING_SECRET` from the operator's secret manager. Keep that original value for recovery on another machine and for headless upgrades without persistent recovery files. + Browser OAuth cannot manage AI Gateway. Installation previews mark an inaccessible gateway as requiring inspection; apply rechecks it with the already-required runtime token (AI Gateway: Edit) before provisioning. All other provider operations keep the operator credential. Later OAuth lifecycle operations can reuse that token from encrypted local recovery storage. On another workstation, use a management API token with AI Gateway access or supply the runtime token explicitly for that check. Runtime and installation manifests record the last usage protocol proven live across the complete Worker set. A protocol transition gates traffic before the first Worker update and opens it only after target health and immutable versions pass; interrupted transitions remain gated and resumable. diff --git a/packages/platform/src/email-protocol.ts b/packages/platform/src/email-protocol.ts index 5d7b5cd6e..3514db862 100644 --- a/packages/platform/src/email-protocol.ts +++ b/packages/platform/src/email-protocol.ts @@ -213,6 +213,9 @@ function unbase64url(value: string): Uint8Array { } async function receiptKey(secret: string, usage: 'sign' | 'verify'): Promise { + if (!secret) { + throw new Error('Email signing key is not configured'); + } return crypto.subtle.importKey( 'raw', encoder.encode(secret), diff --git a/packages/void/skills/void/SKILL.md b/packages/void/skills/void/SKILL.md index c6becccb0..401c5770f 100644 --- a/packages/void/skills/void/SKILL.md +++ b/packages/void/skills/void/SKILL.md @@ -89,7 +89,7 @@ Cloudflare browser login does not grant AI Gateway access. A platform installati Use `--runtime ` on platform install, upgrade, repair, enable, or rollback when deploying a locally built `@void/platform` runtime. The directory must contain the generated integrity manifest, Worker artifacts, and migration tree. Build it with `vp run --filter @void/platform build`; Git source revisions are detected automatically, with `-dirty` for uncommitted changes. `VOID_PLATFORM_SOURCE_REVISION` is an optional override. Do not treat this as a safety bypass: custom and packaged runtimes follow the same verification and rollback path. -For self-hosted platform installation, require a dedicated empty PostgreSQL database. Interactive lifecycle commands use Cloudflare browser OAuth with keyring storage. Wrangler OAuth has Zone Read, so a plan that creates a zone or DNS record requires a scoped `CLOUDFLARE_API_TOKEN` with Account → Zone → Edit and/or Zone → DNS → Edit; finish Workers onboarding and choose a workers.dev subdomain for a fresh Cloudflare account. The installed platform uses a separate `VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN`. Its core permissions include Hyperdrive: Write at account scope and Cache Purge: Purge on the application zone; SSL and Certificates: Edit is needed only when a custom runtime enables custom project domains. The installer preflights account and Hyperdrive access and safely verifies Cache Purge for an existing zone with a unique nonexistent URL. Fresh installs require unique per-installation values from the operator's secret manager: `VOID_PLATFORM_JWT_SECRET` with at least 32 random bytes and `VOID_PLATFORM_PROJECT_SECRET_KEY` as canonical base64 for 32 random bytes. Never let a local checkpoint or ephemeral CI runner be their only custodian. The installer transactionally claims the database for one installation, pins that URL after a successful claim, never removes the claim during uninstall, and uses it for a cross-host lifecycle lock plus a secret-free authoritative lifecycle manifest. Local recovery checkpoints are AES-256-GCM encrypted with an OS-keychain key; never place platform secrets in plaintext files. After discovery on a new machine, provide `VOID_PLATFORM_DATABASE_URL`. Normal upgrades preserve deployed Worker secrets; restoring the original runtime, GitHub, R2, JWT, and project-encryption values is required only when recreating a missing Worker. Managed platform Sandbox is paused for removal: preview `void platform system sandbox-drain --plan`, follow each returned `nextCursor` with `--cursor ''` to inspect bounded pages, then apply with `--yes` and rerun until the DB-backed response reports `complete: true`; never delete an unverified app by name. The installer trusts only DB-backed sandbox-drain probe protocol v1. Before it accepts an empty inventory, the database admission barrier makes older deployment inserts finish and become visible or rejects them after the protocol floor is armed. Lifecycle redeploys preserve unmanaged Worker routes and custom domains in both the new trigger state and rollback snapshot. They stop before migrations or uploads when live Hyperdrive origin metadata differs from the pinned database. Platform upgrade SQL is forward-only: packaged hashes and the live Drizzle prefix must match, pending migrations require an exact source-version/schema rollback edge, and the old version remains authoritative until target health succeeds. Use `void platform rollback --runtime ` only when the installed runtime declares the exact earlier version/schema compatible; pass `--from-runtime` for the exact current custom artifact. Rollback preserves the forward database schema and cannot lower a database-required safety protocol. Safe uninstall retains Worker routes, custom domains, and R2 for explicit manual cleanup because Cloudflare cannot condition their deletion on an immutable generation. +For self-hosted platform installation, require a dedicated empty PostgreSQL database. Interactive lifecycle commands use Cloudflare browser OAuth with keyring storage. Wrangler OAuth has Zone Read, so a plan that creates a zone or DNS record requires a scoped `CLOUDFLARE_API_TOKEN` with Account → Zone → Edit and/or Zone → DNS → Edit; finish Workers onboarding and choose a workers.dev subdomain for a fresh Cloudflare account. The installed platform uses a separate `VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN`. Its core permissions include Hyperdrive: Write at account scope and Cache Purge: Purge on the application zone; SSL and Certificates: Edit is needed only when a custom runtime enables custom project domains. The installer preflights account and Hyperdrive access and safely verifies Cache Purge for an existing zone with a unique nonexistent URL. Fresh installs require unique per-installation values from the operator's secret manager: `VOID_PLATFORM_JWT_SECRET` with at least 32 random bytes and `VOID_PLATFORM_PROJECT_SECRET_KEY` as canonical base64 for 32 random bytes. Never let a local checkpoint or ephemeral CI runner be their only custodian. Enabling email generates a separate signing key in encrypted recovery state; supply `VOID_PLATFORM_EMAIL_SIGNING_SECRET` from the secret manager for headless installs without persistent recovery files. The installer transactionally claims the database for one installation, pins that URL after a successful claim, never removes the claim during uninstall, and uses it for a cross-host lifecycle lock plus a secret-free authoritative lifecycle manifest. Local recovery checkpoints are AES-256-GCM encrypted with an OS-keychain key; never place platform secrets in plaintext files. After discovery on a new machine, provide `VOID_PLATFORM_DATABASE_URL`. For email-enabled installations without encrypted recovery state, also restore the original `VOID_PLATFORM_EMAIL_SIGNING_SECRET`; recreating only the email gateway needs this key, not JWT or runtime credentials. Normal upgrades preserve other deployed Worker secrets; restore the original runtime, GitHub, R2, JWT, and project-encryption values when recreating the API or proxy as documented. Managed platform Sandbox is paused for removal: preview `void platform system sandbox-drain --plan`, follow each returned `nextCursor` with `--cursor ''` to inspect bounded pages, then apply with `--yes` and rerun until the DB-backed response reports `complete: true`; never delete an unverified app by name. The installer trusts only DB-backed sandbox-drain probe protocol v1. Before it accepts an empty inventory, the database admission barrier makes older deployment inserts finish and become visible or rejects them after the protocol floor is armed. Lifecycle redeploys preserve unmanaged Worker routes and custom domains in both the new trigger state and rollback snapshot. They stop before migrations or uploads when live Hyperdrive origin metadata differs from the pinned database. Platform upgrade SQL is forward-only: packaged hashes and the live Drizzle prefix must match, pending migrations require an exact source-version/schema rollback edge, and the old version remains authoritative until target health succeeds. Use `void platform rollback --runtime ` only when the installed runtime declares the exact earlier version/schema compatible; pass `--from-runtime` for the exact current custom artifact. Rollback preserves the forward database schema and cannot lower a database-required safety protocol. Safe uninstall retains Worker routes, custom domains, and R2 for explicit manual cleanup because Cloudflare cannot condition their deletion on an immutable generation. For self-hosted recovery, `VOID_PLATFORM_PROJECT_SECRET_KEY` restores an original `v1` project-secret keyring. After rotation, restore every retained version with `VOID_PLATFORM_PROJECT_SECRET_KEYS_JSON` and its active entry with `VOID_PLATFORM_PROJECT_SECRET_ACTIVE_KEY_VERSION`. These inputs restore a missing API Worker and never replace the live keyring of an existing Worker. Inject them from a secret manager without logging them or writing plaintext files. diff --git a/packages/void/src/cli/platform-installer.ts b/packages/void/src/cli/platform-installer.ts index 5e469296d..f79746ade 100644 --- a/packages/void/src/cli/platform-installer.ts +++ b/packages/void/src/cli/platform-installer.ts @@ -110,6 +110,8 @@ export type PlatformInstallationSecrets = Readonly<{ bootstrapGitHubLogin: string; cloudflareApiToken: string; databaseUrl: string; + emailEnabled: boolean; + emailSigningSecret: string; githubClientId: string; githubClientSecret: string; jwtSecret: string; @@ -118,11 +120,12 @@ export type PlatformInstallationSecrets = Readonly<{ projectSecretKeysJson: string; r2AccessKeyId: string; r2SecretAccessKey: string; - /** Explicit configuration changes only; never populated from recovery data. */ + /** Explicitly authorized updates; recovered email identity remains authoritative. */ workerSecretUpdates?: Readonly< Partial< Record< | 'CF_API_TOKEN' + | 'EMAIL_SIGNING_SECRET' | 'GITHUB_CLIENT_ID' | 'GITHUB_CLIENT_SECRET' | 'R2_ACCESS_KEY_ID' @@ -137,6 +140,7 @@ export type PlatformInstallationSecrets = Readonly<{ const PLATFORM_WORKER_SECRET_UPDATE_NAMES = [ 'CF_API_TOKEN', + 'EMAIL_SIGNING_SECRET', 'GITHUB_CLIENT_ID', 'GITHUB_CLIENT_SECRET', 'R2_ACCESS_KEY_ID', @@ -369,6 +373,9 @@ export function createPlatformInstallationSecrets(input: { bootstrapGitHubLogin: string; cloudflareApiToken: string; databaseUrl: string; + emailEnabled?: boolean; + emailSigningSecret?: string; + existingEmailEnabled?: boolean; githubClientId: string; githubClientSecret: string; existingInstallation?: boolean; @@ -437,6 +444,34 @@ export function createPlatformInstallationSecrets(input: { 'platform: VOID_PLATFORM_JWT_SECRET must contain at least 32 bytes of secret material unique to this installation.', ); } + const emailEnabled = input.emailEnabled === true; + const existingEmailEnabled = input.existingEmailEnabled === true; + const emailSigningSecretInScope = emailEnabled || existingEmailEnabled; + let emailSigningSecret = emailSigningSecretInScope + ? restoredIdentity(input.emailSigningSecret || '', 'emailSigningSecret') + : checkpoint.emailSigningSecret || ''; + if (emailEnabled && !emailSigningSecret) { + if (existingInstallation && existingEmailEnabled) { + throw new Error( + 'platform: VOID_PLATFORM_EMAIL_SIGNING_SECRET is required to maintain an email-enabled installation without its encrypted recovery state.', + ); + } + emailSigningSecret = randomBytes(32).toString('base64'); + } + if ( + emailSigningSecretInScope && + emailSigningSecret && + Buffer.byteLength(emailSigningSecret, 'utf8') < 32 + ) { + throw new Error( + 'platform: VOID_PLATFORM_EMAIL_SIGNING_SECRET must contain at least 32 bytes of secret material unique to this installation.', + ); + } + if (emailSigningSecretInScope && emailSigningSecret && emailSigningSecret === resolvedJwtSecret) { + throw new Error( + 'platform: VOID_PLATFORM_EMAIL_SIGNING_SECRET must be different from VOID_PLATFORM_JWT_SECRET.', + ); + } const projectSecretKeyring = resolveProjectSecretKeyring({ checkpoint, existingInstallation, @@ -448,8 +483,14 @@ export function createPlatformInstallationSecrets(input: { const pendingWorkerSecretUpdateIntent = parseWorkerSecretUpdateIntent( checkpoint.workerSecretUpdatesJson, ); + const emailSigningSecretUpdateAuthorized = + emailSigningSecretInScope && + !!emailSigningSecret && + ((emailEnabled && (!existingEmailEnabled || !checkpoint.emailSigningSecret)) || + !!input.emailSigningSecret); const explicitWorkerSecretUpdates = withoutEmptySecrets({ CF_API_TOKEN: input.cloudflareApiToken, + ...(emailSigningSecretUpdateAuthorized ? { EMAIL_SIGNING_SECRET: emailSigningSecret } : {}), GITHUB_CLIENT_ID: input.githubClientId, GITHUB_CLIENT_SECRET: input.githubClientSecret, R2_ACCESS_KEY_ID: input.r2AccessKeyId, @@ -491,6 +532,8 @@ export function createPlatformInstallationSecrets(input: { 'VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN', ), databaseUrl: required(input.databaseUrl || checkpoint.databaseUrl || '', 'DATABASE_URL'), + emailEnabled, + emailSigningSecret, githubClientId: existingInstallation || modernAuthentication ? configured(input.githubClientId, 'githubClientId') @@ -675,6 +718,7 @@ function secretCheckpoint( githubClientId: secrets.githubClientId, githubClientSecret: secrets.githubClientSecret, jwtSecret: secrets.jwtSecret, + emailSigningSecret: secrets.emailSigningSecret, projectSecretActiveKeyVersion: secrets.projectSecretActiveKeyVersion, projectSecretKey: secrets.projectSecretKey, projectSecretKeysJson: secrets.projectSecretKeysJson, @@ -931,6 +975,8 @@ export async function installPlatform( explicitUpdates: explicitWorkerSecretUpdates, localIntent: secrets.pendingWorkerSecretUpdateIntent, manifest, + requiresEmailSigningSecret: + manifest.deployment.capabilities.email || plan.deployment.capabilities.email, }); } catch (error) { await releaseDatabaseLock(); @@ -2828,6 +2874,7 @@ export function apiWorkerSecrets( CF_ZONE_ID: zoneId, GITHUB_CLIENT_ID: secrets.githubClientId, GITHUB_CLIENT_SECRET: secrets.githubClientSecret, + ...(secrets.emailEnabled ? { EMAIL_SIGNING_SECRET: secrets.emailSigningSecret } : {}), JWT_SECRET: secrets.jwtSecret, PLATFORM_BOOTSTRAP_GITHUB_ID: secrets.bootstrapGitHubId, PLATFORM_AUTH_SETUP_TOKEN: secrets.authSetupToken ?? '', @@ -2858,23 +2905,26 @@ export function platformWorkerSecretPayload( return apiWorkerSecrets(secrets, accountId, zoneId); } if (worker === 'emailGateway') { - return withoutEmptySecrets({ JWT_SECRET: secrets.jwtSecret }); + const payload = withoutEmptySecrets({ + EMAIL_SIGNING_SECRET: secrets.emailEnabled ? secrets.emailSigningSecret : '', + }); + return Object.keys(payload).length > 0 ? payload : null; } return proxyWorkerSecrets(secrets, accountId); } - if (worker === 'emailGateway') { - return null; - } const allowed = worker === 'api' ? [ 'CF_API_TOKEN', + 'EMAIL_SIGNING_SECRET', 'GITHUB_CLIENT_ID', 'GITHUB_CLIENT_SECRET', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', ] - : ['CF_API_TOKEN']; + : worker === 'proxy' + ? ['CF_API_TOKEN', 'EMAIL_SIGNING_SECRET'] + : ['EMAIL_SIGNING_SECRET']; const updates = Object.fromEntries( Object.entries(secrets.workerSecretUpdates ?? {}).filter( ([name, value]) => allowed.includes(name) && typeof value === 'string' && value !== '', @@ -2924,6 +2974,7 @@ function proxyWorkerSecrets( return withoutEmptySecrets({ CF_ACCOUNT_ID: accountId, CF_API_TOKEN: secrets.cloudflareApiToken, + ...(secrets.emailEnabled ? { EMAIL_SIGNING_SECRET: secrets.emailSigningSecret } : {}), JWT_SECRET: secrets.jwtSecret, }); } @@ -2972,6 +3023,9 @@ export function assertRequiredPlatformSecrets( requireSecret(secrets.githubClientSecret, 'VOID_PLATFORM_GITHUB_CLIENT_SECRET'); } requireSecret(secrets.jwtSecret, 'VOID_PLATFORM_JWT_SECRET'); + if (plan.deployment.capabilities.email) { + requireSecret(secrets.emailSigningSecret, 'VOID_PLATFORM_EMAIL_SIGNING_SECRET'); + } requireSecret( secrets.projectSecretKeysJson, 'VOID_PLATFORM_PROJECT_SECRET_KEYS_JSON (or VOID_PLATFORM_PROJECT_SECRET_KEY for v1)', @@ -2991,6 +3045,9 @@ export function assertRequiredPlatformSecrets( ) { requireSecret(secrets.cloudflareApiToken, 'VOID_PLATFORM_RUNTIME_CLOUDFLARE_API_TOKEN'); requireSecret(secrets.jwtSecret, 'VOID_PLATFORM_JWT_SECRET'); + if (plan.deployment.capabilities.email) { + requireSecret(secrets.emailSigningSecret, 'VOID_PLATFORM_EMAIL_SIGNING_SECRET'); + } } if ( plan.actions.some( @@ -3000,7 +3057,9 @@ export function assertRequiredPlatformSecrets( action.action === 'create', ) ) { - requireSecret(secrets.jwtSecret, 'VOID_PLATFORM_JWT_SECRET'); + if (plan.deployment.capabilities.email) { + requireSecret(secrets.emailSigningSecret, 'VOID_PLATFORM_EMAIL_SIGNING_SECRET'); + } } if (missing.size > 0) { throw new Error( diff --git a/packages/void/src/cli/platform-lifecycle.ts b/packages/void/src/cli/platform-lifecycle.ts index 9b1f44f9b..f6ceab8d7 100644 --- a/packages/void/src/cli/platform-lifecycle.ts +++ b/packages/void/src/cli/platform-lifecycle.ts @@ -687,6 +687,9 @@ export async function runPlatformLifecycleCommand(args: PlatformArgs): Promise typeof updates[name] === 'string' && updates[name] !== '', +function hasCompleteWorkerSecretReplacement( + updates: WorkerSecretUpdates, + requiresEmailSigningSecret: boolean, +): boolean { + return ( + COMPLETE_WORKER_SECRET_UPDATE_NAMES.every( + (name) => typeof updates[name] === 'string' && updates[name] !== '', + ) && + (!requiresEmailSigningSecret || + (typeof updates[EMAIL_WORKER_SECRET_UPDATE_NAME] === 'string' && + updates[EMAIL_WORKER_SECRET_UPDATE_NAME] !== '')) ); } diff --git a/packages/void/test/unit/platform-installer.test.ts b/packages/void/test/unit/platform-installer.test.ts index e289fdd1a..9d713b47b 100644 --- a/packages/void/test/unit/platform-installer.test.ts +++ b/packages/void/test/unit/platform-installer.test.ts @@ -117,6 +117,7 @@ function installPlatform( }); } const TEST_PLATFORM_JWT_SECRET = 'test-only-platform-jwt-secret-material'; +const TEST_PLATFORM_EMAIL_SIGNING_SECRET = 'test-only-email-signing-secret-material'; const TEST_PLATFORM_PROJECT_SECRET_KEY = Buffer.alloc(32, 5).toString('base64'); function sandboxDrainPreparation(state: 'complete' | 'pending') { @@ -594,6 +595,7 @@ describe('platform installer', () => { bootstrapGitHubLogin: 'octocat', cloudflareApiToken: 'test-token', databaseUrl: 'postgres://user:password@db.example.com/email', + emailEnabled: true, githubClientId: 'id', githubClientSecret: 'secret', jwtSecret: TEST_PLATFORM_JWT_SECRET, @@ -720,6 +722,265 @@ describe('platform installer', () => { }); }); + it('generates and preserves a dedicated email signing key only for email installations', () => { + const freshInput = { + bootstrapGitHubId: '583231', + bootstrapGitHubLogin: 'octocat', + cloudflareApiToken: 'cf-token', + databaseUrl: 'postgres://user:password@db.example.com/void', + githubClientId: 'github-id', + githubClientSecret: 'github-secret', + jwtSecret: TEST_PLATFORM_JWT_SECRET, + projectSecretKey: TEST_PLATFORM_PROJECT_SECRET_KEY, + r2AccessKeyId: 'r2-id', + r2SecretAccessKey: 'r2-secret', + }; + const emailDisabled = createPlatformInstallationSecrets({ + ...freshInput, + emailSigningSecret: TEST_PLATFORM_EMAIL_SIGNING_SECRET, + }); + expect(emailDisabled.emailSigningSecret).toBe(''); + expect(apiWorkerSecrets(emailDisabled, 'account', 'zone')).not.toHaveProperty( + 'EMAIL_SIGNING_SECRET', + ); + expect( + platformWorkerSecretPayload('emailGateway', emailDisabled, 'account', 'zone', false), + ).toBeNull(); + const existingEmailDisabled = createPlatformInstallationSecrets({ + ...freshInput, + emailSigningSecret: TEST_PLATFORM_EMAIL_SIGNING_SECRET, + existingInstallation: true, + updateExistingWorkers: true, + }); + expect(existingEmailDisabled.emailSigningSecret).toBe(''); + expect(existingEmailDisabled.workerSecretUpdates).not.toHaveProperty('EMAIL_SIGNING_SECRET'); + + const freshEmail = createPlatformInstallationSecrets({ + ...freshInput, + emailEnabled: true, + }); + expect(Buffer.byteLength(freshEmail.emailSigningSecret, 'utf8')).toBeGreaterThanOrEqual(32); + expect(freshEmail.emailSigningSecret).not.toBe(TEST_PLATFORM_JWT_SECRET); + expect(apiWorkerSecrets(freshEmail, 'account', 'zone')).toHaveProperty( + 'EMAIL_SIGNING_SECRET', + freshEmail.emailSigningSecret, + ); + expect( + platformWorkerSecretPayload('proxy', freshEmail, 'account', 'zone', false), + ).toMatchObject({ + EMAIL_SIGNING_SECRET: freshEmail.emailSigningSecret, + JWT_SECRET: TEST_PLATFORM_JWT_SECRET, + }); + expect( + platformWorkerSecretPayload('emailGateway', freshEmail, 'account', 'zone', false), + ).toEqual({ EMAIL_SIGNING_SECRET: freshEmail.emailSigningSecret }); + + expect(() => + createPlatformInstallationSecrets({ + ...freshInput, + emailEnabled: true, + emailSigningSecret: TEST_PLATFORM_JWT_SECRET, + }), + ).toThrow('must be different from VOID_PLATFORM_JWT_SECRET'); + + const existingInput = { + ...freshInput, + existingInstallation: true, + emailEnabled: true, + existingEmailEnabled: true, + }; + expect(() => createPlatformInstallationSecrets(existingInput)).toThrow( + 'VOID_PLATFORM_EMAIL_SIGNING_SECRET is required', + ); + expect(() => + createPlatformInstallationSecrets({ + ...existingInput, + emailSigningSecret: 'short', + }), + ).toThrow('at least 32 bytes'); + expect(() => + createPlatformInstallationSecrets({ + ...existingInput, + checkpoint: { + jwtSecret: TEST_PLATFORM_JWT_SECRET, + emailSigningSecret: TEST_PLATFORM_JWT_SECRET, + }, + emailSigningSecret: TEST_PLATFORM_EMAIL_SIGNING_SECRET, + }), + ).toThrow('must be different from VOID_PLATFORM_JWT_SECRET'); + const restored = createPlatformInstallationSecrets({ + ...existingInput, + checkpoint: { emailSigningSecret: TEST_PLATFORM_EMAIL_SIGNING_SECRET }, + emailSigningSecret: 'wrong-email-signing-secret-that-must-not-win', + updateExistingWorkers: true, + }); + expect(restored.emailSigningSecret).toBe(TEST_PLATFORM_EMAIL_SIGNING_SECRET); + expect(restored.workerSecretUpdates).toEqual({ + CF_API_TOKEN: 'cf-token', + EMAIL_SIGNING_SECRET: TEST_PLATFORM_EMAIL_SIGNING_SECRET, + GITHUB_CLIENT_ID: 'github-id', + GITHUB_CLIENT_SECRET: 'github-secret', + R2_ACCESS_KEY_ID: 'r2-id', + R2_SECRET_ACCESS_KEY: 'r2-secret', + }); + expect(platformWorkerSecretPayload('api', restored, 'account', 'zone', true)).toEqual( + restored.workerSecretUpdates, + ); + expect(platformWorkerSecretPayload('proxy', restored, 'account', 'zone', true)).toEqual({ + CF_API_TOKEN: 'cf-token', + EMAIL_SIGNING_SECRET: TEST_PLATFORM_EMAIL_SIGNING_SECRET, + }); + expect(platformWorkerSecretPayload('emailGateway', restored, 'account', 'zone', true)).toEqual({ + EMAIL_SIGNING_SECRET: TEST_PLATFORM_EMAIL_SIGNING_SECRET, + }); + + const disabling = createPlatformInstallationSecrets({ + ...freshInput, + checkpoint: { emailSigningSecret: TEST_PLATFORM_EMAIL_SIGNING_SECRET }, + emailSigningSecret: 'replacement-signal-that-must-not-override-recovery', + existingInstallation: true, + existingEmailEnabled: true, + updateExistingWorkers: true, + }); + expect(disabling.emailSigningSecret).toBe(TEST_PLATFORM_EMAIL_SIGNING_SECRET); + expect(disabling.workerSecretUpdates).toHaveProperty( + 'EMAIL_SIGNING_SECRET', + TEST_PLATFORM_EMAIL_SIGNING_SECRET, + ); + expect(() => + createPlatformInstallationSecrets({ + ...freshInput, + checkpoint: { emailSigningSecret: 'short' }, + existingInstallation: true, + existingEmailEnabled: true, + }), + ).toThrow('at least 32 bytes'); + expect( + createPlatformInstallationSecrets({ + ...freshInput, + existingInstallation: true, + existingEmailEnabled: true, + }).emailSigningSecret, + ).toBe(''); + }); + + it('checkpoints a first-enable email key as a resumable Worker secret update', () => { + const secrets = createPlatformInstallationSecrets({ + bootstrapGitHubId: '', + bootstrapGitHubLogin: '', + cloudflareApiToken: '', + databaseUrl: 'postgres://user:password@db.example.com/void', + emailEnabled: true, + existingEmailEnabled: false, + existingInstallation: true, + githubClientId: '', + githubClientSecret: '', + jwtSecret: '', + projectSecretKey: '', + r2AccessKeyId: '', + r2SecretAccessKey: '', + updateExistingWorkers: true, + }); + expect(secrets.workerSecretUpdates).toEqual({ + EMAIL_SIGNING_SECRET: secrets.emailSigningSecret, + }); + for (const worker of ['api', 'proxy', 'emailGateway'] as const) { + expect(platformWorkerSecretPayload(worker, secrets, 'account', 'zone', true)).toEqual({ + EMAIL_SIGNING_SECRET: secrets.emailSigningSecret, + }); + } + }); + + it('does not let an email-disable plan bypass an unresolved email secret update', async () => { + const directory = mkdtempSync(join(tmpdir(), 'void-platform-email-secret-authority-test-')); + directories.push(directory); + process.env.VOID_PLATFORM_REGISTRY_DIR = directory; + const currentDeployment = createPlatformDeploymentManifest({ + application: { baseDomain: 'apps.example.com', zoneName: 'example.com' }, + capabilities: { email: true }, + displayName: 'Example', + emailSenderDomain: 'mail.example.com', + emailSharedZoneId: 'mail-zone', + installationSlug: 'example', + }); + let manifest = createPlatformInstallationManifest({ + account: { id: 'account', name: 'Account' }, + createdAt: '2026-09-20T00:00:00.000Z', + deployment: currentDeployment, + id: 'example-a1b2c3d4', + ownershipNonce: '0123456789abcdef0123456789abcdef', + platformVersion: '1.0.0', + }); + manifest = recordInstallationStep( + manifest, + { + completedAt: '2026-09-20T00:00:01.000Z', + key: 'worker-secret-updates:1:pending', + resultHash: 'foreign-email-intent', + }, + '2026-09-20T00:00:01.000Z', + ); + manifest = recordInstallationStep( + manifest, + { + completedAt: '2026-09-20T00:00:02.000Z', + key: 'worker-cutover:1:restored', + resultHash: 'restored', + }, + '2026-09-20T00:00:02.000Z', + ); + writeInstallationManifest(manifest); + const currentPlan = await createPlatformInstallPlan( + planningClient(), + { + accountId: 'account', + applicationDomain: 'apps.example.com', + controlPlaneDomain: '', + dedicatedZone: false, + displayName: 'Example', + installationSlug: 'example', + zoneName: 'example.com', + }, + manifest, + ); + const plan = { + ...currentPlan, + deployment: createPlatformDeploymentManifest({ + ...currentPlan.deployment, + capabilities: { ...currentPlan.deployment.capabilities, email: false }, + }), + }; + const secrets = createPlatformInstallationSecrets({ + bootstrapGitHubId: '583231', + bootstrapGitHubLogin: 'octocat', + checkpoint: { emailSigningSecret: TEST_PLATFORM_EMAIL_SIGNING_SECRET }, + cloudflareApiToken: 'cf-token', + databaseUrl: 'postgres://user:password@db.example.com/void', + existingEmailEnabled: true, + existingInstallation: true, + githubClientId: 'github-id', + githubClientSecret: 'github-secret', + jwtSecret: TEST_PLATFORM_JWT_SECRET, + projectSecretKey: TEST_PLATFORM_PROJECT_SECRET_KEY, + r2AccessKeyId: 'r2-id', + r2SecretAccessKey: 'r2-secret', + updateExistingWorkers: true, + }); + expect(secrets.workerSecretUpdates).not.toHaveProperty('EMAIL_SIGNING_SECRET'); + const deployWorker = vi.fn(); + + await expect( + installPlatform(plan, secrets, manifest, { + acquireDatabaseLifecycleLock, + claimDatabase, + client: {} as never, + deployWorker, + revalidateBeforeWorkerDeploy: async () => {}, + }), + ).rejects.toThrow('owned by another encrypted recovery checkpoint'); + expect(deployWorker).not.toHaveBeenCalled(); + }); + it('validates complete project-secret keyring restoration inputs', () => { const input = { bootstrapGitHubId: '583231', @@ -2502,6 +2763,8 @@ describe('platform installer', () => { controlPlaneDomain: '', dedicatedZone: false, displayName: 'Example', + emailSenderDomain: 'mail.example.com', + emailSharedZoneId: 'mail-zone', installationSlug: 'example', zoneName: 'example.com', }, @@ -2523,11 +2786,14 @@ describe('platform installer', () => { bootstrapGitHubLogin: 'octocat', cloudflareApiToken: 'cf-token', checkpoint: { + emailSigningSecret: TEST_PLATFORM_EMAIL_SIGNING_SECRET, projectSecretActiveKeyVersion: 'v1', projectSecretKey: TEST_PLATFORM_PROJECT_SECRET_KEY, projectSecretKeysJson: JSON.stringify({ v1: TEST_PLATFORM_PROJECT_SECRET_KEY }), }, databaseUrl: 'postgres://user:password@db.example.com/void', + emailEnabled: true, + existingEmailEnabled: true, existingInstallation: true, githubClientId: 'github-id', githubClientSecret: 'github-secret', @@ -2552,6 +2818,7 @@ describe('platform installer', () => { ).rejects.toThrow('stop after the encrypted checkpoint'); expect(readInstallationRecoverySecrets(manifest)).toMatchObject({ + emailSigningSecret: TEST_PLATFORM_EMAIL_SIGNING_SECRET, projectSecretActiveKeyVersion: 'v2', projectSecretKey: v1, projectSecretKeysJson: JSON.stringify({ v1, v2 }), @@ -2559,6 +2826,7 @@ describe('platform installer', () => { const envelope = readFileSync(join(directory, 'account', `${manifest.id}.secrets.enc`), 'utf8'); expect(envelope).not.toContain(v1); expect(envelope).not.toContain(v2); + expect(envelope).not.toContain(TEST_PLATFORM_EMAIL_SIGNING_SECRET); }); it("does not replay another workstation's stale recovery secrets during an upgrade", () => { @@ -2858,7 +3126,7 @@ describe('platform installer', () => { ); }); - it('recreates only the email gateway with its shared JWT and no Cloudflare token', async () => { + it('recreates only the email gateway with its email key and no JWT or Cloudflare token', async () => { const fullPlan = await createPlatformInstallPlan( planningClient(), { @@ -2867,6 +3135,8 @@ describe('platform installer', () => { controlPlaneDomain: '', dedicatedZone: false, displayName: 'Example', + emailSenderDomain: 'mail.example.com', + emailSharedZoneId: 'mail-zone', installationSlug: 'example', zoneName: 'example.com', }, @@ -2901,6 +3171,9 @@ describe('platform installer', () => { existingInstallation: true, githubClientId: '', githubClientSecret: '', + emailEnabled: true, + emailSigningSecret: TEST_PLATFORM_EMAIL_SIGNING_SECRET, + existingEmailEnabled: true, jwtSecret: TEST_PLATFORM_JWT_SECRET, r2AccessKeyId: '', r2SecretAccessKey: '', @@ -2908,7 +3181,7 @@ describe('platform installer', () => { expect(() => assertRequiredPlatformSecrets(plan, manifest, secrets)).not.toThrow(); expect(platformWorkerSecretPayload('emailGateway', secrets, 'account', 'zone', false)).toEqual({ - JWT_SECRET: TEST_PLATFORM_JWT_SECRET, + EMAIL_SIGNING_SECRET: TEST_PLATFORM_EMAIL_SIGNING_SECRET, }); expect( platformWorkerSecretPayload( @@ -2918,7 +3191,7 @@ describe('platform installer', () => { 'zone', false, ), - ).toEqual({ JWT_SECRET: TEST_PLATFORM_JWT_SECRET }); + ).toEqual({ EMAIL_SIGNING_SECRET: TEST_PLATFORM_EMAIL_SIGNING_SECRET }); expect( platformWorkerSecretPayload('emailGateway', secrets, 'account', 'zone', true), ).toBeNull(); diff --git a/packages/void/test/unit/platform-management-upgrade.test.ts b/packages/void/test/unit/platform-management-upgrade.test.ts index 25635790e..1b9139cfb 100644 --- a/packages/void/test/unit/platform-management-upgrade.test.ts +++ b/packages/void/test/unit/platform-management-upgrade.test.ts @@ -332,6 +332,36 @@ describe('installed platform upgrade', () => { expect(state.progress.start).toHaveBeenCalledWith('Repairing the platform'); }); + it('forwards the dedicated email key and recorded capability during maintenance', async () => { + const emailSigningSecret = 'restored-email-signing-secret-material'; + vi.stubEnv('VOID_PLATFORM_EMAIL_SIGNING_SECRET', emailSigningSecret); + state.manifest = { + ...state.manifest!, + deployment: createPlatformDeploymentManifest({ + ...state.manifest!.deployment, + capabilities: { ...state.manifest!.deployment.capabilities, email: true }, + emailSenderDomain: 'mail.example.com', + emailSharedZoneId: 'mail-zone', + }), + }; + + await runInstalledPlatformCommand({ + plan: false, + runtime: '', + selector: state.manifest.id, + subcommand: 'repair', + yes: true, + }); + + expect(state.createSecrets).toHaveBeenLastCalledWith( + expect.objectContaining({ + emailEnabled: true, + emailSigningSecret, + existingEmailEnabled: true, + }), + ); + }); + it('releases the held lifecycle lock when database preparation fails', async () => { state.prepareDatabase.mockImplementationOnce(async () => { state.events.push('prepare:failed'); diff --git a/packages/void/test/unit/platform-secret-update-authority.test.ts b/packages/void/test/unit/platform-secret-update-authority.test.ts index 43cc17662..491356a87 100644 --- a/packages/void/test/unit/platform-secret-update-authority.test.ts +++ b/packages/void/test/unit/platform-secret-update-authority.test.ts @@ -14,6 +14,11 @@ const completeReplacement = { R2_SECRET_ACCESS_KEY: 'new-r2-secret-access-key', }; +const completeEmailReplacement = { + ...completeReplacement, + EMAIL_SIGNING_SECRET: 'new-email-signing-secret', +}; + function manifestWithSteps(steps: ReadonlyArray>) { let manifest = createPlatformInstallationManifest({ account: { id: 'account', name: 'Account' }, @@ -51,6 +56,7 @@ describe('platform Worker secret update authority', () => { assertPlatformWorkerSecretUpdateAuthority({ explicitUpdates: { CF_API_TOKEN: 'partial-replacement' }, manifest, + requiresEmailSigningSecret: false, }), ).toThrow('owned by another encrypted recovery checkpoint'); }); @@ -66,6 +72,7 @@ describe('platform Worker secret update authority', () => { explicitUpdates: { CF_API_TOKEN: 'retry-override' }, localIntent: { generation: 1, id: 'intent-a' }, manifest, + requiresEmailSigningSecret: true, }), ).not.toThrow(); expect(() => @@ -73,6 +80,7 @@ describe('platform Worker secret update authority', () => { explicitUpdates: {}, localIntent: { generation: null, id: 'intent-a' }, manifest, + requiresEmailSigningSecret: true, }), ).not.toThrow(); }); @@ -87,6 +95,29 @@ describe('platform Worker secret update authority', () => { assertPlatformWorkerSecretUpdateAuthority({ explicitUpdates: completeReplacement, manifest, + requiresEmailSigningSecret: false, + }), + ).not.toThrow(); + }); + + it('requires the email key in a complete replacement for an email-enabled plan', () => { + const manifest = manifestWithSteps([ + { key: 'worker-secret-updates:1:pending', resultHash: 'intent-a' }, + { key: 'worker-cutover:1:restored', resultHash: 'restored' }, + ]); + + expect(() => + assertPlatformWorkerSecretUpdateAuthority({ + explicitUpdates: completeReplacement, + manifest, + requiresEmailSigningSecret: true, + }), + ).toThrow('owned by another encrypted recovery checkpoint'); + expect(() => + assertPlatformWorkerSecretUpdateAuthority({ + explicitUpdates: completeEmailReplacement, + manifest, + requiresEmailSigningSecret: true, }), ).not.toThrow(); }); @@ -103,6 +134,7 @@ describe('platform Worker secret update authority', () => { explicitUpdates: {}, localIntent: { generation: 1, id: 'intent-a' }, manifest, + requiresEmailSigningSecret: false, }), ).toThrow('owned by another encrypted recovery checkpoint'); expect(() => @@ -110,6 +142,7 @@ describe('platform Worker secret update authority', () => { explicitUpdates: completeReplacement, localIntent: { generation: 1, id: 'intent-a' }, manifest, + requiresEmailSigningSecret: false, }), ).not.toThrow(); }); @@ -126,10 +159,18 @@ describe('platform Worker secret update authority', () => { ]); expect(() => - assertPlatformWorkerSecretUpdateAuthority({ explicitUpdates: {}, manifest: committed }), + assertPlatformWorkerSecretUpdateAuthority({ + explicitUpdates: {}, + manifest: committed, + requiresEmailSigningSecret: true, + }), ).not.toThrow(); expect(() => - assertPlatformWorkerSecretUpdateAuthority({ explicitUpdates: {}, manifest: superseded }), + assertPlatformWorkerSecretUpdateAuthority({ + explicitUpdates: {}, + manifest: superseded, + requiresEmailSigningSecret: true, + }), ).not.toThrow(); }); }); diff --git a/packages/void/test/unit/platform-setup-flow.test.ts b/packages/void/test/unit/platform-setup-flow.test.ts index c132a5db5..cd6620600 100644 --- a/packages/void/test/unit/platform-setup-flow.test.ts +++ b/packages/void/test/unit/platform-setup-flow.test.ts @@ -138,6 +138,13 @@ beforeEach(() => { const deployment = createPlatformDeploymentManifest({ installationSlug: input.installationSlug, displayName: input.displayName, + ...(input.emailSharedZoneId && input.emailSenderDomain + ? { + capabilities: { email: true }, + emailSenderDomain: input.emailSenderDomain, + emailSharedZoneId: input.emailSharedZoneId, + } + : {}), application: { baseDomain: 'account.workers.dev', zoneName: '', @@ -886,6 +893,23 @@ describe('platform credential onboarding', () => { expect(mocks.install).toHaveBeenCalledOnce(); expect(info.mock.calls.map(([message]) => message).join('\n')).not.toContain('openssl rand'); }); + it('checkpoints a generated email key before leaving the setup draft', async () => { + for (const [key, value] of Object.entries(environment)) { + vi.stubEnv(key, value); + } + vi.stubEnv('VOID_EMAIL_SHARED_ZONE_ID', 'mail-zone'); + vi.stubEnv('VOID_EMAIL_SENDER_DOMAIN', 'mail.example.com'); + + await runPlatformLifecycleCommand(parsePlatformArgs(args)); + + const manifest = listInstallationManifests()[0]!; + const saved = readPendingInstallationSecrets(manifest)!; + const installSecrets = mocks.install.mock.calls[0]![1]; + expect(isPlatformSetupDraft(manifest)).toBe(false); + expect(saved.emailSigningSecret).toBe(installSecrets.emailSigningSecret); + expect(Buffer.byteLength(saved.emailSigningSecret, 'utf8')).toBeGreaterThanOrEqual(32); + expect(saved.emailSigningSecret).not.toBe(environment.VOID_PLATFORM_JWT_SECRET); + }); it('does not persist an invalid signing key or begin provisioning', async () => { const normal = mocks.password.getMockImplementation()!; mocks.password.mockImplementation(async (input) => diff --git a/platform/meta/design-docs/0078-email-cf-native.md b/platform/meta/design-docs/0078-email-cf-native.md index 999a48394..b79de89e8 100644 --- a/platform/meta/design-docs/0078-email-cf-native.md +++ b/platform/meta/design-docs/0078-email-cf-native.md @@ -181,6 +181,19 @@ first registered project is permitted. ### Trust and management scope +The platform API, proxy and gateway share a dedicated `EMAIL_SIGNING_SECRET` +for email request proofs, provider credential leases, tenant dispatch receipts +and recipient confirmation links. Login sessions and project authentication +continue to use `JWT_SECRET`; the gateway receives no login signing key. +Neither key is exposed to tenant Workers or customer ingress Workers. + +Generate the email key once per installation, preserve it in encrypted recovery +state and the operator's secret manager, and provision it with the first Worker +upload. Production and staging use different values. Missing keys fail closed; +there is no JWT fallback. Rotate the email key across all three services together; +outstanding email receipts and confirmation links then expire, while login +sessions remain valid. + An ingress credential authenticates one `(installation, account, zone, ingress)` identity, not a caller-supplied project ID. The gateway verifies that the exact recipient domain is active on that ingress and resolves its project from the @@ -685,6 +698,8 @@ is required for the first release. There are no production email users to migrate, so dual-running the old design and maintaining legacy email protocol compatibility are not release requirements. Development installations may be reset or explicitly converted as appropriate. +An explicit conversion must remove the gateway's obsolete `JWT_SECRET` binding +after the dedicated email-key cutover; preserve the API and proxy login keys. Any reset must account for real provider resources and credentials: inspect owned catch-all rules, retain unrelated mail configuration, clean up obsolete relays, and explicitly revoke unused test grants. Test shared and custom routes together diff --git a/platform/meta/lessons.md b/platform/meta/lessons.md index 75ef7ce2f..f2abdeac5 100644 --- a/platform/meta/lessons.md +++ b/platform/meta/lessons.md @@ -70,6 +70,9 @@ ## Cloudflare and deployment +- Preflight shared secrets before migrations or Worker changes, and upload them + with a new Worker's first deployment. An existing staging secret does not + prove that first-production bootstrap works. - Install CommonJS interoperability on the actual Worker build environment, whose name comes from Wrangler rather than a presumed `ssr` name. - Analytics Engine queries include timestamps used in filtering/sorting, use diff --git a/platform/meta/operations.md b/platform/meta/operations.md index 838c6d777..6e656487f 100644 --- a/platform/meta/operations.md +++ b/platform/meta/operations.md @@ -73,7 +73,8 @@ Keep these values recoverable through the deployment owner's secret manager: | Configuration | Purpose | | ------------------------------------------------------------------------------------- | --------------------------------------------------------------- | | `CF_API_TOKEN`, `CF_ACCOUNT_ID`, `CF_ZONE_ID` | Runtime Cloudflare account and application-zone access | -| `JWT_SECRET` | API, proxy, and email gateway authentication | +| `JWT_SECRET` | API sessions and API/proxy platform authentication | +| `EMAIL_SIGNING_SECRET` | Email request proofs, receipts, and confirmation tokens | | `PROJECT_SECRET_KEYS_JSON`, `PROJECT_SECRET_ACTIVE_KEY_VERSION` | Encryption of project secrets | | `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET` | GitHub sign-in OAuth application | | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | Google sign-in OAuth client | @@ -84,7 +85,7 @@ Keep these values recoverable through the deployment owner's secret manager: The project-secret keyring is a JSON object mapping key versions to base64-encoded 32-byte keys. The active version must exist in that object. Preserve older keys while any stored secret still uses them; losing a key makes those secrets unreadable. Database backups alone do not contain the decryption keys. -The API and proxy share their JWT signing configuration. Change it as a coordinated operation because existing sessions and remote-binding clients depend on it. Inspect the Worker bindings and application configuration before rotating any shared credential. +The API and proxy share their JWT signing configuration. Change it as a coordinated operation because existing sessions and remote-binding clients depend on it. Email uses a separate signing secret shared by the API, proxy, and email gateway. Keep stable, distinct values for production and staging, and rotate each shared credential independently as a coordinated operation. Inspect the Worker bindings and application configuration before rotating either one. ## GitHub Deployment Integration @@ -113,15 +114,9 @@ For repository deployments, add the equivalent values to the selected `env.produ - API, proxy, and email gateway: the same `EMAIL_SENDER_DOMAIN`. - API and email gateway: `EMAIL_SHARED_ACCOUNT_ID`, `EMAIL_SHARED_ZONE_ID`, and `EMAIL_SHARED_INGRESS_NAME`, identifying the platform account, mail zone, and dedicated gateway Worker. - API: `EMAIL_GATEWAY_ORIGIN`, the gateway's HTTPS origin reachable from customer ingress Workers. -- API, proxy, and email gateway: the same installation `JWT_SECRET`; the API retains the scoped runtime token and project-encryption keys. +- API, proxy, and email gateway: the same installation `EMAIL_SIGNING_SECRET`; the API retains its separate `JWT_SECRET`, scoped runtime token, and project-encryption keys. -Install the gateway's copy of the shared JWT as a Wrangler secret in each environment before deploying it: - -```sh -cd platform/packages/email-gateway -wrangler secret put JWT_SECRET --env production -wrangler secret put JWT_SECRET --env staging -``` +Store one stable, high-entropy `EMAIL_SIGNING_SECRET` in each deployment owner's secret manager and in the corresponding `Prod` or `Staging` GitHub environment. The hosted deployment preflight rejects a missing, short, or whitespace-padded value before database migrations or Worker changes. API, proxy, and gateway deployments upload the selected environment's value as an encrypted Worker secret, including when the gateway is created for the first time. Do not generate a new value for each deployment or put it in Wrangler `vars`. For the first email rollout, configure and deploy the proxy and email gateway before adding the API's shared-email values. Verify both Workers, then add the API values and deploy the API so scheduled reconciliation cannot direct inbound mail at an unavailable gateway. From the repository root, the production sequence is: @@ -133,6 +128,8 @@ vp run --filter @voidcloud/platform deploy:api Use the corresponding `deploy:staging:*` commands for staging. After email is enabled and all three Workers exist, the normal platform deployment command can update them. +A dedicated-key cutover has no compatibility bridge to the previous JWT-backed email protocol. Provision the same environment-specific `EMAIL_SIGNING_SECRET` for all three deployments, keep inbound routing disabled, and complete the gateway, proxy, and API rollout before enabling email traffic. Preserve `JWT_SECRET` on the API and proxy: login sessions and non-email authentication still depend on it. After cutover, remove a previous gateway's `JWT_SECRET` binding because Worker deployments preserve existing secrets. If a rollout stops between Workers, leave routing disabled and resume with the same email signing value. + The API's scheduled reconciliation creates the shared connection and reserved shared-domain route only when the complete identity is configured. Confirm the resulting operation and inbound readiness before directing traffic to the gateway. Provision routing and Sending independently: a provider permission or plan refusal must remain visible in the corresponding readiness state. Sending to arbitrary recipients requires Cloudflare Email Sending onboarding and its supported plan. Customer connections deploy one ingress Worker in the customer's account and zone. Shared and custom domain assignments can coexist on one zone. Setup proves the deployed ingress secret and the gateway's acceptance before changing the owned catch-all. Inspect foreign rules and preserve them; never repoint a catch-all simply because its Worker name resembles Void's. diff --git a/platform/package.json b/platform/package.json index ebe9fedc3..266f07f3f 100644 --- a/platform/package.json +++ b/platform/package.json @@ -5,14 +5,14 @@ "scripts": { "build": "vp run --filter @voidcloud/dashboard build", "check": "vp run -r --parallel typecheck", - "deploy": "vp run deploy:api && vp run deploy:proxy && vp run deploy:email-gateway && vp run deploy:tail && vp run deploy:dispatch && vp run deploy:dashboard", - "deploy:api": "vp run --filter @voidcloud/api migrate && vp run --filter @voidcloud/api deploy --env production", + "deploy": "node scripts/wrangler-deploy.ts --preflight --env production && vp run deploy:api && vp run deploy:proxy && vp run deploy:email-gateway && vp run deploy:tail && vp run deploy:dispatch && vp run deploy:dashboard", + "deploy:api": "node scripts/wrangler-deploy.ts --preflight --env production && vp run --filter @voidcloud/api migrate && vp run --filter @voidcloud/api deploy --env production", "deploy:dashboard": "vp run --filter @voidcloud/dashboard deploy --env production", "deploy:dispatch": "vp run --filter @voidcloud/dispatch deploy --env production", "deploy:email-gateway": "vp run --filter @voidcloud/email-gateway deploy --env production", "deploy:proxy": "vp run --filter @voidcloud/proxy deploy --env production", - "deploy:staging": "vp run deploy:staging:api && vp run deploy:staging:proxy && vp run deploy:staging:email-gateway && vp run deploy:staging:tail && vp run deploy:staging:dispatch && vp run deploy:staging:dashboard", - "deploy:staging:api": "vp run --filter @voidcloud/api migrate:staging && vp run --filter @voidcloud/api deploy --env staging", + "deploy:staging": "node scripts/wrangler-deploy.ts --preflight --env staging && vp run deploy:staging:api && vp run deploy:staging:proxy && vp run deploy:staging:email-gateway && vp run deploy:staging:tail && vp run deploy:staging:dispatch && vp run deploy:staging:dashboard", + "deploy:staging:api": "node scripts/wrangler-deploy.ts --preflight --env staging && vp run --filter @voidcloud/api migrate:staging && vp run --filter @voidcloud/api deploy --env staging", "deploy:staging:dashboard": "vp run --filter @voidcloud/dashboard deploy --env staging", "deploy:staging:dispatch": "vp run --filter @voidcloud/dispatch deploy --env staging", "deploy:staging:email-gateway": "vp run --filter @voidcloud/email-gateway deploy --env staging", diff --git a/platform/packages/api/README.md b/platform/packages/api/README.md index 7fabb1bb8..d4620d95a 100644 --- a/platform/packages/api/README.md +++ b/platform/packages/api/README.md @@ -344,6 +344,7 @@ Secrets used at runtime: - `CF_ACCOUNT_ID` - `CF_ZONE_ID` - `JWT_SECRET` +- `EMAIL_SIGNING_SECRET` (email-enabled installations) - `PROJECT_SECRET_KEYS_JSON` - `PROJECT_SECRET_ACTIVE_KEY_VERSION` - `GITHUB_CLIENT_ID` diff --git a/platform/packages/api/scripts/setup-local.ts b/platform/packages/api/scripts/setup-local.ts index 954f6f730..3683b18de 100644 --- a/platform/packages/api/scripts/setup-local.ts +++ b/platform/packages/api/scripts/setup-local.ts @@ -141,6 +141,7 @@ function ensureLocalDevVars(): void { DEV_AUTH_BYPASS: 'true', PLATFORM_ENV: 'staging', JWT_SECRET: 'dev', + EMAIL_SIGNING_SECRET: 'dev-email-signing-key-not-for-production', CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE: localDbUrl, }; const devVarsDirs = [platformDir, resolve(platformDir, '../dashboard')]; diff --git a/platform/packages/api/src/auth/confirm-token.ts b/platform/packages/api/src/auth/confirm-token.ts index 3edf118a4..09595fb8d 100644 --- a/platform/packages/api/src/auth/confirm-token.ts +++ b/platform/packages/api/src/auth/confirm-token.ts @@ -89,6 +89,9 @@ export async function signConfirmToken( payload: ConfirmTokenPayload, secret: string, ): Promise { + if (!secret) { + throw new Error('Email signing key is not configured'); + } const json = JSON.stringify(payload); const jsonBytes = encoder.encode(json); const headerPart = base64urlEncode(jsonBytes); @@ -108,7 +111,7 @@ export async function verifyConfirmToken( secret: string, now: number = Math.floor(Date.now() / 1000), ): Promise { - if (typeof token !== 'string' || !token.includes('.')) { + if (!secret || typeof token !== 'string' || !token.includes('.')) { return null; } const parts = token.split('.'); diff --git a/platform/packages/api/src/email/ingress-resolution.ts b/platform/packages/api/src/email/ingress-resolution.ts index 465df364e..be3946cf0 100644 --- a/platform/packages/api/src/email/ingress-resolution.ts +++ b/platform/packages/api/src/email/ingress-resolution.ts @@ -60,7 +60,11 @@ app.post('/probe-ingress', async (context) => { } const signed = `email-probe-v1\n${accountId}\n${zoneId}\n${ingressName}`; const auth = context.req.header('x-void-internal'); - if (!auth || !(await hmacVerifyState(signed, auth, context.env.JWT_SECRET))) { + if ( + !context.env.EMAIL_SIGNING_SECRET || + !auth || + !(await hmacVerifyState(signed, auth, context.env.EMAIL_SIGNING_SECRET)) + ) { return context.json({ error: 'forbidden' }, 403); } const connection = ( @@ -134,7 +138,11 @@ app.post('/resolve-ingress', async (context) => { const recipient = (to as string).toLowerCase(); const signed = `email-ingress-v1\n${accountId}\n${zoneId}\n${ingressName}\n${recipient}`; const auth = context.req.header('x-void-internal'); - if (!auth || !(await hmacVerifyState(signed, auth, context.env.JWT_SECRET))) { + if ( + !context.env.EMAIL_SIGNING_SECRET || + !auth || + !(await hmacVerifyState(signed, auth, context.env.EMAIL_SIGNING_SECRET)) + ) { return context.json({ error: 'forbidden' }, 403); } const db = context.get('db'); diff --git a/platform/packages/api/src/env.ts b/platform/packages/api/src/env.ts index 32eabe3a1..38dd512e6 100644 --- a/platform/packages/api/src/env.ts +++ b/platform/packages/api/src/env.ts @@ -34,6 +34,7 @@ export type ApiEnv = Env & { CF_ZONE_ID: string; AI_GATEWAY_ID?: string; JWT_SECRET: string; + EMAIL_SIGNING_SECRET: string; EMAIL_GATEWAY_ORIGIN?: string; EMAIL_SHARED_ACCOUNT_ID?: string; EMAIL_SHARED_ZONE_ID?: string; diff --git a/platform/packages/api/src/routes/email-confirm.ts b/platform/packages/api/src/routes/email-confirm.ts index e50d79d09..86a7d68c2 100644 --- a/platform/packages/api/src/routes/email-confirm.ts +++ b/platform/packages/api/src/routes/email-confirm.ts @@ -2,7 +2,7 @@ * Token-authenticated endpoint for the platform-side destination verification * link. The HMAC-signed token IS the auth — it * embeds (project_id, destination_id, address, exp) and is validated - * against JWT_SECRET. Single-use is enforced by DB state: the click + * against EMAIL_SIGNING_SECRET. Single-use is enforced by DB state: the click * flips the destination row to 'verified', so a second click finds an * already-verified row and returns idempotent success. * @@ -37,7 +37,7 @@ app.get('/destinations/confirm', async (context) => { return context.html(errorPage('Missing confirmation token.'), 400); } - const payload = await verifyConfirmToken(token, context.env.JWT_SECRET); + const payload = await verifyConfirmToken(token, context.env.EMAIL_SIGNING_SECRET); if (!payload) { // Don't distinguish bad signature vs expired vs malformed in the // user-visible page — they're all "this link no longer works". diff --git a/platform/packages/api/src/routes/email.ts b/platform/packages/api/src/routes/email.ts index feb86d4b1..df98005b1 100644 --- a/platform/packages/api/src/routes/email.ts +++ b/platform/packages/api/src/routes/email.ts @@ -731,7 +731,7 @@ async function dispatchPlatformVerification( iat: now, exp: now + 24 * 60 * 60, }; - const token = await signConfirmToken(tokenPayload, context.env.JWT_SECRET); + const token = await signConfirmToken(tokenPayload, context.env.EMAIL_SIGNING_SECRET); const sendPromise = sendPlatformVerificationEmail( context.env, { id: project.id, slug: project.slug }, diff --git a/platform/packages/api/src/routes/internal-email-actions.ts b/platform/packages/api/src/routes/internal-email-actions.ts index 156a7f28a..8933509de 100644 --- a/platform/packages/api/src/routes/internal-email-actions.ts +++ b/platform/packages/api/src/routes/internal-email-actions.ts @@ -82,7 +82,10 @@ app.use('*', async (context, next) => { } catch { return context.json({ error: 'invalid body' }, 400); } - if (!(await hmacVerifyState(raw, signature, context.env.JWT_SECRET))) { + if ( + !context.env.EMAIL_SIGNING_SECRET || + !(await hmacVerifyState(raw, signature, context.env.EMAIL_SIGNING_SECRET)) + ) { return context.json({ error: 'invalid internal auth' }, 403); } let body: unknown; diff --git a/platform/packages/api/src/routes/internal-email.ts b/platform/packages/api/src/routes/internal-email.ts index 6a26b896b..69fbf6526 100644 --- a/platform/packages/api/src/routes/internal-email.ts +++ b/platform/packages/api/src/routes/internal-email.ts @@ -44,11 +44,12 @@ app.post('/', async (context) => { const normalized = normalizeEmailDomain(domain); const signature = context.req.header('x-void-internal'); if ( + !context.env.EMAIL_SIGNING_SECRET || !signature || !(await hmacVerifyState( `email-lease-v1\n${projectId}\n${normalized}`, signature, - context.env.JWT_SECRET, + context.env.EMAIL_SIGNING_SECRET, )) ) { return context.json({ error: 'forbidden' }, 403); diff --git a/platform/packages/api/test/integration/api-email-domains.test.ts b/platform/packages/api/test/integration/api-email-domains.test.ts index ee9813119..0b78c5118 100644 --- a/platform/packages/api/test/integration/api-email-domains.test.ts +++ b/platform/packages/api/test/integration/api-email-domains.test.ts @@ -21,7 +21,7 @@ import { clearTables, createTestProject, createTestUser, - JWT_SECRET, + EMAIL_SIGNING_SECRET, setupEnv, teardownEnv, type TestEnv, @@ -320,7 +320,7 @@ describe('project email domain authority', () => { 'Content-Type': 'application/json', 'x-void-internal': await hmacSignState( `email-lease-v1\n${projectId}\n${signatureDomain}`, - JWT_SECRET, + EMAIL_SIGNING_SECRET, ), }, body: JSON.stringify({ domain, projectId }), @@ -338,7 +338,7 @@ describe('project email domain authority', () => { expect((await lease(project.id, 'lease.example.com', 'other.example.com')).status).toBe(403); const signed = await hmacSignState( `email-lease-v1\n${project.id}\nlease.example.com`, - JWT_SECRET, + EMAIL_SIGNING_SECRET, ); const oversized = await app.fetch( new Request('http://localhost/internal/email/domain-credential', { diff --git a/platform/packages/api/test/integration/api-email.test.ts b/platform/packages/api/test/integration/api-email.test.ts index 54dcd6f1b..c9e3504dc 100644 --- a/platform/packages/api/test/integration/api-email.test.ts +++ b/platform/packages/api/test/integration/api-email.test.ts @@ -1726,7 +1726,7 @@ describe('GET /email/destinations/confirm', () => { iat: overrides.iat ?? now, exp: overrides.exp ?? now + 24 * 60 * 60, }, - env.JWT_SECRET, + env.EMAIL_SIGNING_SECRET, ); } @@ -1802,14 +1802,14 @@ describe('GET /email/destinations/confirm', () => { expect(res.status).toBe(400); }); - it('returns 400 for a token signed with the wrong secret', async () => { + it('rejects a confirmation signed with the login key', async () => { const user = await createTestUser(env.db); const project = await createTestProject(env.db, user.id); const did = await seedPlatformPending('shared@example.com', project); const now = Math.floor(Date.now() / 1000); const forged = await signConfirmToken( { v: 1, pid: project.id, did, addr: 'shared@example.com', iat: now, exp: now + 3600 }, - 'not-the-platform-secret', + env.JWT_SECRET, ); const res = await confirm(forged); @@ -2267,7 +2267,7 @@ describe('email platform capability', () => { iat: now, exp: now + 3600, }, - env.JWT_SECRET, + env.EMAIL_SIGNING_SECRET, ); const res = await app.fetch( diff --git a/platform/packages/api/test/integration/email-connections.test.ts b/platform/packages/api/test/integration/email-connections.test.ts index 4a5a8bb70..05304f2a3 100644 --- a/platform/packages/api/test/integration/email-connections.test.ts +++ b/platform/packages/api/test/integration/email-connections.test.ts @@ -117,7 +117,7 @@ describe('durable zone email connections', () => { const to = 'support@limits.example.com'; const proof = await hmacSignState( `email-ingress-v1\n${connection.account_id}\n${connection.zone_id}\n${connection.ingress_worker_name}\n${to}`, - env.JWT_SECRET, + env.EMAIL_SIGNING_SECRET, ); const response = await app.fetch( new Request('https://api/internal/email/resolve-ingress', { diff --git a/platform/packages/api/test/integration/helpers.ts b/platform/packages/api/test/integration/helpers.ts index fdfe608a7..c1df4bdb8 100644 --- a/platform/packages/api/test/integration/helpers.ts +++ b/platform/packages/api/test/integration/helpers.ts @@ -37,6 +37,7 @@ import { loadPGliteTemplateBundle } from './db-template.ts'; import { setTestDb, clearTestDb } from './setup.ts'; export const JWT_SECRET = 'test-jwt-secret'; +export const EMAIL_SIGNING_SECRET = 'test-email-signing-secret-independent'; export const CF_API_TOKEN = 'test-cf-token'; export const CF_ACCOUNT_ID = 'test-account-id'; export const CF_ZONE_ID = 'test-zone-id'; @@ -59,6 +60,7 @@ export type TestEnv = { CF_ACCOUNT_ID: string; CF_ZONE_ID: string; JWT_SECRET: string; + EMAIL_SIGNING_SECRET: string; PLATFORM_AUTH_DATABASE_UNCACHED: string; PROJECT_SECRET_KEYS_JSON: string; PROJECT_SECRET_ACTIVE_KEY_VERSION: string; @@ -463,6 +465,7 @@ export async function setupEnv(): Promise { CF_ACCOUNT_ID, CF_ZONE_ID, JWT_SECRET, + EMAIL_SIGNING_SECRET, PLATFORM_AUTH_DATABASE_UNCACHED: 'true', PROJECT_SECRET_KEYS_JSON, PROJECT_SECRET_ACTIVE_KEY_VERSION, diff --git a/platform/packages/api/test/integration/platform-access-protection.test.ts b/platform/packages/api/test/integration/platform-access-protection.test.ts index dfb9ce643..3d3f64c24 100644 --- a/platform/packages/api/test/integration/platform-access-protection.test.ts +++ b/platform/packages/api/test/integration/platform-access-protection.test.ts @@ -189,7 +189,7 @@ describe('Access-protected platform requests', () => { await env.db .insert(emailReceipts) .values({ id: receipt.receiptId, project_id: project.id, status: 'received' }); - const proof = await hmacSignState(JSON.stringify(receipt), env.JWT_SECRET); + const proof = await hmacSignState(JSON.stringify(receipt), env.EMAIL_SIGNING_SECRET); const accepted = await request( '/internal/email/actions/receipts', undefined, @@ -224,7 +224,7 @@ describe('Access-protected platform requests', () => { undefined, undefined, body, - { 'x-void-internal': await hmacSignState(payload, env.JWT_SECRET) }, + { 'x-void-internal': await hmacSignState(payload, env.EMAIL_SIGNING_SECRET) }, ); expect(response.status).toBe(404); } diff --git a/platform/packages/api/test/integration/scheduled.test.ts b/platform/packages/api/test/integration/scheduled.test.ts index 6acef4dd5..027f7d7cc 100644 --- a/platform/packages/api/test/integration/scheduled.test.ts +++ b/platform/packages/api/test/integration/scheduled.test.ts @@ -31,6 +31,7 @@ function makeBindings(e: TestEnv) { CF_ACCOUNT_ID: e.CF_ACCOUNT_ID, CF_ZONE_ID: e.CF_ZONE_ID, JWT_SECRET: e.JWT_SECRET, + EMAIL_SIGNING_SECRET: e.EMAIL_SIGNING_SECRET, PROJECT_SECRET_KEYS_JSON: e.PROJECT_SECRET_KEYS_JSON, PROJECT_SECRET_ACTIVE_KEY_VERSION: e.PROJECT_SECRET_ACTIVE_KEY_VERSION, R2_ACCESS_KEY_ID: e.R2_ACCESS_KEY_ID, diff --git a/platform/packages/api/test/unit/email-actions-request.test.ts b/platform/packages/api/test/unit/email-actions-request.test.ts index 253a4d525..9e9201447 100644 --- a/platform/packages/api/test/unit/email-actions-request.test.ts +++ b/platform/packages/api/test/unit/email-actions-request.test.ts @@ -1,7 +1,29 @@ import { describe, expect, it, vi } from 'vite-plus/test'; +import { hmacSignState } from '../../src/auth/hmac.ts'; import emailActions from '../../src/routes/internal-email-actions.ts'; describe('internal email action request bounds', () => { + it('authenticates actions with the email key and rejects the login key', async () => { + const bindings = { JWT_SECRET: 'login-key', EMAIL_SIGNING_SECRET: 'email-key' }; + const raw = '{}'; + const call = async (signingKey: string, emailKey = bindings.EMAIL_SIGNING_SECRET) => + emailActions.request( + '/admit', + { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-void-internal': await hmacSignState(raw, signingKey), + }, + body: raw, + }, + { ...bindings, EMAIL_SIGNING_SECRET: emailKey }, + ); + expect((await call(bindings.EMAIL_SIGNING_SECRET)).status).toBe(400); + expect((await call(bindings.JWT_SECRET)).status).toBe(403); + expect((await call(bindings.JWT_SECRET, '')).status).toBe(403); + }); + it('times out a stalled body without awaiting its cancellation', async () => { vi.useFakeTimers(); try { diff --git a/platform/packages/api/test/unit/email-verification.test.ts b/platform/packages/api/test/unit/email-verification.test.ts index 85e9b8615..6dc21ca1f 100644 --- a/platform/packages/api/test/unit/email-verification.test.ts +++ b/platform/packages/api/test/unit/email-verification.test.ts @@ -142,7 +142,7 @@ function verificationEnv(overrides: Partial = {}) { }); return { env: { - JWT_SECRET: SECRET, + EMAIL_SIGNING_SECRET: SECRET, EMAIL: { send } as unknown as SendEmail, EMAIL_SENDER_DOMAIN: MAIL_DOMAIN, EMAIL_GATEWAY_ORIGIN: GATEWAY_ORIGIN, diff --git a/platform/packages/api/wrangler.jsonc b/platform/packages/api/wrangler.jsonc index 3eb61e04f..2135fc537 100644 --- a/platform/packages/api/wrangler.jsonc +++ b/platform/packages/api/wrangler.jsonc @@ -183,7 +183,7 @@ // R2Bucket object but not its name, and the presigner needs the name. "R2_STATIC_ASSETS_BUCKET": "void-static-assets-overflow", }, - // Secrets (via `wrangler secret put`): CF_API_TOKEN, CF_ACCOUNT_ID, CF_ZONE_ID, JWT_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY + // Encrypted Worker secrets: CF_API_TOKEN, CF_ACCOUNT_ID, CF_ZONE_ID, JWT_SECRET, EMAIL_SIGNING_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY // R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY are S3-compatible API tokens used to presign direct-to-R2 asset uploads (see src/r2-presign.ts). // Optional env var: AUTH_REDIRECT_URI (defaults to https://api.void.cloud/auth/callback) // For local dev, set AUTH_REDIRECT_URI=http://localhost:8787/auth/callback and DEV_AUTH_BYPASS=true in .dev.vars @@ -191,6 +191,7 @@ "env": { "production": { "name": "void-api", + "secrets": { "required": ["EMAIL_SIGNING_SECRET"] }, "hyperdrive": [ { "binding": "HYPERDRIVE", @@ -326,6 +327,7 @@ }, "staging": { "name": "void-api-staging", + "secrets": { "required": ["EMAIL_SIGNING_SECRET"] }, "hyperdrive": [ { "binding": "HYPERDRIVE", diff --git a/platform/packages/email-gateway/src/index.ts b/platform/packages/email-gateway/src/index.ts index 44a648a29..5e213803f 100644 --- a/platform/packages/email-gateway/src/index.ts +++ b/platform/packages/email-gateway/src/index.ts @@ -8,7 +8,7 @@ import { import type { EmailEnvelope } from '../../proxy/src/email-router.ts'; import type { Env as ProxyEnv } from '../../proxy/src/types.ts'; -type Env = ProxyEnv & { +type Env = Omit & { PLATFORM_INSTALLATION_ID?: string; PLATFORM_VERSION?: string; PLATFORM_TRAFFIC_STATE?: string; @@ -51,6 +51,9 @@ async function withDeliverySlot(run: () => Promise): Promise { } async function sign(value: string, secret: string): Promise { + if (!secret) { + throw new Error('Email signing key is not configured'); + } const key = await crypto.subtle.importKey( 'raw', encoder.encode(secret), @@ -118,7 +121,7 @@ async function resolveIngress( }; const proof = await sign( `email-ingress-v1\n${input.accountId}\n${input.zoneId}\n${input.ingressName}\n${input.to.toLowerCase()}`, - env.JWT_SECRET, + env.EMAIL_SIGNING_SECRET, ); const response = await beforeDeadline(() => env.API.fetch('https://api/internal/email/resolve-ingress', { @@ -545,7 +548,7 @@ async function probe(request: Request, env: Env): Promise { } const proof = await sign( `email-probe-v1\n${accountId}\n${zoneId}\n${ingressName}`, - env.JWT_SECRET, + env.EMAIL_SIGNING_SECRET, ); const controller = new AbortController(); const apiDeadline = Date.now() + 5_000; diff --git a/platform/packages/email-gateway/src/tenant-dispatch.ts b/platform/packages/email-gateway/src/tenant-dispatch.ts index 284144c78..a7fe3854f 100644 --- a/platform/packages/email-gateway/src/tenant-dispatch.ts +++ b/platform/packages/email-gateway/src/tenant-dispatch.ts @@ -15,7 +15,7 @@ const active = new Map(); export async function dispatchBoundedEmailToTenant( stub: Pick, - env: { JWT_SECRET: string }, + env: { EMAIL_SIGNING_SECRET: string }, input: { projectId: string; deploymentId: string; @@ -48,7 +48,7 @@ export async function dispatchBoundedEmailToTenant( recipient: input.envelope.to, expiresAt: Date.now() + 30_000, }, - env.JWT_SECRET, + env.EMAIL_SIGNING_SECRET, ); const remaining = deadline - Date.now(); if (remaining <= 0) { diff --git a/platform/packages/email-gateway/test/unit/gateway.test.ts b/platform/packages/email-gateway/test/unit/gateway.test.ts index be9a0d493..ad487a75d 100644 --- a/platform/packages/email-gateway/test/unit/gateway.test.ts +++ b/platform/packages/email-gateway/test/unit/gateway.test.ts @@ -36,7 +36,7 @@ const env = ( dispatchGet: (...args: Array) => Fetcher = () => ({ fetch: vi.fn() }) as never, ) => ({ - JWT_SECRET: 'platform-secret', + EMAIL_SIGNING_SECRET: 'platform-secret', API: { fetch: apiFetch }, EMAIL_SHARED_ACCOUNT_ID: 'account-1', EMAIL_SHARED_ZONE_ID: 'zone-1', diff --git a/platform/packages/email-gateway/test/unit/tenant-dispatch.test.ts b/platform/packages/email-gateway/test/unit/tenant-dispatch.test.ts index 3cf45df2e..7f33da09c 100644 --- a/platform/packages/email-gateway/test/unit/tenant-dispatch.test.ts +++ b/platform/packages/email-gateway/test/unit/tenant-dispatch.test.ts @@ -19,7 +19,7 @@ describe('bounded tenant email dispatch', () => { }; const pending = dispatchBoundedEmailToTenant( stub as never, - { JWT_SECRET: 'secret' }, + { EMAIL_SIGNING_SECRET: 'secret' }, { projectId: 'project-1', deploymentId: 'deployment-1', diff --git a/platform/packages/email-gateway/wrangler.jsonc b/platform/packages/email-gateway/wrangler.jsonc index deee79fe6..d4e457328 100644 --- a/platform/packages/email-gateway/wrangler.jsonc +++ b/platform/packages/email-gateway/wrangler.jsonc @@ -18,7 +18,7 @@ "production": { "name": "void-email-gateway", "workers_dev": true, - "secrets": { "required": ["JWT_SECRET"] }, + "secrets": { "required": ["EMAIL_SIGNING_SECRET"] }, "services": [{ "binding": "API", "service": "void-api" }], "dispatch_namespaces": [{ "binding": "DISPATCH", "namespace": "void-users" }], "kv_namespaces": [{ "binding": "ROUTING", "id": "9250c33f3db6494ebe8ad6272812c8c0" }], @@ -33,7 +33,7 @@ "staging": { "name": "void-email-gateway-staging", "workers_dev": true, - "secrets": { "required": ["JWT_SECRET"] }, + "secrets": { "required": ["EMAIL_SIGNING_SECRET"] }, "services": [{ "binding": "API", "service": "void-api-staging" }], "dispatch_namespaces": [{ "binding": "DISPATCH", "namespace": "void-users-staging" }], "kv_namespaces": [{ "binding": "ROUTING", "id": "60240eecea804f39bf8b7395cd6c6b08" }], diff --git a/platform/packages/proxy/README.md b/platform/packages/proxy/README.md index dab6c6f8c..6793a3e86 100644 --- a/platform/packages/proxy/README.md +++ b/platform/packages/proxy/README.md @@ -134,16 +134,17 @@ test/unit/ ## Bindings -| Binding | Type | Purpose | -| --------------- | ------------------ | ------------------------------------------------------ | -| `AI` | Workers AI | Real inference binding | -| `API` | Service binding | Internal API calls (`revalidate`, resource resolution) | -| `DISPATCH` | Dispatch namespace | Fast path to deployed user workers | -| `ROUTING` | KV | AI limit flags, routing blobs, email allowlists/quotas | -| `SEND_EMAIL` | send_email | Account-level outbound mail | -| `JWT_SECRET` | Secret | HMAC/JWT verification | -| `CF_ACCOUNT_ID` | Secret | Cloudflare account ID | -| `CF_API_TOKEN` | Secret | Fallback REST API access | +| Binding | Type | Purpose | +| ---------------------- | ------------------ | ------------------------------------------------------ | +| `AI` | Workers AI | Real inference binding | +| `API` | Service binding | Internal API calls (`revalidate`, resource resolution) | +| `DISPATCH` | Dispatch namespace | Fast path to deployed user workers | +| `ROUTING` | KV | AI limit flags, routing blobs, email allowlists/quotas | +| `SEND_EMAIL` | send_email | Account-level outbound mail | +| `JWT_SECRET` | Secret | HMAC/JWT verification | +| `EMAIL_SIGNING_SECRET` | Secret | Email request proofs, credential leases, and receipts | +| `CF_ACCOUNT_ID` | Secret | Cloudflare account ID | +| `CF_API_TOKEN` | Secret | Fallback REST API access | | Var | Purpose | | --------------------- | --------------------------------------------------------- | diff --git a/platform/packages/proxy/src/email-admission.ts b/platform/packages/proxy/src/email-admission.ts index 7a0c87bf9..5d8e2748c 100644 --- a/platform/packages/proxy/src/email-admission.ts +++ b/platform/packages/proxy/src/email-admission.ts @@ -28,6 +28,9 @@ const EMAIL_ADMISSION_DEADLINE_MS = 15_000; const MAX_ADMISSION_RESPONSE_BYTES = 65_536; async function sign(data: string, secret: string): Promise { + if (!secret) { + throw new Error('Email signing key is not configured'); + } const key = await crypto.subtle.importKey( 'raw', encoder.encode(secret), @@ -43,7 +46,7 @@ async function sign(data: string, secret: string): Promise { } async function call( - env: Pick, + env: Pick, path: string, body: unknown, deadlineMs = EMAIL_DEFAULT_DEADLINE_MS, @@ -75,7 +78,7 @@ async function call( } }; const raw = JSON.stringify(body); - const proof = await sign(raw, env.JWT_SECRET); + const proof = await sign(raw, env.EMAIL_SIGNING_SECRET); const response = await beforeDeadline(() => env.API.fetch(`https://api/internal/email/actions${path}`, { method: 'POST', @@ -140,14 +143,14 @@ export type ReceiptRouteFence = { }; export function claimRelayedReceipt( - env: Pick, + env: Pick, identity: RelayedReceiptIdentity, ): Promise<{ state: 'claimed' | 'in_progress' | 'completed'; reject?: boolean }> { return call(env, '/receipts/claim', identity); } export function completeRelayedReceipt( - env: Pick, + env: Pick, identity: RelayedReceiptIdentity, reject: boolean, ): Promise<{ ok: true }> { @@ -356,7 +359,7 @@ export async function emailPayloadDigest( } export function admitEmail( - env: Pick, + env: Pick, body: { projectId: string; kind: 'direct' | 'forward' | 'reply'; @@ -373,7 +376,7 @@ export function admitEmail( } export function startEmailAttempt( - env: Pick, + env: Pick, operationId: string, recipients: Array, deadlineMs = EMAIL_ACTION_DEADLINE_MS, @@ -387,7 +390,7 @@ export function startEmailAttempt( } export function finishEmailAttempt( - env: Pick, + env: Pick, operationId: string, recipients: Array, state: 'provider_accepted' | 'failed' | 'outcome_unknown' | 'cancelled', @@ -403,7 +406,7 @@ export function finishEmailAttempt( } export function recordEmailReceipt( - env: Pick, + env: Pick, receiptId: string, projectId: string, status: string, diff --git a/platform/packages/proxy/src/email-lease.ts b/platform/packages/proxy/src/email-lease.ts index 2e07515d8..ab022b433 100644 --- a/platform/packages/proxy/src/email-lease.ts +++ b/platform/packages/proxy/src/email-lease.ts @@ -17,11 +17,14 @@ export function leaseBearer(lease: EmailDomainLease): string { * null on any failure; the caller maps that to a retryable upstream error. */ export async function leaseEmailDomainCredential( - env: Pick, + env: Pick, domain: string, projectId: string, deadlineMs = LEASE_DEADLINE_MS, ): Promise { + if (!env.EMAIL_SIGNING_SECRET) { + return null; + } const controller = new AbortController(); const deadline = Date.now() + Math.min(deadlineMs, LEASE_DEADLINE_MS); const beforeDeadline = async (run: () => Promise): Promise => { @@ -53,7 +56,7 @@ export async function leaseEmailDomainCredential( try { const token = await hmacSign( `email-lease-v1\n${projectId}\n${domain.toLowerCase()}`, - env.JWT_SECRET, + env.EMAIL_SIGNING_SECRET, ); res = await beforeDeadline(() => env.API.fetch('https://api/internal/email/domain-credential', { diff --git a/platform/packages/proxy/src/email-router.ts b/platform/packages/proxy/src/email-router.ts index 955be7369..032287520 100644 --- a/platform/packages/proxy/src/email-router.ts +++ b/platform/packages/proxy/src/email-router.ts @@ -26,7 +26,8 @@ import { recordInboundDelivery, requestSendRaw, } from './email.ts'; -import type { Env } from './types.ts'; +import type { Env as ProxyEnv } from './types.ts'; +type Env = Omit; // Built via new RegExp to dodge oxlint no-control-regex rule. // oxlint-disable-next-line no-control-regex diff --git a/platform/packages/proxy/src/email.ts b/platform/packages/proxy/src/email.ts index 5d6c2e566..e0fe55d3a 100644 --- a/platform/packages/proxy/src/email.ts +++ b/platform/packages/proxy/src/email.ts @@ -1605,7 +1605,7 @@ interface RecipientResult { * it only from `reserved`; a committed `attempt_started` transition conflicts. */ async function cancelUnstartedRecipients( - env: Pick, + env: Pick, operationId: string, recipients: Array, deadlineMs?: number, diff --git a/platform/packages/proxy/src/index.ts b/platform/packages/proxy/src/index.ts index 6b7fbe54f..507b9114c 100644 --- a/platform/packages/proxy/src/index.ts +++ b/platform/packages/proxy/src/index.ts @@ -87,7 +87,7 @@ async function hmacSign(data: string, secret: string): Promise { return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); } -// The tenant calls this over its internal service binding. JWT_SECRET never +// The tenant calls this over its internal service binding. EMAIL_SIGNING_SECRET never // enters the tenant, so a project token cannot mint a gateway receipt. app.post('/email/verify-receipt', async (context) => { let body: unknown; @@ -116,7 +116,10 @@ app.post('/email/verify-receipt', async (context) => { if (context.req.header('x-void-internal') !== projectToken) { return context.json({ valid: false }, 403); } - const claims = await verifyEmailReceipt(input.receipt, context.env.JWT_SECRET, { + if (!context.env.EMAIL_SIGNING_SECRET) { + return context.json({ valid: false }, 503); + } + const claims = await verifyEmailReceipt(input.receipt, context.env.EMAIL_SIGNING_SECRET, { projectId: input.projectId, deploymentId: input.deploymentId, recipient: input.recipient, diff --git a/platform/packages/proxy/src/types.ts b/platform/packages/proxy/src/types.ts index 508d876e1..115291a5b 100644 --- a/platform/packages/proxy/src/types.ts +++ b/platform/packages/proxy/src/types.ts @@ -37,6 +37,7 @@ export type Env = Readonly<{ AI: AiBinding; AI_GATEWAY_ID?: string; JWT_SECRET: string; + EMAIL_SIGNING_SECRET: string; ROUTING: KVNamespace; CF_ACCOUNT_ID: string; diff --git a/platform/packages/proxy/test/unit/email-admission-send.test.ts b/platform/packages/proxy/test/unit/email-admission-send.test.ts index d6b7c5b9a..95bdbc520 100644 --- a/platform/packages/proxy/test/unit/email-admission-send.test.ts +++ b/platform/packages/proxy/test/unit/email-admission-send.test.ts @@ -88,7 +88,7 @@ function fixture() { const sender = vi.fn(async () => ({ messageId: 'provider-1' })); const env = { API: { fetch: apiFetch }, - JWT_SECRET: 'test-secret', + EMAIL_SIGNING_SECRET: 'test-secret', SEND_EMAIL: { send: sender }, EMAIL_SENDER_DOMAIN: 'mail.example.com', ROUTING: { get: vi.fn() }, diff --git a/platform/packages/proxy/test/unit/email-admission.test.ts b/platform/packages/proxy/test/unit/email-admission.test.ts index e57de2665..d4efc3f78 100644 --- a/platform/packages/proxy/test/unit/email-admission.test.ts +++ b/platform/packages/proxy/test/unit/email-admission.test.ts @@ -230,7 +230,7 @@ describe('email admission service deadline', () => { }); }); const pending = admitEmail( - { API: { fetch } as never, JWT_SECRET: 'secret' }, + { API: { fetch } as never, EMAIL_SIGNING_SECRET: 'secret' }, { projectId: 'project_1', kind: 'direct', @@ -276,7 +276,7 @@ describe('email admission service deadline', () => { }), ); const pending = finishEmailAttempt( - { API: { fetch } as never, JWT_SECRET: 'secret' }, + { API: { fetch } as never, EMAIL_SIGNING_SECRET: 'secret' }, 'emailact_1', ['recipient@example.com'], 'provider_accepted', @@ -298,7 +298,7 @@ describe('email admission service deadline', () => { try { const fetch = vi.fn(() => new Promise(() => {})); const pending = admitEmail( - { API: { fetch } as never, JWT_SECRET: 'secret' }, + { API: { fetch } as never, EMAIL_SIGNING_SECRET: 'secret' }, { projectId: 'project_1', kind: 'direct', diff --git a/platform/packages/proxy/test/unit/email-custom-domain.test.ts b/platform/packages/proxy/test/unit/email-custom-domain.test.ts index 72943cd78..ab4b6802c 100644 --- a/platform/packages/proxy/test/unit/email-custom-domain.test.ts +++ b/platform/packages/proxy/test/unit/email-custom-domain.test.ts @@ -18,6 +18,7 @@ const worker = (await import('../../src/index.ts')).default; const { requestSendRaw } = await import('../../src/email.ts'); const JWT_SECRET = 'test-secret-key'; +const EMAIL_SIGNING_SECRET = 'test-email-signing-key-independent'; const PROD_DOMAIN = 'mail.void.cloud'; const CUSTOM_DOMAIN = 'acme.com'; const CUSTOM_FROM = `support@${CUSTOM_DOMAIN}`; @@ -123,6 +124,7 @@ function createMockEnv() { const env = { AI: {}, JWT_SECRET, + EMAIL_SIGNING_SECRET, ROUTING: { get: vi.fn(async () => null) }, CF_ACCOUNT_ID: 'acct', CF_API_TOKEN: 'cf-token', @@ -273,7 +275,7 @@ describe('POST /email/send — custom sender domain', () => { }); const leaseHeaders = new Headers(leaseInit.headers); expect(leaseHeaders.get('x-void-internal')).toBe( - await signHmac(`email-lease-v1\nproj_1\n${CUSTOM_DOMAIN}`, JWT_SECRET), + await signHmac(`email-lease-v1\nproj_1\n${CUSTOM_DOMAIN}`, EMAIL_SIGNING_SECRET), ); // The delivery: one POST to the CUSTOMER account's send_raw, leased diff --git a/platform/packages/proxy/test/unit/email-router.test.ts b/platform/packages/proxy/test/unit/email-router.test.ts index 11974ff89..91822cafa 100644 --- a/platform/packages/proxy/test/unit/email-router.test.ts +++ b/platform/packages/proxy/test/unit/email-router.test.ts @@ -285,7 +285,7 @@ function makeEnv(options: MakeEnvOptions = {}) { }); const env = { AI: {}, - JWT_SECRET: 'test-secret', + EMAIL_SIGNING_SECRET: 'test-secret', CF_ACCOUNT_ID: 'acct', CF_API_TOKEN: 'token', API: { fetch: apiFetch }, diff --git a/platform/packages/proxy/test/unit/email.test.ts b/platform/packages/proxy/test/unit/email.test.ts index b4401684c..4041feedf 100644 --- a/platform/packages/proxy/test/unit/email.test.ts +++ b/platform/packages/proxy/test/unit/email.test.ts @@ -25,6 +25,7 @@ const { buildMime, normalizeEmail } = await import('../../../../../packages/void/src/runtime/email/mime.ts'); const JWT_SECRET = 'test-secret-key'; +const EMAIL_SIGNING_SECRET = 'test-email-signing-key-independent'; const PROD_DOMAIN = 'mail.void.cloud'; const STAGING_DOMAIN = 'mail.voidcloud.dev'; @@ -140,6 +141,7 @@ function createMockEnv( return { AI: {}, JWT_SECRET, + EMAIL_SIGNING_SECRET, ROUTING: kv, CF_ACCOUNT_ID: 'acct', CF_API_TOKEN: 'cf-token', @@ -369,14 +371,17 @@ describe('proxy wrangler config', () => { expect(gatewayVars.EMAIL_SHARED_INGRESS_NAME).toBe(gateway.name); expect(proxy.services).toContainEqual({ binding: 'API', service: scope.name }); expect(gateway.services).toContainEqual({ binding: 'API', service: scope.name }); + if (name !== 'top level') { + expect(scope.secrets).toEqual({ required: ['EMAIL_SIGNING_SECRET'] }); + expect(proxy.secrets).toEqual({ required: ['EMAIL_SIGNING_SECRET'] }); + expect(gateway.secrets).toEqual({ required: ['EMAIL_SIGNING_SECRET'] }); + } } const productionVars = env.production.vars as Record; const stagingVars = env.staging.vars as Record; expect(stagingVars.EMAIL_SHARED_ACCOUNT_ID).toBe(productionVars.EMAIL_SHARED_ACCOUNT_ID); expect(stagingVars.EMAIL_SHARED_ZONE_ID).not.toBe(productionVars.EMAIL_SHARED_ZONE_ID); expect(stagingVars.EMAIL_SENDER_DOMAIN).not.toBe(productionVars.EMAIL_SENDER_DOMAIN); - expect(gatewayEnv.production.secrets).toEqual({ required: ['JWT_SECRET'] }); - expect(gatewayEnv.staging.secrets).toEqual({ required: ['JWT_SECRET'] }); }); }); diff --git a/platform/packages/proxy/test/unit/proxy.test.ts b/platform/packages/proxy/test/unit/proxy.test.ts index 890b7205e..505c95ed8 100644 --- a/platform/packages/proxy/test/unit/proxy.test.ts +++ b/platform/packages/proxy/test/unit/proxy.test.ts @@ -1,9 +1,11 @@ +import { signEmailReceipt } from '@void/platform/email-protocol'; import { describe, it, expect, vi, beforeAll, afterEach } from 'vite-plus/test'; import { readEmailRequestJson } from '../../src/email-request-body.ts'; import worker from '../../src/index.ts'; import { PLATFORM_DISABLED_KEY } from '../../src/platform-lifecycle.ts'; const JWT_SECRET = 'test-secret-key'; +const EMAIL_SIGNING_SECRET = 'test-email-signing-key-independent'; // --- JWT helper (mirrors the worker's HMAC-SHA256 signing) --- @@ -144,6 +146,7 @@ function createEnv( ...aiOverrides, }, JWT_SECRET, + EMAIL_SIGNING_SECRET, ROUTING: createMockKv(kvData), CF_ACCOUNT_ID: 'test-account-id', CF_API_TOKEN: 'test-api-token', @@ -413,6 +416,38 @@ describe('proxy worker', () => { }); }); + it('verifies email receipts independently of project login authentication', async () => { + const claims = { + version: 1 as const, + receiptId: 'a'.repeat(64), + projectId: 'proj_1', + deploymentId: 'deploy_1', + recipient: 'support@example.com', + expiresAt: Date.now() + 30_000, + }; + const projectToken = await signAiToken(claims.projectId, JWT_SECRET); + const call = async (receiptKey: string, auth = projectToken, env = createEnv()) => + worker.fetch( + post( + '/email/verify-receipt', + { ...claims, receipt: await signEmailReceipt(claims, receiptKey) }, + { 'x-void-internal': auth }, + ), + env, + ); + expect(await (await call(EMAIL_SIGNING_SECRET)).json()).toEqual({ + valid: true, + receiptId: claims.receiptId, + }); + expect(await (await call(JWT_SECRET)).json()).toEqual({ valid: false }); + expect( + (await call(EMAIL_SIGNING_SECRET, await signAiToken(claims.projectId, EMAIL_SIGNING_SECRET))) + .status, + ).toBe(403); + const missing = { ...createEnv(), EMAIL_SIGNING_SECRET: '' }; + expect((await call(JWT_SECRET, projectToken, missing)).status).toBe(503); + }); + describe('JWT authentication (HTTPS path)', () => { it('accepts valid JWT for the project owner', async () => { const env = createEnv(); @@ -448,8 +483,8 @@ describe('proxy worker', () => { expect(await res.json()).toEqual({ error: 'invalid or expired token' }); }); - it('rejects JWT signed with wrong secret', async () => { - const badToken = await signJwt({ sub: 'user_1', login: 'testuser' }, 'wrong-secret'); + it('rejects login JWTs signed with the email key', async () => { + const badToken = await signJwt({ sub: 'user_1', login: 'testuser' }, EMAIL_SIGNING_SECRET); const res = await worker.fetch( post( diff --git a/platform/packages/proxy/wrangler.jsonc b/platform/packages/proxy/wrangler.jsonc index 0d53fd7c8..587cba96c 100644 --- a/platform/packages/proxy/wrangler.jsonc +++ b/platform/packages/proxy/wrangler.jsonc @@ -34,7 +34,7 @@ // src/email-router.ts; mirrored to deployed user workers as the // __VOID_EMAIL_DOMAIN binding. Never defaulted in code. "vars": { "EMAIL_SENDER_DOMAIN": "mail.void.cloud" }, - // Secrets (via `wrangler secret put`): JWT_SECRET, CF_ACCOUNT_ID, CF_API_TOKEN + // Encrypted Worker secrets: JWT_SECRET, EMAIL_SIGNING_SECRET, CF_ACCOUNT_ID, CF_API_TOKEN "observability": { "logs": { "enabled": true, @@ -45,6 +45,7 @@ "env": { "production": { "name": "void-proxy", + "secrets": { "required": ["EMAIL_SIGNING_SECRET"] }, "ai": { "binding": "AI" }, "kv_namespaces": [ { @@ -70,6 +71,7 @@ }, "staging": { "name": "void-proxy-staging", + "secrets": { "required": ["EMAIL_SIGNING_SECRET"] }, "ai": { "binding": "AI" }, "kv_namespaces": [ { diff --git a/platform/scripts/wrangler-deploy.ts b/platform/scripts/wrangler-deploy.ts index 5a8f63069..322c10744 100644 --- a/platform/scripts/wrangler-deploy.ts +++ b/platform/scripts/wrangler-deploy.ts @@ -1,7 +1,18 @@ import { spawnSync } from 'node:child_process'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { parseArgs } from 'node:util'; -const { values } = parseArgs({ +const EMAIL_SIGNING_SECRET = 'EMAIL_SIGNING_SECRET'; +const EMAIL_WORKER_DIRECTORIES = new Set( + ['api', 'email-gateway', 'proxy'].map((name) => + fileURLToPath(new URL(`../packages/${name}`, import.meta.url)), + ), +); + +const { values, positionals } = parseArgs({ allowPositionals: true, options: { build: { @@ -11,6 +22,22 @@ const { values } = parseArgs({ short: 'e', type: 'string', }, + config: { + short: 'c', + type: 'string', + }, + 'dry-run': { + type: 'boolean', + }, + outdir: { + type: 'string', + }, + outfile: { + type: 'string', + }, + preflight: { + type: 'boolean', + }, }, strict: false, }); @@ -24,10 +51,44 @@ if (env !== 'production' && env !== 'staging') { process.exit(1); } +function readEmailSigningSecret(): string { + const value = process.env[EMAIL_SIGNING_SECRET]; + if (!value) { + console.error(`${EMAIL_SIGNING_SECRET} is required for ${env} platform deployments.`); + process.exit(1); + } + if (value !== value.trim() || Buffer.byteLength(value, 'utf8') < 32) { + console.error( + `${EMAIL_SIGNING_SECRET} must have at least 32 bytes and no leading or trailing whitespace.`, + ); + process.exit(1); + } + return value; +} + +const subprocessEnv = { ...process.env }; +delete subprocessEnv[EMAIL_SIGNING_SECRET]; + +if (values.preflight === true) { + readEmailSigningSecret(); + console.log(`Platform deployment preflight passed for ${env}.`); + process.exit(0); +} + +const wranglerArgs = process.argv.slice(2).filter((arg) => arg !== '--build'); +const usesEmailSigningSecret = + EMAIL_WORKER_DIRECTORIES.has(process.cwd()) && + process.env.WRANGLER_CI_OVERRIDE_NAME === undefined && + positionals.length === 0 && + Object.keys(values).every((option) => + ['build', 'env', 'dry-run', 'outdir', 'outfile'].includes(option), + ); +const emailSigningSecret = usesEmailSigningSecret ? readEmailSigningSecret() : undefined; + if (values.build === true) { const build = spawnSync('vp', ['build'], { env: { - ...process.env, + ...subprocessEnv, CLOUDFLARE_ENV: process.env.CLOUDFLARE_ENV ?? env, }, stdio: 'inherit', @@ -38,10 +99,25 @@ if (values.build === true) { } } -const wranglerArgs = process.argv.slice(2).filter((arg) => arg !== '--build'); - -const deploy = spawnSync('wrangler', ['deploy', ...wranglerArgs], { - stdio: 'inherit', -}); +let secretsDirectory: string | undefined; +try { + const deployArgs = ['deploy', ...wranglerArgs]; + if (emailSigningSecret) { + secretsDirectory = mkdtempSync(join(tmpdir(), 'void-platform-secrets-')); + const secretsPath = join(secretsDirectory, 'secrets.json'); + writeFileSync(secretsPath, JSON.stringify({ [EMAIL_SIGNING_SECRET]: emailSigningSecret }), { + mode: 0o600, + }); + deployArgs.push('--secrets-file', secretsPath); + } -process.exit(deploy.status ?? 1); + const deploy = spawnSync('wrangler', deployArgs, { + env: subprocessEnv, + stdio: 'inherit', + }); + process.exitCode = deploy.status ?? 1; +} finally { + if (secretsDirectory) { + rmSync(secretsDirectory, { force: true, recursive: true }); + } +}