diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index d7fe1074d..cd32aef26 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -43,6 +43,7 @@ const referenceItems = [ { text: 'void secret', link: '/reference/cli#secrets' }, { text: 'void github', link: '/reference/cli#github' }, { text: 'void domain', link: '/reference/cli#custom-domains' }, + { text: 'void email', link: '/reference/cli#email' }, { text: 'void init --agents', link: '/reference/cli#agent' }, ], }, diff --git a/docs/guide/email.md b/docs/guide/email.md index 0b1f02bde..8a96622dd 100644 --- a/docs/guide/email.md +++ b/docs/guide/email.md @@ -66,9 +66,40 @@ The project owner's email (the GitHub address you signed up with) is added autom ::: warning When this is the right fit The shared sender is great for: ops alerts to the team, notifications to the project owner, reply-by-email flows on top of inbound, internal/app-internal mail. -For SaaS sending to arbitrary end-users (every signup gets a welcome email), the per-recipient verification model doesn't fit. On [your own Cloudflare account](#your-own-cloudflare-account) with Workers Paid, Void onboards your mail domain for Email Sending, which lifts the verified-recipient gate. Otherwise use [Resend](https://resend.com), [Postmark](https://postmarkapp.com), or [SES](https://aws.amazon.com/ses/) directly — install their SDK and call it from your handler. We may formalize this with a provider abstraction later if there is demand; until then, calling the SDK directly is simple enough that the wrapper would not earn its keep. +For SaaS sending to arbitrary end-users (every signup gets a welcome email), the per-recipient verification model doesn't fit. On the platform, [registering your own domain](#your-own-domain-on-the-platform) lifts that gate for sends from that domain. On [your own Cloudflare account](#your-own-cloudflare-account) with Workers Paid, Void onboards your mail domain for Email Sending, which lifts the verified-recipient gate. Otherwise use [Resend](https://resend.com), [Postmark](https://postmarkapp.com), or [SES](https://aws.amazon.com/ses/) directly — install their SDK and call it from your handler. We may formalize this with a provider abstraction later if there is demand; until then, calling the SDK directly is simple enough that the wrapper would not earn its keep. ::: +## Your own domain on the platform + +The shared sender lives on the platform's `mail.void.cloud` zone. To send — and receive — at a domain you own, register its Cloudflare zone with the project: + +```sh +void email domain add acme.com +``` + +`add` needs one credential for the zone and offers two ways to grant it. The default opens Cloudflare's hosted consent page for an OAuth grant — one Allow click; the page names Wrangler, whose OAuth client Void borrows for it. Pressing Enter at any point, or any failure of the consent flow, switches to the fallback: a three-click template link that creates a scoped API token, which the CLI watches for on the clipboard or takes as a masked paste. Either credential is POSTed to the platform once and stored there, encrypted for the project — nothing is kept on your machine. + +**Where the mail lives.** Void never enables routing over live mail: when `acme.com` already carries MX records, the CLI proposes `mail.acme.com` (`[change with --subdomain]`); the apex is used only when it carries no MX records. `--subdomain ` overrides the proposal outright. + +**The pending state.** Enabling Email Routing on a subdomain is the one step with no API path, so when it is the step that remains, `add` prints it — Cloudflare dashboard → Email Routing → acme.com → Settings → Subdomains → add the subdomain — and the row sits at `pending`. Poll with: + +```sh +void email domain status acme.com +``` + +Once public MX on the domain names Cloudflare, the row flips itself to `active` — no second command. `status` also re-probes the stored credential and the relay worker on every call, so it doubles as the drift report. + +**When a row is not active.** `failed` names the step that failed; fix it and re-run `void email domain add acme.com` — adding again replaces the credential and retries, and the routing rules stay. `token_revoked` / `token_expired` mean the stored credential died at Cloudflare; re-run `add` with a fresh grant or token — rules and the relay stay. + +Two upkeep verbs: + +- `void email domain sync acme.com` redeploys the relay at the current version and rotates its secret — the answer when `status` reports the relay missing or drifted. +- `void email domain remove acme.com` deletes the platform row, the stored credential, and the relay secret. Cloudflare-side cleanup is best-effort; anything that could not be finished is named so you can delete it by hand. + +Two rules bound registrations: one live email domain per Cloudflare zone (a second `add` on the same zone is refused until you `remove` the first), and one project per domain (a domain registered to another project is refused). + +Sends from a registered domain skip the verified-recipient allowlist — the domain's own Email Sending onboarding replaces it — while platform quota and abuse controls still apply. Inbound needs nothing further: once the domain is `active`, mail to any address on it reaches your `email/` handlers. + ## Options | Option | Type | Notes | @@ -87,7 +118,7 @@ At most 100 recipients across `to`, `cc` and `bcc` per call. Each address is che `Address` accepts either a string (`"hello@acme.dev"` or `"Name "`) or an object (`{ email, name? }`). Display names with non-ASCII characters are RFC 2047 encoded automatically. -On the platform the sender is pinned to your project. `from` must be your project's own platform address — `@mail.void.cloud` or `+@mail.void.cloud`, optionally with a display name (`Acme `). Anything else is rejected with `INVALID_FROM`. Omit `from` and Void fills in `+noreply@mail.void.cloud` for you. Sending from your own domain on the platform is not supported yet. +On the platform the sender is pinned to your project. `from` must be your project's own platform address — `@mail.void.cloud` or `+@mail.void.cloud`, optionally with a display name (`Acme `) — or any address on a domain registered with `void email domain add` (see [Your own domain on the platform](#your-own-domain-on-the-platform)). Anything else is rejected with `INVALID_FROM`. Omit `from` and Void fills in `+noreply@mail.void.cloud` for you. On your own Cloudflare account, `from` defaults to `email.from` from `void.json` and must be on a domain your account can send from; Cloudflare rejects any other sender and `sendEmail` reports it as `INVALID_FROM`. @@ -383,7 +414,7 @@ never throws, while `replyEmail` throws when it cannot determine a sender. ### Configuring inbound delivery -In production, inbound runs on one shared mail facility. The platform routes `+anything@` to your worker's `email()` export — **there is nothing to configure in the Cloudflare dashboard and no per-project DNS work**. Your handlers are live as soon as the deploy lands. +In production, inbound runs on one shared mail facility. The platform routes `+anything@` to your worker's `email()` export — **there is nothing to configure in the Cloudflare dashboard and no per-project DNS work**. Your handlers are live as soon as the deploy lands. A [registered custom domain](#your-own-domain-on-the-platform) lands on the same facility: once `void email domain add` reports it `active`, mail to any address on the domain reaches your `email/` handlers, with nothing further to configure. On your own Cloudflare account there is no shared facility: the deploy derives one Email Routing rule per handler and writes it into `wrangler.jsonc` for you — see [Your own Cloudflare account](#your-own-cloudflare-account). diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 62ad362cd..38ef6887f 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -46,6 +46,7 @@ Use this page as a command reference. If you are setting up a project for the fi | `void email destinations` | List verified recipient addresses | | `void email allow
` | Add a recipient and send a verification email | | `void email disallow
` | Remove a recipient from the allowlist | +| `void email domain` | Send and receive at your own domain on a Cloudflare zone | | `void init` | Setup wizard for new or existing projects | ## Binary Invocation @@ -1313,6 +1314,54 @@ void email disallow
[--project ] Remove one recipient from the project's destination list. Sends to that address are refused within about a minute: the platform updates the project's allowlist as part of the command, and the proxy re-reads it every 60 seconds. No deploy is involved. +### `void email domain` + +``` +void email domain [] [--project ] +``` + +Send and receive at your own domain on a Cloudflare zone you own, registered to the project. Void platform only — on your own Cloudflare account the mail domain comes from `email.from` instead (see `void email setup`). The walkthrough is [Your own domain on the platform](../guide/email.md#your-own-domain-on-the-platform). + +#### `void email domain add` + +``` +void email domain add [--subdomain ] [--project ] +``` + +Register the domain with the project. One credential is required, granted two ways: an OAuth grant from Cloudflare's hosted consent page (the page names Wrangler — Void borrows its OAuth client), or, as the fallback Enter switches to at any point, a scoped API token created from a three-click template link and picked up from the clipboard or a masked paste. The credential is POSTed once and stored on the platform, encrypted for the project — nothing is kept locally. Needs an interactive terminal. The CLI proposes `mail.` when the apex already carries MX records and allows the apex only when it carries none; `--subdomain` overrides the proposal. One live email domain per zone and one project per domain are enforced — a conflict is refused with a 409. Re-running `add` on a `failed`, `token_revoked`, or `token_expired` row replaces the credential and retries; the routing rules stay. + +#### `void email domain status` + +``` +void email domain status [--project ] +``` + +Show one registered domain. The platform re-probes the stored credential and the relay worker on every call, so this doubles as the drift report. A `pending` row whose only remaining step is the dashboard's subdomain form (printed by `add`) self-clears to `active` once public MX on the domain names Cloudflare — which makes this command the poll for that one human step. + +#### `void email domain list` + +``` +void email domain list [--project ] +``` + +List the project's registered email domains with their status and mode. + +#### `void email domain sync` + +``` +void email domain sync [--project ] +``` + +Redeploy the domain's relay worker at the current version and rotate its secret — the fix when `status` reports the relay missing or drifted. + +#### `void email domain remove` + +``` +void email domain remove [--project ] +``` + +Delete the registration: the platform row, the stored credential, and the relay secret. Cloudflare-side cleanup is best-effort; any step that fails is named (`failed_steps`) so you can finish it in the Cloudflare dashboard. + ### `void email status` ``` diff --git a/packages/void/src/cli/cf-oauth.ts b/packages/void/src/cli/cf-oauth.ts new file mode 100644 index 000000000..b86e9c554 --- /dev/null +++ b/packages/void/src/cli/cf-oauth.ts @@ -0,0 +1,315 @@ +/** + * The Cloudflare OAuth grant on wrangler's public PKCE client (design doc + * 0078, "The OAuth grant on wrangler's client"; task contract 8) — the + * primary credential grant for `void email domain add`. The customer clicks + * Allow on Cloudflare's hosted consent page, the loopback server below + * receives the code, exchanges it at the token endpoint, and returns the + * grant's refresh token. + * + * The refresh token is held in memory only: the command POSTs it to the + * platform as its first use and drops it. It is never written to disk, the + * keychain, a log line, or an error message. + * + * The client id is wrangler's own public client (no secret), which + * Cloudflare can rotate or revoke any day — so the template-link + paste + * path in `email.ts` is the permanent fallback, not a legacy branch. The + * consent page is Cloudflare's and names Wrangler; it cannot say Void, so + * the warning line is printed here before the browser opens. + */ + +import { randomBytes } from 'node:crypto'; +import { log } from '@clack/prompts'; +import { createCodeChallenge, createCodeVerifier, openBrowser } from './auth.ts'; + +/** wrangler's public PKCE OAuth client id (no secret). Not ours — see the header. */ +export const CF_OAUTH_CLIENT_ID = '54d11594-84e4-41aa-b438-e81b8fa78ee7'; +export const CF_OAUTH_AUTHORIZE_URL = 'https://dash.cloudflare.com/oauth2/auth'; +export const CF_OAUTH_TOKEN_URL = 'https://dash.cloudflare.com/oauth2/token'; +export const CF_OAUTH_REVOKE_URL = 'https://dash.cloudflare.com/oauth2/revoke'; +/** + * The redirect registered on wrangler's client. Fixed port and path: the + * consent flow redirects here and only here, so the loopback server binds + * exactly :8976 and answers exactly /oauth/callback — unlike the platform + * login's random-port /callback in auth.ts, which cannot serve this flow. + */ +export const CF_OAUTH_CALLBACK_PORT = 8976; +export const CF_OAUTH_CALLBACK_PATH = '/oauth/callback'; +export const CF_OAUTH_REDIRECT_URI: string = `http://localhost:${CF_OAUTH_CALLBACK_PORT}${CF_OAUTH_CALLBACK_PATH}`; +/** The scopes the email-domain setup needs; `offline_access` is what yields the refresh token. */ +export const CF_OAUTH_SCOPE = + 'zone:read email_routing:write email_sending:write workers_scripts:write offline_access'; + +export type CfOauthGrant = Readonly<{ + /** The grant's refresh token. Never logged, never persisted locally. */ + refreshToken: string; +}>; + +/** + * Revoke a grant at Cloudflare — RFC 7009 on wrangler's public client, the + * same form wrangler's `logout` posts (a public client authenticates with + * the token itself; no Authorization header). Never throws, never logs the + * token; the boolean is whether Cloudflare CONFIRMED the revocation (200 — + * CF answers 200 even for a bogus token), so `false` means the grant's + * state is unknown and it may still be live: callers that print an outcome + * must not claim a revocation they cannot prove. For when the CLI holds a + * grant it will not hand to the platform: a consent exchange that + * completed after the flow settled (fire-and-forget there — the flow is + * settled), or an add request that provably never persisted one. + */ +export async function revokeCfOauthGrant(refreshToken: string): Promise { + try { + const res = await fetch(CF_OAUTH_REVOKE_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + token: refreshToken, + token_type_hint: 'refresh_token', + client_id: CF_OAUTH_CLIENT_ID, + }).toString(), + }); + return res.ok; + } catch { + // The grant's state at Cloudflare is unknown either way. + return false; + } +} + +/** The consent URL the browser opens — PKCE S256, state-bound to the loopback server. */ +export function buildCfOauthAuthorizeUrl(params: { state: string; codeChallenge: string }): string { + const url = new URL(CF_OAUTH_AUTHORIZE_URL); + url.searchParams.set('response_type', 'code'); + url.searchParams.set('client_id', CF_OAUTH_CLIENT_ID); + url.searchParams.set('redirect_uri', CF_OAUTH_REDIRECT_URI); + url.searchParams.set('scope', CF_OAUTH_SCOPE); + url.searchParams.set('state', params.state); + url.searchParams.set('code_challenge', params.codeChallenge); + url.searchParams.set('code_challenge_method', 'S256'); + return url.href; +} + +/** + * Exchange the authorization code at Cloudflare's token endpoint. The + * response body is never logged and never copied into an error — it carries + * token material on success, so failure messages name only the HTTP status. + */ +async function exchangeCfOauthCode(code: string, codeVerifier: string): Promise { + const res = await fetch(CF_OAUTH_TOKEN_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'authorization_code', + code, + redirect_uri: CF_OAUTH_REDIRECT_URI, + client_id: CF_OAUTH_CLIENT_ID, + code_verifier: codeVerifier, + }).toString(), + }); + if (!res.ok) { + throw new Error(`cf-oauth: Cloudflare's token exchange failed (HTTP ${res.status}).`); + } + let body: unknown; + try { + body = await res.json(); + } catch { + throw new Error("cf-oauth: Cloudflare's token exchange returned an invalid response."); + } + const refreshToken = + body && typeof body === 'object' && 'refresh_token' in body ? body.refresh_token : undefined; + if (typeof refreshToken !== 'string' || refreshToken.length === 0) { + // `offline_access` is on the scope string, so a grant without a refresh + // token is a Cloudflare-side surprise worth naming — the refresh token is + // the one thing the platform stores. + throw new Error("cf-oauth: Cloudflare's answer carried no refresh token."); + } + return { refreshToken }; +} + +/** Same minimal callback page the platform login renders (auth.ts keeps its own copy). */ +function page(title: string, message: string): string { + return ` + +${title} - Void + +

${title}

${message}

`; +} + +/** + * Run the grant: bind the loopback server on :8976, warn about the + * Wrangler-named consent page, open the browser, and resolve with the + * refresh token once the code has been exchanged INSIDE the request handler + * (so the browser only sees the success page after the exchange succeeded). + * + * Rejects on a busy port, a denied consent, a failed exchange, an abort + * (`signal` — the command aborts when Enter switches to the token path), or + * the timeout; the caller falls back to the template-link path on any of + * them. `onUrl` fires with the authorize URL once the server is listening, + * so the command can show it as the manual fallback when the browser fails + * to open. The server is always closed before settling. + */ +export async function runCfOauthGrant(options: { + onUrl?: (url: string) => void; + /** Default 5 minutes. */ + timeoutMs?: number; + signal?: AbortSignal; + /** Injectable for tests; defaults to the real `node:child_process` `execFile`. */ + execFile?: typeof import('node:child_process').execFile; +}): Promise { + const http = await import('node:http'); + const { onUrl, signal } = options; + const timeoutMs = options.timeoutMs ?? 5 * 60 * 1000; + const execFile = options.execFile ?? (await import('node:child_process')).execFile; + + if (signal?.aborted) { + throw new Error('cf-oauth: cancelled.'); + } + + return new Promise((resolve, reject) => { + let settled = false; + + const state = randomBytes(32).toString('hex'); + const codeVerifier = createCodeVerifier(); + const codeChallenge = createCodeChallenge(codeVerifier); + + const onAbort = (): void => fail(new Error('cf-oauth: cancelled.')); + + const fail = (error: Error): void => { + if (settled) { + return; + } + settled = true; + server.close(); + signal?.removeEventListener('abort', onAbort); + reject(error); + }; + + const succeed = (grant: CfOauthGrant): void => { + if (settled) { + return; + } + settled = true; + server.close(); + signal?.removeEventListener('abort', onAbort); + resolve(grant); + }; + + // server.close() stops new connections but leaves the in-flight callback + // socket open — both settled branches below still answer the tab. + const cancelled = (res: import('node:http').ServerResponse): void => { + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end( + page( + 'Authorization cancelled', + 'This sign-in was cancelled in the terminal. You can close this tab.', + ), + ); + }; + + const server = http.createServer(async (req, res) => { + const url = new URL(req.url!, 'http://localhost'); + if (url.pathname !== CF_OAUTH_CALLBACK_PATH) { + res.writeHead(404); + res.end('Not found'); + return; + } + + if (url.searchParams.get('state') !== state) { + res.writeHead(400, { 'Content-Type': 'text/html' }); + res.end(page('Authorization failed', 'Invalid callback. Please try again.')); + return; + } + + // The customer clicked deny, or Cloudflare refused the request itself. + const cfError = url.searchParams.get('error'); + if (cfError) { + const message = + cfError === 'access_denied' + ? 'The Cloudflare consent was denied.' + : `Cloudflare returned an error (${cfError}).`; + res.writeHead(403, { 'Content-Type': 'text/html' }); + res.end(page('Authorization failed', message)); + fail(new Error(`cf-oauth: ${message}`)); + return; + } + + // Reject-but-keep-listening: a stray request without a code (favicon + // aside, everything off-path 404s above) must not settle the flow — the + // genuine callback can still arrive. + const code = url.searchParams.get('code'); + if (!code) { + res.writeHead(400, { 'Content-Type': 'text/html' }); + res.end(page('Authorization failed', 'No authorization code received. Please try again.')); + return; + } + + // Exchange INSIDE the request path so the browser only sees the success + // page once the token exchange succeeded — the same rule the platform + // login keeps. Guard against the timeout racing the in-flight exchange. + let grant: CfOauthGrant; + try { + grant = await exchangeCfOauthCode(code, codeVerifier); + } catch (err) { + if (settled) { + cancelled(res); + return; + } + res.writeHead(400, { 'Content-Type': 'text/html' }); + res.end( + page( + 'Authorization failed', + 'Could not complete the Cloudflare grant. Please try again.', + ), + ); + fail( + err instanceof Error ? err : new Error("cf-oauth: Cloudflare's token exchange failed."), + ); + return; + } + + if (settled) { + // The flow settled (Enter, abort, or the timeout) while the + // exchange was in flight — but Cloudflare still minted the grant, + // and the CLI is the only actor holding it. Revoke rather than + // strand a live user-wide grant with no handle. Fire-and-forget: + // the flow is settled, so this must never throw or stall anything. + void revokeCfOauthGrant(grant.refreshToken); + cancelled(res); + return; + } + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(page('Cloudflare connected', 'You can close this tab and return to the terminal.')); + succeed(grant); + }); + + // Close immediately after the callback — don't wait for keep-alive timeout. + server.on('connection', (socket) => socket.unref()); + + server.on('error', (err) => { + // EADDRINUSE: another login (or wrangler's own) holds :8976. The caller + // falls back to the template-link path on any failure here. + const code = (err as NodeJS.ErrnoException).code; + fail( + new Error( + `cf-oauth: could not start the local callback server on port ${CF_OAUTH_CALLBACK_PORT}${code ? ` (${code})` : ''}.`, + ), + ); + }); + + signal?.addEventListener('abort', onAbort, { once: true }); + + server.listen(CF_OAUTH_CALLBACK_PORT, '127.0.0.1', () => { + // The consent page is Cloudflare's hosted page for the wrangler client + // and cannot say Void — say it here, before the browser opens (0078). + log.warn( + "Opening Cloudflare's consent page — it names Wrangler; that is expected (Void borrows wrangler's OAuth client for this one-click grant).", + ); + const authorizeUrl = buildCfOauthAuthorizeUrl({ state, codeChallenge }); + onUrl?.(authorizeUrl); + openBrowser(authorizeUrl, execFile); + }); + + const timeout = setTimeout(() => { + fail(new Error('cf-oauth: the consent timed out.')); + }, timeoutMs); + timeout.unref(); + }); +} diff --git a/packages/void/src/cli/cli.ts b/packages/void/src/cli/cli.ts index 857ceb7de..e756a89af 100644 --- a/packages/void/src/cli/cli.ts +++ b/packages/void/src/cli/cli.ts @@ -271,7 +271,7 @@ if (helpPath) { }, { name: 'email', - hint: 'usage | logs | destinations | allow | disallow | status | setup', + hint: 'usage | logs | destinations | allow | disallow | domain | status | setup', description: 'Inspect email activity and manage verified recipients', }, { diff --git a/packages/void/src/cli/client.ts b/packages/void/src/cli/client.ts index f52eb356e..5cbfabedf 100644 --- a/packages/void/src/cli/client.ts +++ b/packages/void/src/cli/client.ts @@ -254,6 +254,87 @@ export type EmailDestinationResponse = { verificationSent?: boolean; }; +/** + * The public shape of an `email_domains` row (design doc 0078, contract 1) — + * metadata only. The api's serializer never carries the credential, the + * relay secret, or any ciphertext, so this type can never accidentally + * contain one. + */ +export type EmailDomainResponse = { + id: string; + domain: string; + mode: 'apex' | 'subdomain' | null; + status: 'pending' | 'active' | 'token_revoked' | 'token_expired' | 'failed'; + credential_kind: 'oauth_grant' | 'api_token'; + relay_worker_name: string | null; + relay_version: number | null; + /** Metadata from GET /user/tokens/verify (api_token rows) — safe to print. */ + token_id: string | null; + token_expires_on: string | null; + /** + * The add attempt that last wrote the credential (null when an older CLI + * wrote it). Optional: apis predating attempt identity omit the key + * entirely, and `in`-operator detection on the raw row is how the add + * reconcile tells that apart from a stamped null. + */ + attemptId?: string | null; + setup_state: { + /** Orchestration step that left the row 'failed'. */ + failed_step?: string; + /** Steps still owed by the human (the routing-subdomain dashboard form). */ + remaining_steps?: Array; + } | null; + /** + * Present on add/sync outcomes that failed a step. The api guarantees the + * text names the failing step or CF error — never credential material — so + * the CLI prints it verbatim. + */ + error?: string; + created_at: string; + updated_at: string; +}; + +/** The zone catch-all outcome of a sync — absent when the row has no zone_id. */ +export type EmailDomainSyncCatchAll = + | 'ensured' + | 'already_set' + | 'foreign_conflict' + | 'probe_failed'; + +/** POST .../email/domains/:domain/sync adds the catch-all outcome at the top level. */ +export type EmailDomainSyncResponse = EmailDomainResponse & { + catch_all?: EmailDomainSyncCatchAll; +}; + +/** GET /email/domains/:domain adds a live credential probe and the relay-drift read. */ +export type EmailDomainStatusResponse = EmailDomainResponse & { + credential_status: 'active' | 'expired' | 'revoked' | 'probe_failed'; + current_relay_version: number; + relay_drift: boolean; + relay_missing: boolean | null; + /** Live read of the zone's catch-all rule relative to this domain's relay. */ + catch_all: 'points_here' | 'points_elsewhere' | 'missing' | 'disabled' | 'unknown'; + /** true when the zone's catch-all no longer points at this relay — `domain sync` re-points it. */ + catch_all_drift: boolean; +}; + +/** A Cloudflare-side cleanup step the email-domain delete orchestration can fail. */ +export type RemoveEmailDomainFailedStep = 'catch_all' | 'delete_relay' | 'revoke_grant'; + +export type RemoveEmailDomainResponse = { + ok: boolean; + /** + * false = the row was KEPT for retry: a Cloudflare-side step failed and + * the remove was not forced, so the credential stays for the retry. + * true = the platform row, the stored credential and the relay secret + * are gone. + */ + removed: boolean; + /** true when `?force=1` dropped the row despite Cloudflare-side failures. */ + forced?: true; + failed_steps?: Array; +}; + export type DomainResponse = { id: string; project_id: string; @@ -1349,4 +1430,117 @@ export class PlatformClient { return res.json(); } + + async listEmailDomains(projectId: string): Promise> { + const res = await fetch(`${this.baseUrl}/projects/${projectId}/email/domains`, { + headers: { + ...this.authHeaders, + }, + }); + + if (!res.ok) { + await throwPlatformApiError('Failed to list email domains', res); + } + + return res.json(); + } + + /** + * `domain add` sends the credential exactly once — the OAuth grant's + * refresh token xor a pasted API token (the api enforces exactly one). It + * is the only call that ever carries it: the platform stores it encrypted + * per project, and every later step (`status`, `sync`, `remove`) addresses + * the row by domain. The caller must not log the input. + */ + async addEmailDomain( + projectId: string, + input: { domain: string; refreshToken?: string; apiToken?: string; attemptId?: string }, + ): Promise { + const res = await fetch(`${this.baseUrl}/projects/${projectId}/email/domains`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...this.authHeaders, + }, + body: JSON.stringify({ + domain: input.domain, + ...(input.refreshToken !== undefined ? { refreshToken: input.refreshToken } : {}), + ...(input.apiToken !== undefined ? { apiToken: input.apiToken } : {}), + ...(input.attemptId !== undefined ? { attemptId: input.attemptId } : {}), + }), + }); + + if (!res.ok) { + await throwPlatformApiError('Failed to add email domain', res); + } + + return res.json(); + } + + async getEmailDomain(projectId: string, domain: string): Promise { + const res = await fetch( + `${this.baseUrl}/projects/${projectId}/email/domains/${encodeURIComponent(domain)}`, + { + headers: { + ...this.authHeaders, + }, + }, + ); + + if (!res.ok) { + await throwPlatformApiError('Failed to fetch email domain status', res); + } + + return res.json(); + } + + /** Redeploys the relay at the current version and rotates its secret (0078, `sync`). */ + async syncEmailDomain(projectId: string, domain: string): Promise { + const res = await fetch( + `${this.baseUrl}/projects/${projectId}/email/domains/${encodeURIComponent(domain)}/sync`, + { + method: 'POST', + headers: { + ...this.authHeaders, + }, + }, + ); + + if (!res.ok) { + await throwPlatformApiError('Failed to sync email domain', res); + } + + return res.json(); + } + + /** + * `force` appends `?force=1`: the api drops the row even when a + * Cloudflare-side cleanup step fails (and answers `forced: true` + + * `failed_steps`). Without it a CF-side failure keeps the row for retry + * (`removed: false`). + */ + async removeEmailDomain( + projectId: string, + domain: string, + force?: boolean, + ): Promise { + const url = new URL( + `${this.baseUrl}/projects/${projectId}/email/domains/${encodeURIComponent(domain)}`, + ); + if (force) { + url.searchParams.set('force', '1'); + } + const res = await fetch(url, { + method: 'DELETE', + headers: { + ...this.authHeaders, + }, + }); + + if (!res.ok) { + await throwPlatformApiError('Failed to remove email domain', res); + } + + return res.json(); + } } diff --git a/packages/void/src/cli/email-args.ts b/packages/void/src/cli/email-args.ts index 55f85488b..d403670b3 100644 --- a/packages/void/src/cli/email-args.ts +++ b/packages/void/src/cli/email-args.ts @@ -12,6 +12,14 @@ export const emailSubcommands: Array = [ { name: 'destinations', description: 'List verified recipient addresses for outbound mail' }, { name: 'allow', arg: '
', description: 'Add a recipient and trigger CF verification' }, { name: 'disallow', arg: '
', description: 'Remove a verified recipient' }, + // The first (and only) nested group: the verb is collected as the arg so + // `domain list` completes in the interactive prompt; `domain add` then + // errors naming the missing , the same as a typed invocation. + { + name: 'domain', + arg: '', + description: 'Send and receive at your own domain on a Cloudflare zone', + }, { name: 'status', description: 'Show the email setup state and address map', @@ -30,12 +38,32 @@ const EMAIL_SUBCOMMANDS = [ 'destinations', 'allow', 'disallow', + 'domain', 'status', 'setup', ] as const; +export const EMAIL_DOMAIN_VERBS = ['add', 'status', 'list', 'sync', 'remove'] as const; +export type EmailDomainVerb = (typeof EMAIL_DOMAIN_VERBS)[number]; + export interface EmailArgs { subcommand: (typeof EMAIL_SUBCOMMANDS)[number]; + /** The nested `void email domain ` verb — set only when subcommand is 'domain'. */ + domainVerb?: EmailDomainVerb; + /** The domain positional of a domain verb (absent for `domain list`). */ + domain?: string; + /** + * `--subdomain ` on `domain add`: which subdomain to register + * instead of the `mail.` the MX decision proposes (design doc 0078, + * "[change with --subdomain]"). + */ + subdomain?: string; + /** + * `--force` on `domain remove`: drop the platform row even when a + * Cloudflare-side cleanup step fails (the api answers `forced: true` and + * names the failed steps for manual cleanup). + */ + force?: boolean; projectSlug?: string; limit?: number; address?: string; @@ -73,7 +101,7 @@ export function parseEmailArgs(args: Array): EmailArgs { const subcommand = args[0] as EmailArgs['subcommand']; if (!subcommand || !(EMAIL_SUBCOMMANDS as ReadonlyArray).includes(subcommand)) { throw new Error( - 'email: Usage: void email [args] [--project ] [--limit ] [--platform cloudflare].', + 'email: Usage: void email [args] [--project ] [--limit ] [--platform cloudflare].', ); } @@ -86,6 +114,8 @@ export function parseEmailArgs(args: Array): EmailArgs { const projectValues: Array = []; const platformValues: Array = []; const backendValues: Array = []; + const subdomainValues: Array = []; + let forceCount = 0; const positional: Array = []; const rest = args.slice(1); @@ -129,11 +159,32 @@ export function parseEmailArgs(args: Array): EmailArgs { } backendValues.push(value); i = next; + } else if (rest[i] === '--subdomain' || rest[i]?.startsWith('--subdomain=')) { + const { value, next } = readFlagValue(rest, i, '--subdomain'); + // Same missing-value rule as --project: a bare flag or an empty shell + // variable reads as no value, not as the next flag's name. + if (value === undefined || value.trim() === '') { + throw new Error('email: --subdomain requires a value (a subdomain label or host).'); + } + subdomainValues.push(value); + i = next; + } else if (rest[i] === '--force' || rest[i]?.startsWith('--force=')) { + // A boolean: `--force=yes` is a positional's worth of confusion, not a value. + if (rest[i] !== '--force') { + throw new Error('email: --force takes no value.'); + } + forceCount++; } else { positional.push(rest[i]); } } + // Same repeated-flag rule as --project/--subdomain. + if (forceCount > 1) { + throw new Error('email: --force can only be specified once.'); + } + const force = forceCount > 0 ? true : undefined; + // Same rule as `void deploy`: `--project` at most once. if (projectValues.length > 1) { throw new Error('email: --project can only be specified once.'); @@ -168,6 +219,30 @@ export function parseEmailArgs(args: Array): EmailArgs { platform = 'cloudflare'; } + if (subdomainValues.length > 1) { + throw new Error('email: --subdomain can only be specified once.'); + } + const subdomain = subdomainValues[0]; + + // The nested `domain` group parses its own positionals (verb + domain) and + // returns early — the one-positional rule below predates it and would + // read the verb as the address. Mode B needs none of this group (0078, + // "Mode B" under custom domains), so it is Void-platform-only. + if (subcommand === 'domain') { + if (platform === 'cloudflare') { + throw new Error( + 'email: --platform cloudflare applies to `void email status` and `void email setup` only (`domain` is a Void platform command).', + ); + } + return parseEmailDomainArgs(positional, { projectSlug, limit, platform, subdomain, force }); + } + if (subdomain !== undefined) { + throw new Error('email: --subdomain applies to `void email domain add` only.'); + } + if (force !== undefined) { + throw new Error('email: --force applies to `void email domain remove` only.'); + } + // `void email allow|disallow` takes exactly one address. Silently // dropping extras (the previous behavior, which kept only the first) // led to confusing UX — `void email allow a@x.dev b@y.dev` quietly @@ -209,3 +284,60 @@ export function parseEmailArgs(args: Array): EmailArgs { return { subcommand, projectSlug, limit, address, platform }; } + +/** + * The nested `void email domain []` group. positional[0] is the + * verb, positional[1] the domain — `list` takes no domain, every other verb + * requires exactly one. Shape validation of the domain itself is the command's + * job (and ultimately the api's — its regex is authoritative); the parser only + * counts positionals, exactly as it does for `allow
`. + */ +function parseEmailDomainArgs( + positional: ReadonlyArray, + flags: { + projectSlug?: string; + limit?: number; + platform?: EmailArgs['platform']; + subdomain?: string; + force?: boolean; + }, +): EmailArgs { + const verb = positional[0]; + if (!verb || !(EMAIL_DOMAIN_VERBS as ReadonlyArray).includes(verb)) { + throw new Error( + 'email: Usage: void email domain [] [--project ].', + ); + } + if (flags.subdomain !== undefined && verb !== 'add') { + throw new Error('email: --subdomain applies to `void email domain add` only.'); + } + if (flags.force !== undefined && verb !== 'remove') { + throw new Error('email: --force applies to `void email domain remove` only.'); + } + const domain = positional[1]; + if (verb === 'list') { + if (domain !== undefined) { + throw new Error('email: `void email domain list` takes no domain argument.'); + } + } else if (domain === undefined) { + throw new Error(`email: Usage: void email domain ${verb} [--project ].`); + } + if (positional.length > 2) { + throw new Error( + `email: \`void email domain ${verb}\` takes exactly one domain argument (got ${positional.length - 1}: ${positional + .slice(1) + .map((p) => JSON.stringify(p)) + .join(', ')}).`, + ); + } + return { + subcommand: 'domain', + domainVerb: verb as EmailDomainVerb, + domain, + subdomain: flags.subdomain, + force: flags.force, + projectSlug: flags.projectSlug, + limit: flags.limit, + platform: flags.platform, + }; +} diff --git a/packages/void/src/cli/email.ts b/packages/void/src/cli/email.ts index 7692a6577..7940d3798 100644 --- a/packages/void/src/cli/email.ts +++ b/packages/void/src/cli/email.ts @@ -1,10 +1,17 @@ -import { confirm, isCancel, log, note } from '@clack/prompts'; +import { execSync } from 'node:child_process'; +import { confirm, isCancel, log, note, password } from '@clack/prompts'; import { parseRootWranglerConfig, readWranglerTopLevelString } from '@void/deploy-cloudflare'; import { readConfig } from '../config.ts'; import { readProjectPaths } from '../project-paths.ts'; import { scanEmailHandlersSync } from '../router/email.ts'; -import { getToken } from './auth.ts'; -import { PlatformClient } from './client.ts'; +import { getToken, openBrowser } from './auth.ts'; +import { revokeCfOauthGrant, runCfOauthGrant, type CfOauthGrant } from './cf-oauth.ts'; +import { + PlatformApiError, + PlatformClient, + type EmailDomainResponse, + type EmailDomainStatusResponse, +} from './client.ts'; import { createDeployWranglerRunner, deriveWorkerName, @@ -28,7 +35,7 @@ import { type EmailPreflight, type EmailWranglerRun, } from './email-cloudflare.ts'; -import { pc } from './output.ts'; +import { createSpinner, pc } from './output.ts'; import { readProjectConfig } from './project.ts'; import { writeProvisionedWranglerConfig } from './wrangler.ts'; @@ -90,6 +97,8 @@ export async function runEmailCommand(root: string, args: EmailArgs): Promise token.startsWith(prefix))) { + return 'refused'; + } + if (CFUT_TOKEN_PATTERN.test(token)) { + return 'cfut'; + } + if (LEGACY_CF_TOKEN_PATTERN.test(token)) { + return 'legacy'; + } + return 'unknown'; +} + +// Clipboard helpers — the read side mirrors the write side in auth-cmd.ts +// (pbcopy / clip / xclip); wl-paste/wl-copy cover Wayland sessions. +function readClipboard(): string | null { + const platform = process.platform; + const command = + platform === 'darwin' + ? 'pbpaste' + : platform === 'win32' + ? 'powershell -NoProfile -Command Get-Clipboard' + : 'xclip -o -selection clipboard'; + try { + return execSync(command, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); + } catch { + if (platform !== 'darwin' && platform !== 'win32') { + try { + return execSync('wl-paste', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); + } catch { + // No clipboard tool (SSH, CI, a bare Wayland session) — the paste prompt is the path. + } + } + return null; + } +} + +/** `pbcopy { + let res: Response; + try { + res = await fetch('https://api.cloudflare.com/client/v4/user/tokens/verify', { + headers: { authorization: `Bearer ${token}` }, + }); + } catch { + return 'unknown'; + } + if (res.status === 401 || res.status === 403) { + return 'inactive'; + } + if (!res.ok) { + return 'unknown'; + } + try { + const body = (await res.json()) as { result?: { status?: unknown } }; + return body.result?.status === 'active' ? 'active' : 'inactive'; + } catch { + return 'unknown'; + } +} + +/** Mirror of the api's normalization (`normalizeEmailDomain`). */ +export function normalizeEmailDomainInput(raw: string): string { + return raw.trim().toLowerCase().replace(/\.$/, ''); +} + +/** + * Same DNS-hostname shape the api enforces — checked here so junk fails + * before a grant is ever requested, not after. Real validation stays the + * platform's zone lookup. + */ +export function isValidEmailDomainInput(domain: string): boolean { + return /^(?!-)[a-z0-9-]{1,63}(?, + name: string, +): Promise | null> { + try { + const records = await dns.resolveMx(name); + return records + .slice() + .sort((a, b) => a.priority - b.priority) + .map((r) => r.exchange.replace(/\.$/, '').toLowerCase()); + } catch (err) { + const code = (err as { code?: unknown } | null)?.code; + return code === 'ENODATA' || code === 'ENOTFOUND' ? [] : null; + } +} + +type EnterRace = { promise: Promise<'enter'>; stop: () => void }; + +/** + * The "Enter switches paths" race from 0078's flow. The default reads one + * cooked-mode line from stdin; `stop` removes the listener so a losing race + * cannot eat the first keystroke of a later prompt. + */ +function createEnterRace(waitForEnter?: () => Promise): EnterRace { + if (waitForEnter) { + return { promise: waitForEnter().then((): 'enter' => 'enter'), stop: () => {} }; + } + const stdin = process.stdin; + let onData: (() => void) | undefined; + const promise = new Promise<'enter'>((resolve) => { + if (!stdin.isTTY) { + return; // Never resolves — non-interactive is gated before any race starts. + } + onData = () => resolve('enter'); + stdin.on('data', onData); + }); + return { + promise, + stop: () => { + if (onData) { + stdin.removeListener('data', onData); + } + }, + }; +} + +/** Seams for {@link emailDomainAdd} — every browser, clipboard, DNS, and stdin touch is injectable. */ +export interface EmailDomainAddDeps { + dns?: Pick; + /** The OAuth grant (default: the real PKCE flow in cf-oauth.ts). */ + runGrant?: (options: { + onUrl?: (url: string) => void; + signal?: AbortSignal; + }) => Promise; + /** Browser open for the template link (default: auth.ts's openBrowser). */ + openUrl?: (url: string) => void; + /** Clipboard read; null means no clipboard tool — the paste prompt is the path. */ + readClipboard?: () => string | null; + clearClipboard?: () => void; + /** The CF-side active check (default: GET /user/tokens/verify). */ + verifyToken?: (token: string) => Promise; + /** The masked paste prompt; null means the user cancelled (Esc). */ + pasteToken?: () => Promise; + /** The Enter keypress that switches paths (default: one stdin line). */ + waitForEnter?: () => Promise; + watchIntervalMs?: number; + /** Default 10 minutes (0078's clipboard watch bound). */ + watchTimeoutMs?: number; + /** Sleep between reconcile polls after a lost add answer (default: setTimeout). */ + sleep?: (ms: number) => Promise; + /** Default: wrangler's interactivity gate, same as `void email setup`. */ + isInteractive?: boolean; + exit?: (code: number) => never; +} + +async function defaultPasteToken(): Promise { + const result = await password({ + message: 'Paste the Cloudflare API token:', + mask: '*', + }); + if (isCancel(result) || typeof result === 'symbol') { + return null; + } + return result; +} + +type EmailDomainCredential = + | { kind: 'oauth_grant'; refreshToken: string } + | { kind: 'api_token'; apiToken: string }; + +/** + * Lost-answer reconcile bounds for `domain add`: attempt-count bounded (not + * wall clock) so the worst case is finite and tests are deterministic. The + * API's pre-insert phase is DB-only but takes tens of ms to seconds of + * Hyperdrive RTTs, and a lost answer does not stop the API worker — a single + * immediate status read can 404 while the POST is still committing. + */ +const ADD_RECONCILE_ATTEMPTS = 15; +const ADD_RECONCILE_INTERVAL_MS = 1000; + +/** + * `void email domain add ` — exported for the unit test; the command + * entry resolves the client and project first. + * + * The flow (0078, "The flow"): render the MX decision → the OAuth grant → + * the template-link + clipboard fallback (Enter switches to the masked paste + * at any point) → POST the credential once → render the resulting row. A + * failed add leaves the platform row 'failed' and re-running add replaces + * the credential — the api's replace path, not anything here. + */ +export async function emailDomainAdd( + client: Pick, + projectId: string, + rawDomain: string, + subdomain: string | undefined, + deps: EmailDomainAddDeps = {}, +): Promise { + const exit = deps.exit ?? ((code: number): never => process.exit(code)); + const fail = (message: string): never => { + log.error(message); + return exit(1); + }; + + const domain = normalizeEmailDomainInput(rawDomain); + if (!isValidEmailDomainInput(domain)) { + return fail(`email: invalid domain '${rawDomain}'.`); + } + let target: { emailDomain: string; forced: boolean }; + try { + target = resolveEmailDomainTarget(domain, subdomain); + } catch (err) { + return fail(err instanceof Error ? err.message : String(err)); + } + + // The MX decision. Forced (--subdomain) needs no default, only a warning + // when the named host already carries MX; unforced reads the apex and + // falls back to mail. — exactly the doc's two render lines. + const dns = deps.dns ?? (await createNodeEmailDns()); + if (target.forced) { + const mx = await lookupMxForRender(dns, target.emailDomain); + if (mx !== null && mx.length > 0) { + log.warn( + `MX ${target.emailDomain} already carries MX (${mx.join(', ')}) — the platform re-checks over public DNS and may refuse it.`, + ); + } + } else { + const mx = await lookupMxForRender(dns, domain); + if (mx === null) { + log.info( + `MX could not read ${domain}'s MX from here — the platform decides over public DNS.`, + ); + } else if (mx.length > 0) { + target = { emailDomain: `mail.${domain}`, forced: false }; + log.info( + `MX ${domain} carries MX for ${mx[0]} → apex is off limits\n using ${target.emailDomain} [change with --subdomain]`, + ); + const subMx = await lookupMxForRender(dns, target.emailDomain); + if (subMx !== null && subMx.length > 0) { + log.warn( + `MX ${target.emailDomain} also carries MX (${subMx.join(', ')}) — the platform may refuse it; pick another with --subdomain.`, + ); + } + } else { + log.info(`MX ${domain} has no MX records → using the apex`); + } + } + + // Both grant paths need a human: a browser, a clipboard, or a paste prompt. + const interactive = deps.isInteractive ?? !isWranglerNonInteractiveOrCI(); + if (!interactive) { + return fail( + 'email: `void email domain add` needs an interactive terminal (the grant opens a browser; the fallback reads the clipboard or a paste). Run it locally.', + ); + } + + // 1. The OAuth grant on wrangler's client (cf-oauth.ts). Enter switches to + // the template-link path mid-wait; any failure falls through to it too — + // the borrowed client id is not ours, so the fallback is permanent. + let credential: EmailDomainCredential | undefined; + const runGrant = deps.runGrant ?? ((options) => runCfOauthGrant(options)); + const grantSpinner = createSpinner(); + grantSpinner.start("Opening Cloudflare's consent page…"); + const controller = new AbortController(); + const enterDuringGrant = createEnterRace(deps.waitForEnter); + const grantOutcome = await Promise.race([ + runGrant({ + signal: controller.signal, + onUrl: (url) => + grantSpinner.message( + `Waiting for the Cloudflare grant — click Allow. If the browser didn't open, visit:\n${pc.cyan(url)}\n(Enter switches to the API-token path.)`, + ), + }).then( + (grant) => ({ type: 'grant' as const, grant }), + (error: unknown) => ({ + type: 'error' as const, + error: error instanceof Error ? error : new Error(String(error)), + }), + ), + enterDuringGrant.promise.then(() => ({ type: 'enter' as const })), + ]); + enterDuringGrant.stop(); + if (grantOutcome.type === 'grant') { + grantSpinner.stop('Grant received.'); + credential = { kind: 'oauth_grant', refreshToken: grantOutcome.grant.refreshToken }; + } else { + controller.abort(); + grantSpinner.stop( + grantOutcome.type === 'enter' + ? 'Switched to the API-token path.' + : 'The consent flow did not complete — using the API-token path.', + ); + if (grantOutcome.type === 'error') { + log.warn(grantOutcome.error.message); + } + } + + // 2. The template link + clipboard watch (0078, "Creating the token in + // three clicks"). The clipboard is read only between opening the link + // and getting a token, only a NEW value shaped like a CF token is + // accepted, and the clipboard is cleared once it arrives. + if (credential === undefined) { + const url = buildCfApiTokenTemplateUrl(target.emailDomain); + const readClip = deps.readClipboard ?? readClipboard; + const clearClip = deps.clearClipboard ?? clearClipboard; + const verify = deps.verifyToken ?? verifyCfApiToken; + const openUrl = + deps.openUrl ?? + ((u: string): void => { + void import('node:child_process').then(({ execFile }) => openBrowser(u, execFile)); + }); + const snapshot = readClip(); + if (snapshot === null) { + log.info('No clipboard tool found here — paste the token instead.'); + } + openUrl(url); + + type WatchOutcome = { type: 'token'; token: string } | { type: 'enter' } | { type: 'timeout' }; + let outcome: WatchOutcome; + let watchSpinner: ReturnType | undefined; + if (snapshot === null) { + outcome = { type: 'timeout' }; + } else { + watchSpinner = createSpinner(); + watchSpinner.start( + [ + 'Create the token in three clicks: Continue to summary → Create Token → Copy.', + 'Watching the clipboard for it — nothing is read until you copy, and it is cleared afterwards.', + '(Enter pastes it yourself instead.)', + `If the browser didn't open, visit:\n${pc.cyan(url)}`, + ].join('\n'), + ); + const spinner = watchSpinner; + const deadline = Date.now() + (deps.watchTimeoutMs ?? 10 * 60 * 1000); + const interval = deps.watchIntervalMs ?? 1000; + const snapshotTrimmed = snapshot.trim(); + const enterDuringWatch = createEnterRace(deps.waitForEnter); + // Either race outcome must stop the poll branch: an orphaned loop would + // keep reading the clipboard on ref'd timers to the deadline (and could + // verify a later token-shaped value) after the flow has moved on. + let watchSettled = false; + let watchTimer: ReturnType | undefined; + outcome = await Promise.race([ + (async (): Promise => { + while (!watchSettled && Date.now() < deadline) { + await new Promise((resolve) => { + watchTimer = setTimeout(resolve, interval); + }); + if (watchSettled) { + break; + } + const value = readClip()?.trim(); + if (!value || value === snapshotTrimmed) { + continue; + } + const shape = classifyCfApiTokenShape(value); + // Wrong shape (another vendor's token included): nothing — still + // waiting, and never a network call for it (0078's branch table). + if (shape === 'refused' || shape === 'unknown') { + continue; + } + const verdict = await verify(value); + if (verdict === 'inactive') { + spinner.message('That is not an active Cloudflare token — still waiting.'); + continue; + } + if (verdict === 'unknown') { + log.info( + 'Could not reach Cloudflare to check the token — the platform will verify it.', + ); + } + return { type: 'token', token: value }; + } + return { type: 'timeout' }; + })(), + enterDuringWatch.promise.then((): WatchOutcome => ({ type: 'enter' })), + ]); + watchSettled = true; + enterDuringWatch.stop(); + // Unref the timer the losing poll branch is parked on — it wakes once, + // sees the flag and exits; it must not keep the process alive meanwhile. + watchTimer?.unref(); + } + + if (outcome.type === 'token') { + clearClip(); + watchSpinner?.stop('Token received — the clipboard copy was cleared.'); + // Said once, per 0078: a clipboard manager's history is outside our reach. + log.info('A clipboard manager may keep its own history — clear it there if you run one.'); + credential = { kind: 'api_token', apiToken: outcome.token }; + } else { + watchSpinner?.stop( + outcome.type === 'enter' ? 'Pasting instead.' : 'No token arrived — paste it instead.', + ); + const pasted = await (deps.pasteToken ?? defaultPasteToken)(); + if (pasted === null) { + // Esc: cancel with nothing stored anywhere (0078's branch table). + log.info('Cancelled — nothing was stored anywhere.'); + return; + } + const token = pasted.trim(); + const shape = classifyCfApiTokenShape(token); + if (shape === 'refused') { + return fail( + 'email: that looks like a different kind of token (a GitHub, OpenAI, Slack, or Cloudflare global key) — the link above creates a scoped Cloudflare API token.', + ); + } + if (shape === 'unknown') { + return fail( + 'email: that is not shaped like a Cloudflare API token (`cfut_…` or the legacy 40-character form). Create one from the link above.', + ); + } + const verdict = await verify(token); + if (verdict === 'inactive') { + return fail('email: that is not an active Cloudflare token.'); + } + if (verdict === 'unknown') { + log.info('Could not reach Cloudflare to check the token — the platform will verify it.'); + } + credential = { kind: 'api_token', apiToken: token }; + } + } + + // 3. The one call that carries the credential. Everything after it + // (status, sync, remove) addresses the row by domain. The attempt id + // is stamped on the row by the api, so a reconcile after a lost answer + // can tell this attempt's committed row apart from a pre-existing one. + const attemptId = crypto.randomUUID(); + let row: EmailDomainResponse; + try { + row = await client.addEmailDomain(projectId, { + domain: target.emailDomain, + ...(credential.kind === 'oauth_grant' + ? { refreshToken: credential.refreshToken } + : { apiToken: credential.apiToken }), + attemptId, + }); + } catch (err) { + if ( + err instanceof PlatformApiError && + (err.status === 400 || err.status === 404 || err.status === 409) + ) { + // Only the add route's deliberate rejections rethrow: it revokes a + // posted grant server-side before answering any of these, and the + // error names the reason. 403 is NOT in this set — the platform's + // middleware answers 403 pre-route (a suspended account, a + // deploy-token scope refusal) without ever parsing the body, so a + // 403 proves nothing about the grant and reconciles like any other + // ambiguous answer. + throw err; + } + // A transport failure (DNS, a connection reset, a lost answer) OR an + // ambiguous answer (403, 5xx, or a 401/413/426/429 from middleware or + // the edge) leaves the add's outcome unknown: the request may never + // have reached the route, it may have failed before the grant was + // stored or revoked, or it COMMITTED and only the outcome was lost. + // The CLI holds the only copy of a freshly minted grant, so reconcile + // before anything irreversible — a committed row is the grant's + // revocation handle, and only a definitive "not on the row" makes a + // CLI-side revoke safe (revoking a stored-and-unrotated grant would + // brick the row it belongs to). + const sleep = + deps.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + // The last informative read picks the deadline branch: a row carrying a + // DIFFERENT attempt id means the platform kept the row's existing + // credential; a 404 means nothing persisted (yet). + let lastRead: 'foreign' | 'missing' | undefined; + for (let attempt = 0; attempt < ADD_RECONCILE_ATTEMPTS; attempt++) { + if (attempt > 0) { + await sleep(ADD_RECONCILE_INTERVAL_MS); + } + let existing: EmailDomainStatusResponse; + try { + existing = await client.getEmailDomain(projectId, target.emailDomain); + } catch (statusErr) { + if (statusErr instanceof PlatformApiError && statusErr.status === 404) { + lastRead = 'missing'; + } + // Any other error is no read at all — keep polling. + continue; + } + if ('attemptId' in existing) { + if (existing.attemptId === attemptId) { + // My POST committed. NEVER revoke — the row is the grant's handle. + log.warn( + "The add's answer was lost (network or platform error), but the platform has the row.", + ); + printEmailDomainOutcome(existing); + return; + } + // Not mine (yet) — my in-flight POST could still commit a replace + // stamping this id, so keep polling to the deadline. + lastRead = 'foreign'; + continue; + } + // An api without attempt identity (the key is absent): this could be + // my add committed there, indistinguishable from a pre-existing row. + // Trust the row like the pre-attempt flow did — NEVER revoke. + log.warn( + "The add's answer was lost (network or platform error), but the platform has the row.", + ); + printEmailDomainOutcome(existing); + return; + } + if (lastRead === 'foreign') { + // The row settled on another attempt id (or none), so this attempt's + // credential was never stored — a committed mine would have stamped + // my id. The revoke cannot brick the row. + if (credential.kind === 'oauth_grant') { + const revoked = await revokeCfOauthGrant(credential.refreshToken); + return fail( + revoked + ? `email: the add did not complete, and ${target.emailDomain} kept the row's existing credential; the OAuth grant minted for this attempt was revoked — re-run to retry the replace.` + : `email: the add did not complete, and ${target.emailDomain} kept the row's existing credential; the OAuth grant minted for this attempt could not be revoked — revoke it in the Cloudflare dashboard, then re-run to retry the replace.`, + ); + } + return fail( + `email: the add did not complete, and ${target.emailDomain} kept the row's existing credential. The token was not stored anywhere; delete it in the Cloudflare dashboard if you are not retrying.`, + ); + } + if (lastRead === 'missing') { + // 404 at every poll — provably nothing persisted. The minted grant's + // only copy is in this process: revoke it rather than strand it live + // (an api_token has no revoke primitive — the customer deletes it + // themselves). + if (credential.kind === 'oauth_grant') { + const revoked = await revokeCfOauthGrant(credential.refreshToken); + return fail( + revoked + ? `email: the add did not complete — ${target.emailDomain} was not registered, and the OAuth grant minted for this attempt was revoked.` + : `email: the add did not complete — ${target.emailDomain} was not registered; the OAuth grant minted for this attempt could not be revoked — revoke it in the Cloudflare dashboard before retrying.`, + ); + } + return fail( + `email: the add did not complete — ${target.emailDomain} was not registered. The token was not stored anywhere; delete it in the Cloudflare dashboard if you are not retrying.`, + ); + } + // No poll produced any read — the add's state is unknown, and a blind + // revoke could brick a committed row: report, don't revoke. + return fail( + `email: the add did not complete, and the follow-up check failed too — the add's state is unknown, so nothing was revoked. A grant minted for this attempt may still be live: once connectivity is back, run \`void email domain status ${target.emailDomain}\`; if it shows no row, revoke the grant in the Cloudflare dashboard before retrying.`, + ); + } + log.success( + credential.kind === 'oauth_grant' + ? 'Grant stored on the platform, encrypted for this project — nothing is kept on this machine.' + : 'Token stored on the platform, encrypted for this project — nothing is kept on this machine.', + ); + printEmailDomainOutcome(row); +} + +function emailDomainStatusText(status: EmailDomainResponse['status']): string { + if (status === 'active') { + return pc.green('active'); + } + if (status === 'pending') { + return pc.yellow('pending'); + } + return pc.red(status === 'failed' ? 'failed' : status.replace('_', ' ')); +} + +/** + * The dashboard path for the one remaining human step. The row does not + * carry the zone name, so a subdomain row strips its first label — the zone + * the walk almost always lands on (`mail.acme.com` → `acme.com`). + */ +function routingSubdomainInstruction(domain: string, mode: EmailDomainResponse['mode']): string { + const zoneGuess = mode === 'subdomain' ? domain.split('.').slice(1).join('.') : domain; + return `add ${domain} in the Cloudflare dashboard — Email Routing → ${zoneGuess} → Settings → Subdomains (no API exists for it)`; +} + +/** + * The shared result render for add and sync: the row as a block, then the + * one guidance line the status calls for. `error` is printed verbatim — the + * api guarantees it names a step or a CF error, never credential material. + */ +function printEmailDomainOutcome(row: EmailDomainResponse): void { + if (row.status === 'failed') { + const step = row.setup_state?.failed_step; + log.error( + `email: ${row.domain} failed${step ? ` at ${step.replaceAll('_', ' ')}` : ''}${row.error ? ` — ${row.error}` : ''}`, + ); + log.info( + `Fix the step above, then re-run \`void email domain add ${row.domain}\` — adding again replaces the credential and retries.`, + ); + return; + } + + const lines = [ + `Domain: ${row.domain}`, + `Status: ${emailDomainStatusText(row.status)}`, + `Mode: ${row.mode ?? '—'}`, + `Credential: ${row.credential_kind === 'oauth_grant' ? 'OAuth grant' : 'API token'}`, + ]; + if (row.relay_worker_name) { + lines.push( + `Relay: ${row.relay_worker_name}${row.relay_version !== null ? ` v${row.relay_version}` : ''}`, + ); + } + if (row.token_expires_on) { + lines.push(`Token TTL: expires ${row.token_expires_on}`); + } + note(lines.join('\n'), 'Email Domain'); + + const remaining = row.setup_state?.remaining_steps ?? []; + if (row.status === 'pending' && remaining.includes('routing_subdomain')) { + log.warn(`One step only you can do: ${routingSubdomainInstruction(row.domain, row.mode)}.`); + log.info(`Then run \`void email domain status ${row.domain}\` to poll.`); + return; + } + if (row.status === 'pending') { + log.info(`Run \`void email domain status ${row.domain}\` to poll.`); + return; + } + if (row.status === 'token_revoked' || row.status === 'token_expired') { + log.warn( + `The stored credential was ${row.status === 'token_revoked' ? 'revoked at Cloudflare' : 'left to expire'} — re-run \`void email domain add ${row.domain}\` with a fresh grant or token. Rules and the relay stay.`, + ); + return; + } + if (remaining.includes('sending_onboarding')) { + log.info( + `Inbound is live. Sending to arbitrary recipients needs Workers Paid — until then sendEmail() works to verified destinations only. After upgrading, run \`void email domain sync ${row.domain}\` to finish onboarding.`, + ); + } + log.success( + `${row.domain} is live — send with \`sendEmail({ from: 'you@${row.domain}', … })\`; inbound mail to any address on ${row.domain} reaches your email/ handlers.`, + ); +} + +/** + * `void email domain status ` — exported for the unit test. Re-probes + * the credential and the relay on every call (the api does it), so this is + * also the drift report: it never fights the customer's edits, it names them. + */ +export async function emailDomainStatus( + client: Pick, + projectId: string, + rawDomain: string, +): Promise { + const domain = normalizeEmailDomainInput(rawDomain); + const row: EmailDomainStatusResponse = await client.getEmailDomain(projectId, domain); + + const lines = [ + `Domain: ${row.domain}`, + `Status: ${emailDomainStatusText(row.status)}`, + `Mode: ${row.mode ?? '—'}`, + ]; + const credential = + row.credential_status === 'probe_failed' + ? `${row.credential_kind === 'oauth_grant' ? 'OAuth grant' : 'API token'} · probe failed (stored view shown)` + : `${row.credential_kind === 'oauth_grant' ? 'OAuth grant' : 'API token'} · ${row.credential_status}`; + lines.push(`Credential: ${credential}`); + if (row.token_id) { + lines.push( + `Token: id ${row.token_id}${row.token_expires_on ? ` · expires ${row.token_expires_on}` : ''}`, + ); + } + if (row.relay_worker_name) { + let relay = `Relay: ${row.relay_worker_name}${row.relay_version !== null ? ` v${row.relay_version}` : ''}`; + if (row.relay_missing === true) { + relay += ' · missing from the account'; + } else if (row.relay_drift) { + relay += ` · drifted (current is v${row.current_relay_version})`; + } + lines.push(relay); + } + if (row.setup_state?.failed_step) { + lines.push(`Failed step: ${row.setup_state.failed_step.replaceAll('_', ' ')}`); + } + lines.push(`Catch-all: ${row.catch_all}`); + note(lines.join('\n'), 'Email Domain'); + + if (row.error) { + log.error(`email: ${row.error}`); + } + const remaining = row.setup_state?.remaining_steps ?? []; + if (remaining.includes('routing_subdomain')) { + log.warn(`One step only you can do: ${routingSubdomainInstruction(row.domain, row.mode)}.`); + } + if (remaining.includes('sending_onboarding')) { + log.info( + `Sending to arbitrary recipients needs Workers Paid — inbound works; sendEmail() to verified destinations only. After upgrading, run \`void email domain sync ${row.domain}\`.`, + ); + } + if (row.relay_missing === true || row.relay_drift) { + log.info(`Run \`void email domain sync ${row.domain}\` to redeploy the relay in place.`); + } + if (row.catch_all_drift) { + log.info(`Catch-all drifted — run \`void email domain sync ${row.domain}\` to re-point it.`); + } + if (row.status === 'token_revoked' || row.status === 'token_expired') { + log.warn( + `Re-run \`void email domain add ${row.domain}\` with a fresh grant or token — adding again replaces the credential, rules stay.`, + ); + } +} + +/** `void email domain list` — exported for the unit test. */ +export async function emailDomainList( + client: Pick, + projectId: string, +): Promise { + const rows = await client.listEmailDomains(projectId); + if (rows.length === 0) { + log.info( + 'No email domains. Run `void email domain add ` to send and receive at your own domain on a Cloudflare zone.', + ); + return; + } + const width = Math.max(...rows.map((row) => row.domain.length)); + const lines = rows.map( + (row) => + ` ${row.domain.padEnd(width)} ${emailDomainStatusText(row.status)} ${row.mode ?? '—'}`, + ); + note(lines.join('\n'), 'Email Domains'); +} + +/** `void email domain sync ` — exported for the unit test. */ +export async function emailDomainSync( + client: Pick, + projectId: string, + rawDomain: string, +): Promise { + const domain = normalizeEmailDomainInput(rawDomain); + const row = await client.syncEmailDomain(projectId, domain); + if (row.status !== 'failed') { + log.success( + `Relay redeployed${row.relay_version !== null ? ` at v${row.relay_version}` : ''} with a rotated secret.`, + ); + // catch_all is absent when the row carries no zone_id. + if (row.catch_all === 'foreign_conflict') { + log.warn( + "Catch-all: the zone's catch-all points at a different worker and was NOT overwritten — change it in the zone's Email Routing settings if inbound mail should reach this relay.", + ); + } else if (row.catch_all !== undefined) { + log.info(`Catch-all: ${row.catch_all.replaceAll('_', ' ')}`); + } + } + printEmailDomainOutcome(row); +} + +/** `void email domain remove ` — exported for the unit test. */ +export async function emailDomainRemove( + client: Pick, + projectId: string, + rawDomain: string, + options: { force?: boolean; exit?: (code: number) => never } = {}, +): Promise { + const domain = normalizeEmailDomainInput(rawDomain); + const result = await client.removeEmailDomain(projectId, domain, options.force); + + if (!result.removed) { + // Kept for retry: a Cloudflare-side step failed without --force, so the + // row (and the stored credential the retry needs) stays. + const steps = result.failed_steps?.length ? result.failed_steps.join(', ') : 'unknown'; + log.error(`email: could not remove ${domain} — failed Cloudflare-side steps: ${steps}.`); + log.info( + `The registration was kept — retry \`void email domain remove ${domain}\` once the Cloudflare-side problem is fixed, or re-run with --force to drop the row anyway.`, + ); + (options.exit ?? ((code: number): never => process.exit(code)))(1); + } + + log.success( + `Removed ${domain} — the platform row, the stored credential and the relay secret are gone.`, + ); + const failed = result.failed_steps ?? []; + if ( + failed.length > 0 && + (result.forced === true || failed.some((step) => step !== 'revoke_grant')) + ) { + log.warn( + `Cloudflare-side cleanup failed for: ${failed.join(', ')} — delete the relay worker and reset the catch-all in the zone's Email Routing settings yourself.`, + ); + } else if (failed.length > 0) { + // Only the grant revoke failed: the rules and relay are already gone. + log.info( + 'Note: the Cloudflare grant could not be revoked (already invalid or Cloudflare unreachable) — no mail impact.', + ); + } +} + +async function runEmailDomainCommand( + client: PlatformClient, + projectId: string, + args: EmailArgs, +): Promise { + switch (args.domainVerb) { + case 'add': + return emailDomainAdd(client, projectId, args.domain!, args.subdomain); + case 'status': + return emailDomainStatus(client, projectId, args.domain!); + case 'list': + return emailDomainList(client, projectId); + case 'sync': + return emailDomainSync(client, projectId, args.domain!); + case 'remove': + return emailDomainRemove(client, projectId, args.domain!, { force: args.force }); + } +} + // ── Mode B: the developer's own Cloudflare account ───────────────────────────── /** diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index efa746858..fc485e4a2 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -497,7 +497,8 @@ const HELP_TREE: HelpTree = { }, }, email: { - summary: 'Inspect email activity and manage verified recipients.', + summary: + 'Inspect email activity, manage verified recipients, and send and receive at your own domain.', usage: ['void email '], commands: [ { command: 'usage', description: 'Show monthly outbound/inbound counts and quota' }, @@ -505,6 +506,10 @@ const HELP_TREE: HelpTree = { { command: 'destinations', description: 'List verified recipient addresses' }, { command: 'allow
', description: 'Add a recipient and trigger CF verification' }, { command: 'disallow
', description: 'Remove a recipient from the allowlist' }, + { + command: 'domain ', + description: 'Send and receive at your own domain on a Cloudflare zone', + }, { command: 'status --platform cloudflare', description: 'Show the email setup state and address map on your own account', @@ -545,6 +550,77 @@ const HELP_TREE: HelpTree = { 'Remove a recipient from the verified allowlist.', 'void email disallow
[options]', ), + // The one nested group: verbs parse in email-args.ts (`domain `). + // Void-platform-only, so `--project` is global here; `--subdomain` is `add`-only. + domain: { + summary: 'Send and receive at your own domain on a Cloudflare zone.', + usage: ['void email domain [] [options]'], + commands: [ + { + command: 'add ', + description: 'Register the domain (OAuth grant, or a scoped API token)', + }, + { + command: 'status ', + description: 'Show state; re-probes the credential and relay, polls a pending row', + }, + { command: 'list', description: 'List registered email domains' }, + { + command: 'sync ', + description: 'Redeploy the relay at the current version and rotate its secret', + }, + { + command: 'remove ', + description: 'Delete the registration, stored credential, and relay secret', + }, + ], + options: [ + { + command: '--subdomain ', + description: 'On add: register this subdomain instead of the proposed mail.', + }, + { command: '--project ', description: 'Project name override' }, + ], + children: { + add: { + summary: + 'Register a domain on a Cloudflare zone you own for sending and receiving. Proposes mail. when the apex already carries MX.', + usage: ['void email domain add [options]'], + options: [ + { + command: '--subdomain ', + description: 'Register this subdomain instead of the proposed mail.', + }, + { command: '--project ', description: 'Project name override' }, + ], + }, + status: withProjectOption( + 'Show a registered domain, re-probing its credential and relay.', + 'void email domain status [options]', + ), + list: withProjectOption( + 'List registered email domains.', + 'void email domain list [options]', + ), + sync: withProjectOption( + 'Redeploy the relay at the current version and rotate its secret.', + 'void email domain sync [options]', + ), + // Not `withProjectOption`: `remove` has a flag of its own (`--force`), + // same shape as the `email logs` page above. + remove: { + summary: 'Delete the registration, stored credential, and relay secret.', + usage: ['void email domain remove [options]'], + options: [ + { + command: '--force', + description: 'Drop the row even when Cloudflare-side cleanup fails', + }, + { command: '--project ', description: 'Project name override' }, + ], + }, + }, + }, // Mode B (design doc 0078): both read the local project + your wrangler session, // never a Void project, so neither takes `--project`. status: { diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index e40254922..5647b3630 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1581,8 +1581,9 @@ window.__vite_plugin_react_preamble_installed__ = true; // (the slug is invisible to them — see design-doc 0078). When a slug is // configured (`__VOID_PROJECT_SLUG`) the dispatcher strips everything up to // and including the first `+` from the local-part before running it through - // the pattern table. Without one — a worker on the developer's own zone — the - // full local part is matched, so `support+T-42@zone` reaches + // the pattern table. Without one — a worker on the developer's own zone, or + // a relayed custom-domain envelope (`viaDomain`, suppressed by `handleEmail`) + // — the full local part is matched, so `support+T-42@zone` reaches // `email/support+[ticket].ts` there too. const email = scan.email; const emailDir = options.emailDir; @@ -2903,12 +2904,22 @@ ${envValidateCall}${isrDeploymentStamp} const userEnv = __filterInternalBinding // `message.to` is the bare `@` rather than the wire form, and to // the generated `__emailHandler`, which routes on the wire address // (`__voidPlatformTo`) and strips the `+` prefix iff a slug is set. + // + // Except on the relay lane: an envelope carrying `viaDomain` arrived via + // POST /email/relay from a customer zone (design doc 0078, "Custom domains + // on Cloudflare") and its recipient carries no `+` prefix — the + // dispatcher runs in no-prefix mode (Mode B item 4), so `support+T-42@acme.com` + // reaches `email/support+[ticket].ts` with the tag intact. Provisioning + // injects `__VOID_PROJECT_SLUG` unconditionally, so the slug must be + // suppressed HERE: left applied, the strip would take everything up to the + // first `+` and dispatch the bare tag to `_default` or a wrong `[user]`. const emailHandler = hasEmail ? remotePath ? `async function handleEmail(envelope, env, ctx) { ${envValidateCall} if (env.__VOID_REMOTE === "1") env = ${createRemoteEnvCall}; const userEnv = __filterInternalBindings(env); - const __slug = typeof env.__VOID_PROJECT_SLUG === "string" && env.__VOID_PROJECT_SLUG.length > 0 ? env.__VOID_PROJECT_SLUG : undefined; + const __relayed = typeof envelope.viaDomain === "string" && envelope.viaDomain.length > 0; + const __slug = __relayed ? undefined : (typeof env.__VOID_PROJECT_SLUG === "string" && env.__VOID_PROJECT_SLUG.length > 0 ? env.__VOID_PROJECT_SLUG : undefined); const { message, getActions } = __createMessageProxy(envelope, { slug: __slug }); await __withRawEnv(env, () => withRuntimeEnv(env, () => __emailHandler(message, userEnv, ctx, { slug: __slug }))); const __actions = getActions(); @@ -2917,7 +2928,8 @@ ${envValidateCall} if (env.__VOID_REMOTE === "1") env = ${createRemoteEnvCall}; }` : `async function handleEmail(envelope, env, ctx) { ${envValidateCall} const userEnv = __filterInternalBindings(env); - const __slug = typeof env.__VOID_PROJECT_SLUG === "string" && env.__VOID_PROJECT_SLUG.length > 0 ? env.__VOID_PROJECT_SLUG : undefined; + const __relayed = typeof envelope.viaDomain === "string" && envelope.viaDomain.length > 0; + const __slug = __relayed ? undefined : (typeof env.__VOID_PROJECT_SLUG === "string" && env.__VOID_PROJECT_SLUG.length > 0 ? env.__VOID_PROJECT_SLUG : undefined); const { message, getActions } = __createMessageProxy(envelope, { slug: __slug }); await __withRawEnv(env, () => withRuntimeEnv(env, () => __emailHandler(message, userEnv, ctx, { slug: __slug }))); const __actions = getActions(); diff --git a/packages/void/src/runtime/email/inbound.ts b/packages/void/src/runtime/email/inbound.ts index 75a2f9029..a7211101a 100644 --- a/packages/void/src/runtime/email/inbound.ts +++ b/packages/void/src/runtime/email/inbound.ts @@ -120,6 +120,15 @@ function tryReadEmailDomain(): string | undefined { return typeof raw === 'string' && raw.length > 0 ? raw : undefined; } +// The relay-lane marker `createMessageProxy` sets from `envelope.viaDomain` +// — the registered custom domain the message arrived on. Undefined for a +// platform-lane or own-account message, and for a hand-built message in a +// test that never went through the proxy. +function readRelayDomain(message: ForwardableEmailMessage): string | undefined { + const raw: unknown = (message as { __voidRelayDomain?: unknown }).__voidRelayDomain; + return typeof raw === 'string' && raw.length > 0 ? raw : undefined; +} + export interface EmailHandlerInfo { /** * Captured params from dynamic / tagged route segments. For example, a @@ -230,6 +239,15 @@ export interface EmailEnvelope { */ raw: ReadableStream | Uint8Array; rawSize: number; + /** + * The registered custom domain this message arrived on, set only by the + * platform's relay lane (`POST /email/relay` — design doc 0078, "Custom + * domains on Cloudflare"). Undefined on the platform mail zone. A relayed + * recipient carries no `+` prefix, so the generated dispatcher runs + * in no-prefix mode for it (Mode B item 4) and `replyEmail` defaults + * `from` to the address that received it, on this domain. + */ + viaDomain?: string; } /** @@ -473,11 +491,20 @@ export function createMessageProxy( const actions: Array = []; const headers = new Headers(envelope.headers); + // A relayed recipient carries no `+` prefix (the relay lane is + // authenticated by the domain's relay secret, and `viaDomain` names that + // domain), so the slug is inert here even if a caller passed one — the + // generated `handleEmail` already suppresses it, and this keeps a + // coincidental `+` local-part prefix from being stripped off a + // customer-domain address. + const slug = + envelope.viaDomain === undefined || envelope.viaDomain === '' ? opts.slug : undefined; + // Strip the platform-injected `+` prefix from message.to so handler // authors see the same address shape they wrote in `email/.ts`. The // dispatcher strips the same prefix for routing; mirroring it here keeps // the user-visible envelope consistent with the routing surface. - const userVisibleTo = stripSlugFromAddress(envelope.to, opts.slug); + const userVisibleTo = stripSlugFromAddress(envelope.to, slug); // Cache raw bytes lazily so repeated reads (e.g. parseEmail() followed by // anything touching message.raw) work. Real CF messages are one-shot, but @@ -718,6 +745,22 @@ export function createMessageProxy( }); } + // Mark the relay lane: the platform proved the domain's relay secret, so + // `viaDomain` names the one registered domain this message arrived on. + // `buildReplyMessage` reads the marker to default `from` to the address + // that received the message (on the customer domain) instead of the + // shared-sender `+noreply@` default — the platform + // pins a relayed reply to the receiving project's registered domains. + // Non-enumerable for the same reason as `__voidPlatformTo` above. + if (typeof envelope.viaDomain === 'string' && envelope.viaDomain.length > 0) { + Object.defineProperty(message, '__voidRelayDomain', { + value: envelope.viaDomain, + enumerable: false, + writable: false, + configurable: false, + }); + } + // Register cache entry so parseEmail() can replay bytes without consuming // the proxy's `raw` getter (which would otherwise hand out a fresh stream // per access — fine for correctness but wasteful for large messages). @@ -1148,9 +1191,19 @@ export async function buildReplyMessage( // With no slug there is no shared sender to pin to: the message was // delivered to a real address on the developer's own zone, and replying // from that address is what a reply means. + // + // A relayed message (a custom domain on the customer's own Cloudflare + // zone — the `__voidRelayDomain` marker from `createMessageProxy`) is the + // same shape as the own-account case even though a slug IS injected: + // `message.to` is a real address on the customer's domain, the platform + // pins relayed replies to the receiving project's registered domains, and + // the send leaves through the customer account's REST send. The shared + // `+noreply@` default would fail that pin. let fromAddr: Address; if (opts.from !== undefined) { fromAddr = opts.from; + } else if (readRelayDomain(message) !== undefined) { + fromAddr = message.to; } else { const slug = tryReadProjectSlug(); if (slug) { diff --git a/packages/void/test/unit/cf-oauth.test.ts b/packages/void/test/unit/cf-oauth.test.ts new file mode 100644 index 000000000..7bd921974 --- /dev/null +++ b/packages/void/test/unit/cf-oauth.test.ts @@ -0,0 +1,369 @@ +import { createHash } from 'node:crypto'; +import { log } from '@clack/prompts'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; +import { + CF_OAUTH_CALLBACK_PATH, + CF_OAUTH_CALLBACK_PORT, + CF_OAUTH_CLIENT_ID, + CF_OAUTH_REDIRECT_URI, + CF_OAUTH_REVOKE_URL, + CF_OAUTH_SCOPE, + CF_OAUTH_TOKEN_URL, + revokeCfOauthGrant, + runCfOauthGrant, +} from '../../src/cli/cf-oauth.ts'; + +/** + * The PKCE grant on wrangler's public client (contract 8) against a mocked + * loopback/token endpoint — no real network: the loopback server on :8976 is + * real (the platform login tests do the same on a random port), and + * Cloudflare's token endpoint is a fetch stub. Token values are inert + * placeholders and are never printed. + */ + +const mockExecFile = vi.fn(); +const originalFetch = globalThis.fetch.bind(globalThis); + +const AUTH_CODE = 'cf-auth-code-placeholder'; +const REFRESH_SENTINEL = 'cf-refresh-token-placeholder'; + +let tokenExchangeBodies: Array; +let tokenEndpointResponse: () => Response | Promise; + +function codeChallengeFor(verifier: string): string { + return createHash('sha256') + .update(verifier) + .digest('base64') + .replaceAll('+', '-') + .replaceAll('/', '_') + .replaceAll('=', ''); +} + +vi.mock('node:child_process', () => ({ + execFile: (...args: Array) => mockExecFile(...args), +})); + +beforeEach(() => { + mockExecFile.mockReset(); + tokenExchangeBodies = []; + tokenEndpointResponse = () => + Response.json({ + access_token: 'cf-access-token-placeholder', + refresh_token: REFRESH_SENTINEL, + expires_in: 3600, + }); + vi.spyOn(log, 'warn').mockImplementation(() => {}); + + vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => { + const url = + input instanceof Request ? input.url : input instanceof URL ? input.href : input.toString(); + if (url.startsWith('http://localhost:') || url.startsWith('http://127.0.0.1:')) { + return originalFetch(input, init); + } + if (url === CF_OAUTH_TOKEN_URL) { + tokenExchangeBodies.push(new URLSearchParams(init?.body?.toString() ?? '')); + return tokenEndpointResponse(); + } + throw new Error(`unexpected network call in test: ${url}`); + }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +async function startGrant(): Promise<{ url: URL; grant: Promise }> { + let ready!: (url: URL) => void; + const urlPromise = new Promise((resolve) => { + ready = resolve; + }); + const grant = runCfOauthGrant({ + timeoutMs: 5000, + onUrl: (url) => ready(new URL(url)), + }); + return { url: await urlPromise, grant }; +} + +function callbackUrl(): URL { + return new URL(CF_OAUTH_REDIRECT_URI); +} + +describe('runCfOauthGrant', () => { + it('runs the full PKCE flow and resolves the grant refresh token', async () => { + const { url, grant } = await startGrant(); + + // The authorize URL is Cloudflare's consent endpoint with the pinned + // contract-8 parameters — wrangler's client, the fixed loopback + // redirect, the email scope set, and an S256 challenge. + expect(url.origin + url.pathname).toBe('https://dash.cloudflare.com/oauth2/auth'); + expect(url.searchParams.get('response_type')).toBe('code'); + expect(url.searchParams.get('client_id')).toBe(CF_OAUTH_CLIENT_ID); + expect(url.searchParams.get('redirect_uri')).toBe(CF_OAUTH_REDIRECT_URI); + expect(url.searchParams.get('scope')).toBe(CF_OAUTH_SCOPE); + expect(url.searchParams.get('code_challenge_method')).toBe('S256'); + expect(url.searchParams.get('code_challenge')).toEqual(expect.any(String)); + const state = url.searchParams.get('state'); + expect(state).toEqual(expect.any(String)); + + // The Wrangler-named consent page warning is printed before opening. + expect(vi.mocked(log.warn)).toHaveBeenCalledWith(expect.stringContaining('names Wrangler')); + + const callback = callbackUrl(); + callback.searchParams.set('state', state!); + callback.searchParams.set('code', AUTH_CODE); + const pageResponse = await fetch(callback); + expect(pageResponse.status).toBe(200); + expect(await pageResponse.text()).toContain('Cloudflare connected'); + + await expect(grant).resolves.toEqual({ refreshToken: REFRESH_SENTINEL }); + + // The exchange is form-encoded against the token endpoint with the code, + // the pinned redirect and client, and the verifier behind the challenge. + expect(tokenExchangeBodies).toHaveLength(1); + const body = tokenExchangeBodies[0]!; + expect(body.get('grant_type')).toBe('authorization_code'); + expect(body.get('code')).toBe(AUTH_CODE); + expect(body.get('redirect_uri')).toBe(CF_OAUTH_REDIRECT_URI); + expect(body.get('client_id')).toBe(CF_OAUTH_CLIENT_ID); + const verifier = body.get('code_verifier'); + expect(verifier).toEqual(expect.any(String)); + expect(codeChallengeFor(verifier!)).toBe(url.searchParams.get('code_challenge')); + + // The browser was asked to open the consent URL, via argv (never a shell). + expect(mockExecFile).toHaveBeenCalled(); + }); + + it('rejects a mismatched state but keeps listening for the real callback', async () => { + const { url, grant } = await startGrant(); + const state = url.searchParams.get('state')!; + + const attack = callbackUrl(); + attack.searchParams.set('state', 'attacker-state'); + attack.searchParams.set('code', AUTH_CODE); + expect((await fetch(attack)).status).toBe(400); + expect(tokenExchangeBodies).toHaveLength(0); + + const valid = callbackUrl(); + valid.searchParams.set('state', state); + valid.searchParams.set('code', AUTH_CODE); + expect((await fetch(valid)).status).toBe(200); + await expect(grant).resolves.toEqual({ refreshToken: REFRESH_SENTINEL }); + }); + + it('rejects when the customer denies the consent', async () => { + const { url, grant } = await startGrant(); + const rejection = expect(grant).rejects.toThrow(/consent was denied/); + + const denied = callbackUrl(); + denied.searchParams.set('state', url.searchParams.get('state')!); + denied.searchParams.set('error', 'access_denied'); + const pageResponse = await fetch(denied); + expect(pageResponse.status).toBe(403); + expect(await pageResponse.text()).toContain('consent was denied'); + + await rejection; + expect(tokenExchangeBodies).toHaveLength(0); + }); + + it('rejects when the token exchange fails, without echoing the response body', async () => { + const canary = 'body-canary-never-in-errors'; + tokenEndpointResponse = () => new Response(canary, { status: 400 }); + const { url, grant } = await startGrant(); + const rejection = expect(grant).rejects.toThrow(/HTTP 400/); + + const callback = callbackUrl(); + callback.searchParams.set('state', url.searchParams.get('state')!); + callback.searchParams.set('code', AUTH_CODE); + const pageResponse = await fetch(callback); + // The exchange runs inside the request handler, so a failure renders the + // failure page, never the success page. + expect(pageResponse.status).toBe(400); + expect(await pageResponse.text()).toContain('Could not complete'); + + const error = await grant.catch((err: unknown) => err); + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).not.toContain(canary); + await rejection; + }); + + it('rejects when the answer carries no refresh token', async () => { + tokenEndpointResponse = () => Response.json({ access_token: 'cf-access-token-placeholder' }); + const { url, grant } = await startGrant(); + const rejection = expect(grant).rejects.toThrow(/no refresh token/); + + const callback = callbackUrl(); + callback.searchParams.set('state', url.searchParams.get('state')!); + callback.searchParams.set('code', AUTH_CODE); + await fetch(callback); + await rejection; + }); + + it('rejects when the callback port is already in use', async () => { + const http = await import('node:http'); + const blocker = http.createServer((_req, res) => res.end('busy')); + await new Promise((resolve) => + blocker.listen(CF_OAUTH_CALLBACK_PORT, '127.0.0.1', resolve), + ); + try { + await expect(runCfOauthGrant({ timeoutMs: 5000 })).rejects.toThrow( + new RegExp(`could not start the local callback server on port ${CF_OAUTH_CALLBACK_PORT}`), + ); + // No browser, no consent warning — nothing opened. + expect(mockExecFile).not.toHaveBeenCalled(); + } finally { + await new Promise((resolve) => blocker.close(resolve)); + } + }); + + it('rejects on abort (Enter switching to the token path) and closes the server', async () => { + const controller = new AbortController(); + const { url, grant } = await (async () => { + let ready!: (url: URL) => void; + const urlPromise = new Promise((resolve) => { + ready = resolve; + }); + const grantPromise = runCfOauthGrant({ + timeoutMs: 5000, + signal: controller.signal, + onUrl: (url) => ready(new URL(url)), + }); + return { url: await urlPromise, grant: grantPromise }; + })(); + expect(url).toBeInstanceOf(URL); + + controller.abort(); + await expect(grant).rejects.toThrow(/cancelled/); + + // The port is free again immediately — the next grant can bind it. + const { url: secondUrl, grant: secondGrant } = await startGrant(); + const callback = callbackUrl(); + callback.searchParams.set('state', secondUrl.searchParams.get('state')!); + callback.searchParams.set('code', AUTH_CODE); + expect((await fetch(callback)).status).toBe(200); + await expect(secondGrant).resolves.toEqual({ refreshToken: REFRESH_SENTINEL }); + }); + + it('revokes the minted grant when the exchange resolves after the flow settled', async () => { + const controller = new AbortController(); + const revokeBodies: Array = []; + let resolveExchange!: (response: Response) => void; + tokenEndpointResponse = () => + new Promise((resolve) => { + resolveExchange = resolve; + }); + // The default stub throws on the revoke endpoint — re-stub with a branch + // that captures it. + vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => { + const url = + input instanceof Request ? input.url : input instanceof URL ? input.href : input.toString(); + if (url.startsWith('http://localhost:') || url.startsWith('http://127.0.0.1:')) { + return originalFetch(input, init); + } + if (url === CF_OAUTH_TOKEN_URL) { + tokenExchangeBodies.push(new URLSearchParams(init?.body?.toString() ?? '')); + return tokenEndpointResponse(); + } + if (url === CF_OAUTH_REVOKE_URL) { + revokeBodies.push(new URLSearchParams(init?.body?.toString() ?? '')); + return new Response(null, { status: 200 }); + } + throw new Error(`unexpected network call in test: ${url}`); + }); + + let ready!: (url: URL) => void; + const urlPromise = new Promise((resolve) => { + ready = resolve; + }); + const grant = runCfOauthGrant({ + timeoutMs: 5000, + signal: controller.signal, + onUrl: (url) => ready(new URL(url)), + }); + const url = await urlPromise; + const rejection = expect(grant).rejects.toThrow(/cancelled/); + + // Fire the valid callback; the exchange hangs inside the handler. + const callback = callbackUrl(); + callback.searchParams.set('state', url.searchParams.get('state')!); + callback.searchParams.set('code', AUTH_CODE); + const pagePromise = fetch(callback); + await vi.waitFor(() => expect(tokenExchangeBodies).toHaveLength(1)); + + // Enter switching to the token path settles the flow mid-exchange. + controller.abort(); + await rejection; + + // The exchange then completes: Cloudflare minted the grant and the CLI is + // the only actor holding it — it must be revoked, not stranded. + resolveExchange( + Response.json({ + access_token: 'cf-access-token-placeholder', + refresh_token: REFRESH_SENTINEL, + expires_in: 3600, + }), + ); + const pageResponse = await pagePromise; + expect(pageResponse.status).toBe(200); + expect(await pageResponse.text()).toContain('cancelled'); + + await vi.waitFor(() => expect(revokeBodies).toHaveLength(1)); + expect(revokeBodies[0]!.get('token')).toBe(REFRESH_SENTINEL); + expect(revokeBodies[0]!.get('token_type_hint')).toBe('refresh_token'); + expect(revokeBodies[0]!.get('client_id')).toBe(CF_OAUTH_CLIENT_ID); + }); + + it(`listens on the pinned ${CF_OAUTH_CALLBACK_PORT}${CF_OAUTH_CALLBACK_PATH} and 404s everything else`, async () => { + const { url, grant } = await startGrant(); + const rejection = expect(grant).rejects.toThrow(); // settled below via deny + + expect(new URL(CF_OAUTH_REDIRECT_URI).pathname).toBe(CF_OAUTH_CALLBACK_PATH); + const off = new URL(CF_OAUTH_REDIRECT_URI); + off.pathname = '/favicon.ico'; + expect((await fetch(off)).status).toBe(404); + + const denied = new URL(CF_OAUTH_REDIRECT_URI); + denied.searchParams.set('state', url.searchParams.get('state')!); + denied.searchParams.set('error', 'access_denied'); + await fetch(denied); + await rejection; + }); +}); + +describe('revokeCfOauthGrant', () => { + it('posts the RFC 7009 form and reports true on a 2xx', async () => { + const fetchSpy = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => new Response(null, { status: 200 }), + ); + vi.stubGlobal('fetch', fetchSpy); + + await expect(revokeCfOauthGrant(REFRESH_SENTINEL)).resolves.toBe(true); + + expect(fetchSpy).toHaveBeenCalledTimes(1); + const [url, init] = fetchSpy.mock.calls[0]!; + expect(String(url)).toBe(CF_OAUTH_REVOKE_URL); + const form = new URLSearchParams(String(init?.body)); + expect(form.get('token')).toBe(REFRESH_SENTINEL); + expect(form.get('token_type_hint')).toBe('refresh_token'); + expect(form.get('client_id')).toBe(CF_OAUTH_CLIENT_ID); + }); + + it('reports false on a non-2xx answer — the grant may still be live', async () => { + const fetchSpy = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response('nope', { status: 500 }), + ); + vi.stubGlobal('fetch', fetchSpy); + + await expect(revokeCfOauthGrant(REFRESH_SENTINEL)).resolves.toBe(false); + }); + + it('reports false on a network failure, never throwing', async () => { + const fetchSpy = vi.fn(async () => { + throw new TypeError('fetch failed'); + }); + vi.stubGlobal('fetch', fetchSpy); + + await expect(revokeCfOauthGrant(REFRESH_SENTINEL)).resolves.toBe(false); + }); +}); diff --git a/packages/void/test/unit/cli-help.test.ts b/packages/void/test/unit/cli-help.test.ts index 0f29c00c1..3faa317c2 100644 --- a/packages/void/test/unit/cli-help.test.ts +++ b/packages/void/test/unit/cli-help.test.ts @@ -155,4 +155,53 @@ describe('rendered help advertises the flags the parser honours', () => { expect(group).toContain('status --platform cloudflare'); expect(group).toContain('setup --platform cloudflare'); }); + + // The nested `domain` group is the one email command with its own verbs; the + // group entry is on the email page, and every verb keeps its own page so the + // printed `void help email domain ` hint actually resolves. + it('lists `email domain` on the email page and resolves the domain help pages', () => { + expect( + parseEmailArgs(['domain', 'add', 'acme.com', '--subdomain', 'mail', '--project', 'acme']), + ).toMatchObject({ + subcommand: 'domain', + domainVerb: 'add', + domain: 'acme.com', + subdomain: 'mail', + projectSlug: 'acme', + }); + + const group = render(['email']); + expect(group).toContain('domain '); + + expect(hasHelpPage(['email', 'domain'])).toBe(true); + expect(getHelpPath(['email', 'domain', '--help'])).toEqual(['email', 'domain']); + const page = render(['email', 'domain']); + for (const verb of [ + 'add ', + 'status ', + 'list', + 'sync ', + 'remove ', + ]) { + expect(page).toContain(verb); + } + expect(page).toContain('--subdomain '); + expect(page).toContain('--project '); + + for (const verb of ['add', 'status', 'list', 'sync', 'remove']) { + expect(hasHelpPage(['email', 'domain', verb])).toBe(true); + } + expect(render(['email', 'domain', 'add'])).toContain( + 'void email domain add [options]', + ); + + // `remove` is the one domain verb with a flag of its own. + expect(parseEmailArgs(['domain', 'remove', 'acme.com', '--force'])).toMatchObject({ + domainVerb: 'remove', + force: true, + }); + const removePage = render(['email', 'domain', 'remove']); + expect(removePage).toContain('--force'); + expect(removePage).toContain('--project '); + }); }); diff --git a/packages/void/test/unit/email-cli-domain.test.ts b/packages/void/test/unit/email-cli-domain.test.ts new file mode 100644 index 000000000..198e7b9bd --- /dev/null +++ b/packages/void/test/unit/email-cli-domain.test.ts @@ -0,0 +1,1296 @@ +import { log, note } from '@clack/prompts'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; +import { + PlatformApiError, + PlatformClient, + type EmailDomainResponse, + type EmailDomainStatusResponse, + type RemoveEmailDomainResponse, +} from '../../src/cli/client.ts'; +import { + buildCfApiTokenTemplateUrl, + classifyCfApiTokenShape, + emailDomainAdd, + emailDomainList, + emailDomainRemove, + emailDomainStatus, + emailDomainSync, + isValidEmailDomainInput, + normalizeEmailDomainInput, + resolveEmailDomainTarget, + type CfTokenVerification, + type EmailDomainAddDeps, +} from '../../src/cli/email.ts'; + +/** + * `void email domain …` (design doc 0078, "Custom domains on Cloudflare"). + * Every browser, clipboard, DNS and stdin touch is a seam; credential values + * here are inert placeholders and are never printed. + */ + +vi.mock('@clack/prompts', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, note: vi.fn() }; +}); + +const LEGACY_TOKEN = `Lgcy-${'a1'.repeat(17)}B`; // 40 chars, [A-Za-z0-9_-] +const CFUT_TOKEN = `cfut_${'c0'.repeat(20)}${'deed'.repeat(2)}`; // 40-char core + checksum tail +const GRANT_SENTINEL = 'grant-refresh-token-placeholder'; + +type LogSpy = ReturnType; + +let successSpy: LogSpy; +let infoSpy: LogSpy; +let warnSpy: LogSpy; +let errorSpy: LogSpy; + +beforeEach(() => { + successSpy = vi.spyOn(log, 'success').mockImplementation(() => {}); + infoSpy = vi.spyOn(log, 'info').mockImplementation(() => {}); + warnSpy = vi.spyOn(log, 'warn').mockImplementation(() => {}); + errorSpy = vi.spyOn(log, 'error').mockImplementation(() => {}); + // Silenced, never asserted: the CI-mode spinner writes through log.step. + vi.spyOn(log, 'step').mockImplementation(() => {}); + vi.mocked(note).mockClear(); +}); + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +function printed(spy: LogSpy): string { + return (spy.mock.calls as Array>).map((call) => String(call[0])).join('\n'); +} + +function notedBlocks(): string { + return vi + .mocked(note) + .mock.calls.map((call) => String(call[0])) + .join('\n'); +} + +function domainRow(overrides: Partial = {}): EmailDomainResponse { + return { + id: 'edom_1', + domain: 'acme.com', + mode: 'apex', + status: 'active', + credential_kind: 'oauth_grant', + relay_worker_name: 'void-email-relay', + relay_version: 1, + token_id: null, + token_expires_on: null, + setup_state: null, + created_at: '2026-09-16T00:00:00Z', + updated_at: '2026-09-16T00:00:00Z', + ...overrides, + }; +} + +function statusRow(overrides: Partial = {}): EmailDomainStatusResponse { + return { + ...domainRow(), + credential_status: 'active', + current_relay_version: 1, + relay_drift: false, + relay_missing: false, + catch_all: 'points_here', + catch_all_drift: false, + ...overrides, + }; +} + +/** exit seam: throws so the command stops the way process.exit would. */ +function exitSpy(): (code: number) => never { + return vi.fn((code: number): never => { + throw new Error(`exit ${code}`); + }); +} + +function neverEnter(): Promise { + return new Promise(() => {}); +} + +describe('buildCfApiTokenTemplateUrl', () => { + it('carries the five pinned permission groups, wildcard resources and the domain name', () => { + const url = new URL(buildCfApiTokenTemplateUrl('acme.com')); + expect(url.origin + url.pathname).toBe('https://dash.cloudflare.com/profile/api-tokens'); + expect(JSON.parse(url.searchParams.get('permissionGroupKeys')!)).toEqual([ + { key: 'zone', type: 'read' }, + { key: 'email_routing_rule', type: 'edit' }, + { key: 'email_sending', type: 'edit' }, + { key: 'workers_scripts', type: 'edit' }, + { key: 'zone_settings', type: 'edit' }, + ]); + expect(url.searchParams.get('accountId')).toBe('*'); + expect(url.searchParams.get('zoneId')).toBe('all'); + // The em dash survives the round trip through percent-encoding. + expect(url.searchParams.get('name')).toBe('Void email — acme.com'); + }); +}); + +describe('classifyCfApiTokenShape', () => { + it('accepts the cfut_ format (prefix + 40 chars + checksum)', () => { + expect(classifyCfApiTokenShape(CFUT_TOKEN)).toBe('cfut'); + // Checksum length is bounded loosely — the docs pin the 40, not the tail. + expect(classifyCfApiTokenShape(`cfut_${'a'.repeat(44)}`)).toBe('cfut'); + expect(classifyCfApiTokenShape(`cfut_${'a'.repeat(64)}`)).toBe('cfut'); + }); + + it('accepts the legacy 40-character form, trimmed', () => { + expect(classifyCfApiTokenShape(LEGACY_TOKEN)).toBe('legacy'); + expect(classifyCfApiTokenShape(` ${LEGACY_TOKEN}\n`)).toBe('legacy'); + }); + + it('refuses other vendor prefixes and the CF global key without a network call', () => { + for (const value of [ + `ghp_${'a'.repeat(36)}`, + `github_pat_${'a'.repeat(30)}`, + `sk-proj-${'a'.repeat(30)}`, + `sk-${'a'.repeat(40)}`, + `xoxb-${'1'.repeat(20)}`, + `xoxp-${'1'.repeat(20)}`, + `cfk_${'a'.repeat(48)}`, + ]) { + expect(classifyCfApiTokenShape(value)).toBe('refused'); + } + }); + + it('rejects everything else as unknown', () => { + expect(classifyCfApiTokenShape('')).toBe('unknown'); + expect(classifyCfApiTokenShape(' ')).toBe('unknown'); + expect(classifyCfApiTokenShape('hello world')).toBe('unknown'); + expect(classifyCfApiTokenShape(`cfut_${'a'.repeat(43)}`)).toBe('unknown'); // core + no checksum + expect(classifyCfApiTokenShape(`cfut_${'a'.repeat(65)}`)).toBe('unknown'); + expect(classifyCfApiTokenShape('a'.repeat(39))).toBe('unknown'); + expect(classifyCfApiTokenShape('a'.repeat(41))).toBe('unknown'); + // An account-token prefix is not accepted — the shape check only passes + // user tokens; anything else is the platform's to refuse. + expect(classifyCfApiTokenShape(`cfat_${'a'.repeat(48)}`)).toBe('unknown'); + // Legacy shape tolerates no whitespace inside. + expect(classifyCfApiTokenShape(`${'a'.repeat(20)} ${'a'.repeat(19)}`)).toBe('unknown'); + }); +}); + +describe('domain input helpers', () => { + it('normalizes like the api (trim, lowercase, strip trailing dot)', () => { + expect(normalizeEmailDomainInput(' ACME.com. ')).toBe('acme.com'); + expect(isValidEmailDomainInput('acme.com')).toBe(true); + expect(isValidEmailDomainInput('mail.acme.com')).toBe(true); + expect(isValidEmailDomainInput('not a domain')).toBe(false); + expect(isValidEmailDomainInput('-bad.com')).toBe(false); + expect(isValidEmailDomainInput('nodot')).toBe(false); + }); + + it('resolves --subdomain labels and hosts under the positional domain', () => { + expect(resolveEmailDomainTarget('acme.com', undefined)).toEqual({ + emailDomain: 'acme.com', + forced: false, + }); + expect(resolveEmailDomainTarget('acme.com', 'mx')).toEqual({ + emailDomain: 'mx.acme.com', + forced: true, + }); + expect(resolveEmailDomainTarget('acme.com', 'mail.acme.com.')).toEqual({ + emailDomain: 'mail.acme.com', + forced: true, + }); + expect(() => resolveEmailDomainTarget('acme.com', 'acme.com')).toThrow( + /must name a subdomain of acme.com/, + ); + expect(() => resolveEmailDomainTarget('acme.com', 'other.com')).toThrow( + /must name a subdomain of acme.com/, + ); + expect(() => resolveEmailDomainTarget('acme.com', '!!!')).toThrow(/invalid --subdomain value/); + }); +}); + +describe('emailDomainAdd', () => { + // The fixed per-invocation attempt id the randomUUID spy returns. + const ATTEMPT_ID = '11111111-2222-4333-8444-555555555555'; + + function addDeps(overrides: Partial = {}): EmailDomainAddDeps { + return { + dns: { resolveMx: vi.fn(async () => []) }, + runGrant: vi.fn(async () => ({ refreshToken: GRANT_SENTINEL })), + isInteractive: true, + waitForEnter: neverEnter, + watchIntervalMs: 1, + watchTimeoutMs: 50, + // Instant reconcile polls — the loop is bounded by attempt count. + sleep: vi.fn(async () => {}), + exit: exitSpy(), + ...overrides, + }; + } + + /** Pins the per-invocation attempt id (restored by the outer afterEach). */ + function mockAttemptId(id: string = ATTEMPT_ID): void { + vi.spyOn(crypto, 'randomUUID').mockReturnValue(id as ReturnType); + } + + it('runs the grant and POSTs the refresh token for an MX-empty apex', async () => { + const addEmailDomain = vi.fn(async () => domainRow({ domain: 'acme.com', mode: 'apex' })); + const deps = addDeps(); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + deps, + ); + + expect(addEmailDomain).toHaveBeenCalledWith('prj_1', { + domain: 'acme.com', + refreshToken: GRANT_SENTINEL, + attemptId: expect.any(String), + }); + expect(printed(infoSpy)).toContain('acme.com has no MX records → using the apex'); + expect(printed(successSpy)).toContain( + 'Grant stored on the platform, encrypted for this project — nothing is kept on this machine.', + ); + expect(notedBlocks()).toContain('Domain: acme.com'); + expect(notedBlocks()).toContain('Mode: apex'); + // The credential never reaches an output. + expect(printed(infoSpy) + printed(successSpy) + notedBlocks()).not.toContain(GRANT_SENTINEL); + }); + + it('proposes mail. when the apex carries MX, and says so', async () => { + const addEmailDomain = vi.fn(async () => + domainRow({ domain: 'mail.acme.com', mode: 'subdomain' }), + ); + const resolveMx = vi.fn(async (name: string) => + name === 'acme.com' ? [{ exchange: 'aspmx.l.google.com.', priority: 1 }] : [], + ); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + addDeps({ dns: { resolveMx } }), + ); + + expect(printed(infoSpy)).toContain( + 'acme.com carries MX for aspmx.l.google.com → apex is off limits', + ); + expect(printed(infoSpy)).toContain('using mail.acme.com [change with --subdomain]'); + expect(addEmailDomain).toHaveBeenCalledWith('prj_1', { + domain: 'mail.acme.com', + refreshToken: GRANT_SENTINEL, + attemptId: expect.any(String), + }); + }); + + it('honours an explicit --subdomain and normalizes the positional domain', async () => { + const addEmailDomain = vi.fn(async () => + domainRow({ domain: 'mx.acme.com', mode: 'subdomain' }), + ); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + ' ACME.com. ', + 'mx', + addDeps(), + ); + + expect(addEmailDomain).toHaveBeenCalledWith('prj_1', { + domain: 'mx.acme.com', + refreshToken: GRANT_SENTINEL, + attemptId: expect.any(String), + }); + }); + + it('refuses an invalid domain or a foreign --subdomain before any grant', async () => { + const runGrant = vi.fn(); + const addEmailDomain = vi.fn(); + + await expect( + emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'not a domain', + undefined, + addDeps({ runGrant }), + ), + ).rejects.toThrow('exit 1'); + expect(printed(errorSpy)).toContain("email: invalid domain 'not a domain'."); + + await expect( + emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + 'other.com', + addDeps({ runGrant }), + ), + ).rejects.toThrow('exit 1'); + expect(printed(errorSpy)).toContain('--subdomain must name a subdomain of acme.com'); + expect(runGrant).not.toHaveBeenCalled(); + expect(addEmailDomain).not.toHaveBeenCalled(); + }); + + it('refuses to run non-interactively (both grant paths need a human)', async () => { + const runGrant = vi.fn(); + await expect( + emailDomainAdd( + { addEmailDomain: vi.fn(), getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + addDeps({ runGrant, isInteractive: false }), + ), + ).rejects.toThrow('exit 1'); + expect(printed(errorSpy)).toContain('needs an interactive terminal'); + expect(runGrant).not.toHaveBeenCalled(); + }); + + it('falls back to the template link + clipboard watch when the grant fails', async () => { + const token = CFUT_TOKEN; + const clipboard = ['clipboard-before', token]; + let reads = 0; + const readClipboard = vi.fn(() => clipboard[Math.min(reads++, clipboard.length - 1)]!); + const clearClipboard = vi.fn(); + const verifyToken = vi.fn(async (): Promise => 'active'); + const openUrl = vi.fn(); + const addEmailDomain = vi.fn(async () => + domainRow({ credential_kind: 'api_token', domain: 'acme.com' }), + ); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + addDeps({ + runGrant: vi.fn(async () => { + throw new Error('cf-oauth: could not start the local callback server on port 8976.'); + }), + readClipboard, + clearClipboard, + verifyToken, + openUrl, + }), + ); + + // The failure is named, the link opened, and only the token-shaped NEW + // clipboard value was verified and POSTed. + expect(printed(warnSpy)).toContain('could not start the local callback server'); + expect(openUrl).toHaveBeenCalledWith(buildCfApiTokenTemplateUrl('acme.com')); + expect(verifyToken).toHaveBeenCalledTimes(1); + expect(clearClipboard).toHaveBeenCalledTimes(1); + expect(addEmailDomain).toHaveBeenCalledWith('prj_1', { + domain: 'acme.com', + apiToken: token, + attemptId: expect.any(String), + }); + expect(printed(successSpy)).toContain( + 'Token stored on the platform, encrypted for this project — nothing is kept on this machine.', + ); + expect(printed(infoSpy) + printed(successSpy) + notedBlocks()).not.toContain(token); + }); + + it('keeps watching past wrong-shape clipboard values without a network call', async () => { + const values = ['snapshot', 'ghp_' + 'a'.repeat(36), 'not a token', LEGACY_TOKEN]; + let reads = 0; + const readClipboard = vi.fn(() => values[Math.min(reads++, values.length - 1)]!); + const verifyToken = vi.fn(async (): Promise => 'active'); + const addEmailDomain = vi.fn(async () => domainRow({ credential_kind: 'api_token' })); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + addDeps({ + runGrant: vi.fn(async () => { + throw new Error('cf-oauth: cancelled.'); + }), + readClipboard, + clearClipboard: vi.fn(), + verifyToken, + openUrl: vi.fn(), + }), + ); + + // One verify — for the only value that passed the shape check. + expect(verifyToken).toHaveBeenCalledTimes(1); + expect(addEmailDomain).toHaveBeenCalledWith('prj_1', { + domain: 'acme.com', + apiToken: LEGACY_TOKEN, + attemptId: expect.any(String), + }); + }); + + it('switches to the masked paste on Enter; a cancel stores nothing', async () => { + const addEmailDomain = vi.fn(async () => domainRow({ credential_kind: 'api_token' })); + const pasteToken = vi.fn(async () => ` ${LEGACY_TOKEN}\n`); + const verifyToken = vi.fn(async (): Promise => 'active'); + // The grant hangs (it waits on a browser for minutes); Enter resolves at + // once, so the race deterministically switches paths. + const pendingGrant = vi.fn(() => new Promise(() => {})); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + addDeps({ + runGrant: pendingGrant, + waitForEnter: vi.fn(async () => {}), + readClipboard: vi.fn(() => 'clipboard-before'), + verifyToken, + pasteToken, + openUrl: vi.fn(), + clearClipboard: vi.fn(), + }), + ); + + expect(addEmailDomain).toHaveBeenCalledWith('prj_1', { + domain: 'acme.com', + apiToken: LEGACY_TOKEN, + attemptId: expect.any(String), + }); + + // Esc at the paste prompt: nothing is POSTed, nothing is stored. + const addEmailDomain2 = vi.fn(); + await emailDomainAdd( + { addEmailDomain: addEmailDomain2, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + addDeps({ + runGrant: pendingGrant, + waitForEnter: vi.fn(async () => {}), + readClipboard: vi.fn(() => null), + pasteToken: vi.fn(async () => null), + openUrl: vi.fn(), + }), + ); + expect(addEmailDomain2).not.toHaveBeenCalled(); + expect(printed(infoSpy)).toContain('Cancelled — nothing was stored anywhere.'); + }); + + it('stops the clipboard watch once Enter wins — no orphaned poll loop', async () => { + const addEmailDomain = vi.fn(async () => domainRow({ credential_kind: 'api_token' })); + // A constant non-token value: the poll loop keeps watching without verifying. + const readClipboard = vi.fn(() => 'clipboard-before'); + const verifyToken = vi.fn(async (): Promise => 'active'); + let resolveEnter!: () => void; + const enterPressed = new Promise((resolve) => { + resolveEnter = resolve; + }); + + const run = emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + addDeps({ + runGrant: vi.fn(async () => { + throw new Error('cf-oauth: cancelled.'); + }), + // The first waitForEnter arms the grant race and never fires (the + // grant's failure ends that race); the second arms the watch race and + // is fired below, once the poll loop is observably running. + waitForEnter: vi + .fn() + .mockImplementationOnce(neverEnter) + .mockImplementationOnce(() => enterPressed), + readClipboard, + clearClipboard: vi.fn(), + verifyToken, + pasteToken: vi.fn(async () => LEGACY_TOKEN), + openUrl: vi.fn(), + // Far past the observation window below, so a still-running loop + // would keep polling through it. + watchTimeoutMs: 10_000, + }), + ); + + // The watch is running: the snapshot read plus at least one interval poll. + await vi.waitFor(() => { + expect(readClipboard.mock.calls.length).toBeGreaterThanOrEqual(2); + }); + resolveEnter(); + await run; + + // Enter switched to the paste path, which POSTed the pasted token. + expect(addEmailDomain).toHaveBeenCalledWith('prj_1', { + domain: 'acme.com', + apiToken: LEGACY_TOKEN, + attemptId: expect.any(String), + }); + // The settled race stopped the poll loop: no further clipboard reads (so + // no timer chain and no stray verify from the watch) past this point. + const readsAtSettle = readClipboard.mock.calls.length; + await new Promise((resolve) => setTimeout(resolve, 30)); // ~30 watch intervals + expect(readClipboard.mock.calls.length).toBe(readsAtSettle); + expect(verifyToken).toHaveBeenCalledTimes(1); // the pasted token's check + }); + + it('refuses a pasted token shaped like another vendor’s, without a network call', async () => { + const verifyToken = vi.fn(); + const addEmailDomain = vi.fn(); + + await expect( + emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + addDeps({ + runGrant: vi.fn(() => new Promise(() => {})), + waitForEnter: vi.fn(async () => {}), + readClipboard: vi.fn(() => null), + pasteToken: vi.fn(async () => `ghp_${'a'.repeat(36)}`), + verifyToken, + openUrl: vi.fn(), + }), + ), + ).rejects.toThrow('exit 1'); + expect(printed(errorSpy)).toContain('that looks like a different kind of token'); + expect(verifyToken).not.toHaveBeenCalled(); + expect(addEmailDomain).not.toHaveBeenCalled(); + }); + + it('refuses a pasted token Cloudflare says is not active', async () => { + const addEmailDomain = vi.fn(); + await expect( + emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + addDeps({ + runGrant: vi.fn(() => new Promise(() => {})), + waitForEnter: vi.fn(async () => {}), + readClipboard: vi.fn(() => null), + pasteToken: vi.fn(async () => LEGACY_TOKEN), + verifyToken: vi.fn(async (): Promise => 'inactive'), + openUrl: vi.fn(), + }), + ), + ).rejects.toThrow('exit 1'); + expect(printed(errorSpy)).toContain('that is not an active Cloudflare token'); + expect(addEmailDomain).not.toHaveBeenCalled(); + }); + + it('renders a failed row with the failed step and the retry hint', async () => { + const addEmailDomain = vi.fn(async () => + domainRow({ + status: 'failed', + setup_state: { failed_step: 'zone_lookup' }, + error: 'no Cloudflare zone found for acme.com in an account this credential can see', + }), + ); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + addDeps(), + ); + + expect(printed(errorSpy)).toContain('failed at zone lookup'); + expect(printed(errorSpy)).toContain('no Cloudflare zone found for acme.com'); + expect(printed(infoSpy)).toContain('re-run `void email domain add acme.com`'); + }); + + it('renders the pending row with the routing-subdomain dashboard step', async () => { + const addEmailDomain = vi.fn(async () => + domainRow({ + domain: 'mail.acme.com', + mode: 'subdomain', + status: 'pending', + setup_state: { remaining_steps: ['routing_subdomain'] }, + }), + ); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + addDeps(), + ); + + expect(notedBlocks()).toContain('Domain: mail.acme.com'); + expect(printed(warnSpy)).toContain('Email Routing → acme.com → Settings → Subdomains'); + expect(printed(infoSpy)).toContain('void email domain status mail.acme.com'); + }); + + it('renders the Workers Free hint when sending onboarding is still pending on a live row', async () => { + const addEmailDomain = vi.fn(async () => + domainRow({ + status: 'active', + setup_state: { remaining_steps: ['sending_onboarding'] }, + }), + ); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain: vi.fn() }, + 'prj_1', + 'acme.com', + undefined, + addDeps(), + ); + + expect(printed(infoSpy)).toContain('Workers Paid'); + expect(printed(infoSpy)).toContain('void email domain sync acme.com'); + // The row is live — the success line still prints. + expect(printed(successSpy)).toContain('acme.com is live'); + }); + + it('rethrows an API rejection without reconciling — the server already revoked the grant', async () => { + const addEmailDomain = vi.fn(async () => { + throw new PlatformApiError( + 'Failed to add email domain', + 409, + '{"error":"domain is registered to another project"}', + ); + }); + const getEmailDomain = vi.fn(); + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + + await expect( + emailDomainAdd({ addEmailDomain, getEmailDomain }, 'prj_1', 'acme.com', undefined, addDeps()), + ).rejects.toThrow(PlatformApiError); + // No reconciliation, no CLI-side revoke: the API's rejection owns both. + expect(getEmailDomain).not.toHaveBeenCalled(); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('routes a 500 answer through the attempt-id reconcile — the row committed', async () => { + mockAttemptId(); + const addEmailDomain = vi.fn(async () => { + throw new PlatformApiError('Failed to add email domain', 500, '{"error":"internal error"}'); + }); + // A 500 is ambiguous — the add may have committed before the error. The + // reconcile proves it did: the row carries this attempt's id. + const getEmailDomain = vi.fn(async () => statusRow({ attemptId: ATTEMPT_ID })); + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain }, + 'prj_1', + 'acme.com', + undefined, + addDeps(), + ); + + expect(getEmailDomain).toHaveBeenCalledTimes(1); + expect(printed(warnSpy)).toContain('answer was lost'); + expect(notedBlocks()).toContain('Domain: acme.com'); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('routes a 500 answer through the attempt-id reconcile — nothing persisted, the grant is revoked', async () => { + mockAttemptId(); + const addEmailDomain = vi.fn(async () => { + throw new PlatformApiError('Failed to add email domain', 500, '{"error":"internal error"}'); + }); + const getEmailDomain = vi.fn(async () => { + throw new PlatformApiError( + 'Failed to fetch email domain status', + 404, + '{"error":"email domain not found"}', + ); + }); + const fetchSpy = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => new Response(null, { status: 200 }), + ); + vi.stubGlobal('fetch', fetchSpy); + + await expect( + emailDomainAdd({ addEmailDomain, getEmailDomain }, 'prj_1', 'acme.com', undefined, addDeps()), + ).rejects.toThrow('exit 1'); + + // The 500 did not prove a server-side revoke, so the CLI kills the grant + // it still holds once the polls prove nothing persisted. + expect(getEmailDomain).toHaveBeenCalledTimes(15); + expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(String(fetchSpy.mock.calls[0]![0])).toBe('https://dash.cloudflare.com/oauth2/revoke'); + expect(printed(errorSpy)).toContain('was not registered'); + expect(printed(errorSpy)).toContain('was revoked'); + }); + + it('reconciles a 403 answer — a suspended account never reached the route, nothing persisted', async () => { + mockAttemptId(); + const addEmailDomain = vi.fn(async () => { + throw new PlatformApiError( + 'Failed to add email domain', + 403, + '{"error":"account suspended"}', + ); + }); + // A 403 may come from the middleware pre-route (no parse, no revoke), so + // it reconciles like any other ambiguous answer — here the polls prove + // nothing persisted and the held grant is revoked. + const getEmailDomain = vi.fn(async () => { + throw new PlatformApiError( + 'Failed to fetch email domain status', + 404, + '{"error":"email domain not found"}', + ); + }); + const fetchSpy = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => new Response(null, { status: 200 }), + ); + vi.stubGlobal('fetch', fetchSpy); + + await expect( + emailDomainAdd({ addEmailDomain, getEmailDomain }, 'prj_1', 'acme.com', undefined, addDeps()), + ).rejects.toThrow('exit 1'); + + expect(getEmailDomain).toHaveBeenCalledTimes(15); + expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(String(fetchSpy.mock.calls[0]![0])).toBe('https://dash.cloudflare.com/oauth2/revoke'); + expect(printed(errorSpy)).toContain('was not registered'); + }); + + it('reconciles a 403 answer — every poll 403s too, so the state stays unknown and nothing is revoked', async () => { + mockAttemptId(); + const addEmailDomain = vi.fn(async () => { + throw new PlatformApiError( + 'Failed to add email domain', + 403, + '{"error":"account suspended"}', + ); + }); + const getEmailDomain = vi.fn(async () => { + throw new PlatformApiError( + 'Failed to fetch email domain status', + 403, + '{"error":"account suspended"}', + ); + }); + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + + await expect( + emailDomainAdd({ addEmailDomain, getEmailDomain }, 'prj_1', 'acme.com', undefined, addDeps()), + ).rejects.toThrow('exit 1'); + + // No poll produced a read — the grant may be live, and a blind revoke + // could brick a committed row: report, don't revoke. + expect(getEmailDomain).toHaveBeenCalledTimes(15); + expect(printed(errorSpy)).toContain('state is unknown'); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('reports a failed revocation instead of claiming it — the grant may still be live', async () => { + mockAttemptId(); + const addEmailDomain = vi.fn(async () => { + throw new TypeError('fetch failed'); + }); + const getEmailDomain = vi.fn(async () => { + throw new PlatformApiError( + 'Failed to fetch email domain status', + 404, + '{"error":"email domain not found"}', + ); + }); + // Cloudflare answers the revoke with a 500: fetch resolves, and a helper + // that ignored the status would let the CLI claim a revocation that + // never happened. + const fetchSpy = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response('nope', { status: 500 }), + ); + vi.stubGlobal('fetch', fetchSpy); + + await expect( + emailDomainAdd({ addEmailDomain, getEmailDomain }, 'prj_1', 'acme.com', undefined, addDeps()), + ).rejects.toThrow('exit 1'); + + expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(printed(errorSpy)).toContain('could not be revoked'); + expect(printed(errorSpy)).toContain('revoke it in the Cloudflare dashboard'); + expect(printed(errorSpy)).not.toContain('was revoked'); + }); + + it('reconciles a lost answer: the row carries this attempt id, nothing is revoked', async () => { + mockAttemptId(); + const addEmailDomain = vi.fn(async () => { + throw new TypeError('fetch failed'); + }); + const getEmailDomain = vi.fn(async () => statusRow({ attemptId: ATTEMPT_ID })); + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain }, + 'prj_1', + 'acme.com', + undefined, + addDeps(), + ); + + // One read settles it: the stamped attempt id proves this attempt's + // POST committed, so the platform holds the credential and the row + // renders like any other add. + expect(getEmailDomain).toHaveBeenCalledTimes(1); + expect(getEmailDomain).toHaveBeenCalledWith('prj_1', 'acme.com'); + expect(printed(warnSpy)).toContain('answer was lost'); + expect(notedBlocks()).toContain('Domain: acme.com'); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('reconciles a lost answer: a 404 then the row with this attempt id — the insert was still in flight', async () => { + mockAttemptId(); + const addEmailDomain = vi.fn(async () => { + throw new TypeError('fetch failed'); + }); + const getEmailDomain = vi + .fn() + .mockRejectedValueOnce( + new PlatformApiError( + 'Failed to fetch email domain status', + 404, + '{"error":"email domain not found"}', + ), + ) + .mockResolvedValueOnce(statusRow({ attemptId: ATTEMPT_ID })); + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain }, + 'prj_1', + 'acme.com', + undefined, + addDeps(), + ); + + // The lost answer did not stop the API worker: the row committed + // between polls, and the stamped attempt id proves the credential is + // this attempt's — revoking here would brick the row. + expect(getEmailDomain).toHaveBeenCalledTimes(2); + expect(printed(warnSpy)).toContain('answer was lost'); + expect(notedBlocks()).toContain('Domain: acme.com'); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('reconciles a lost answer against an api without attempt identity: the row exists, nothing is revoked', async () => { + mockAttemptId(); + const addEmailDomain = vi.fn(async () => { + throw new TypeError('fetch failed'); + }); + // No attemptId key in the parsed row at all (statusRow carries none): + // an old api, where this could be my committed add — indistinguishable + // from a pre-existing row, so trust it and never revoke. + const getEmailDomain = vi.fn(async () => statusRow({ status: 'pending' })); + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + + await emailDomainAdd( + { addEmailDomain, getEmailDomain }, + 'prj_1', + 'acme.com', + undefined, + addDeps(), + ); + + expect(getEmailDomain).toHaveBeenCalledTimes(1); + expect(getEmailDomain).toHaveBeenCalledWith('prj_1', 'acme.com'); + expect(printed(warnSpy)).toContain('answer was lost'); + expect(notedBlocks()).toContain('Domain: acme.com'); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('revokes the minted grant when the row keeps a different attempt id through the deadline', async () => { + mockAttemptId(); + const addEmailDomain = vi.fn(async () => { + throw new TypeError('fetch failed'); + }); + // The pre-existing row, stamped by an earlier attempt: this attempt's + // replace POST never landed, and a committed mine would carry my id. + const getEmailDomain = vi.fn(async () => + statusRow({ attemptId: '99999999-9999-4999-8999-999999999999' }), + ); + const fetchSpy = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => new Response(null, { status: 200 }), + ); + vi.stubGlobal('fetch', fetchSpy); + + await expect( + emailDomainAdd({ addEmailDomain, getEmailDomain }, 'prj_1', 'acme.com', undefined, addDeps()), + ).rejects.toThrow('exit 1'); + + expect(getEmailDomain).toHaveBeenCalledTimes(15); + // Exactly one call: the RFC 7009 revoke of the grant this process held. + expect(fetchSpy).toHaveBeenCalledTimes(1); + const [url, init] = fetchSpy.mock.calls[0]!; + expect(String(url)).toBe('https://dash.cloudflare.com/oauth2/revoke'); + const form = new URLSearchParams(String(init?.body)); + expect(form.get('token')).toBe(GRANT_SENTINEL); + expect(form.get('token_type_hint')).toBe('refresh_token'); + expect(printed(errorSpy)).toContain("kept the row's existing credential"); + expect(printed(errorSpy)).toContain('revoked'); + // The token itself never reaches an output line. + expect(printed(errorSpy) + printed(infoSpy) + printed(warnSpy)).not.toContain(GRANT_SENTINEL); + }); + + it('treats a stamped null attempt id as foreign — a row an older CLI wrote', async () => { + mockAttemptId(); + const addEmailDomain = vi.fn(async () => { + throw new TypeError('fetch failed'); + }); + const getEmailDomain = vi.fn(async () => statusRow({ attemptId: null })); + const fetchSpy = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => new Response(null, { status: 200 }), + ); + vi.stubGlobal('fetch', fetchSpy); + + await expect( + emailDomainAdd({ addEmailDomain, getEmailDomain }, 'prj_1', 'acme.com', undefined, addDeps()), + ).rejects.toThrow('exit 1'); + + // The key is present (new api) but null — not this attempt, so the + // posted grant was never stored and the revoke is safe. + expect(getEmailDomain).toHaveBeenCalledTimes(15); + expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(printed(errorSpy)).toContain("kept the row's existing credential"); + }); + + it('revokes the minted grant when a transport failure provably never persisted it', async () => { + mockAttemptId(); + const addEmailDomain = vi.fn(async () => { + throw new TypeError('fetch failed'); + }); + const getEmailDomain = vi.fn(async () => { + throw new PlatformApiError( + 'Failed to fetch email domain status', + 404, + '{"error":"email domain not found"}', + ); + }); + const fetchSpy = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => new Response(null, { status: 200 }), + ); + vi.stubGlobal('fetch', fetchSpy); + + await expect( + emailDomainAdd({ addEmailDomain, getEmailDomain }, 'prj_1', 'acme.com', undefined, addDeps()), + ).rejects.toThrow('exit 1'); + + // 404 at every one of the 15 polls — provably nothing persisted. + expect(getEmailDomain).toHaveBeenCalledTimes(15); + // Exactly one call: the RFC 7009 revoke of the grant this process held. + expect(fetchSpy).toHaveBeenCalledTimes(1); + const [url, init] = fetchSpy.mock.calls[0]!; + expect(String(url)).toBe('https://dash.cloudflare.com/oauth2/revoke'); + const form = new URLSearchParams(String(init?.body)); + expect(form.get('token')).toBe(GRANT_SENTINEL); + expect(form.get('token_type_hint')).toBe('refresh_token'); + expect(printed(errorSpy)).toContain('was not registered'); + expect(printed(errorSpy)).toContain('revoked'); + // The token itself never reaches an output line. + expect(printed(errorSpy) + printed(infoSpy) + printed(warnSpy)).not.toContain(GRANT_SENTINEL); + }); + + it('never revokes on an indeterminate reconcile — the grant may be the row’s credential', async () => { + mockAttemptId(); + const addEmailDomain = vi.fn(async () => { + throw new TypeError('fetch failed'); + }); + const getEmailDomain = vi.fn(async () => { + throw new TypeError('fetch failed'); + }); + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + + await expect( + emailDomainAdd({ addEmailDomain, getEmailDomain }, 'prj_1', 'acme.com', undefined, addDeps()), + ).rejects.toThrow('exit 1'); + + // No poll produced any read: a blind revoke could brick a committed + // row — report, don't revoke. + expect(getEmailDomain).toHaveBeenCalledTimes(15); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(printed(errorSpy)).toContain('state is unknown'); + }); +}); + +describe('emailDomainStatus', () => { + it('renders the row, the live credential probe and the relay state', async () => { + const getEmailDomain = vi.fn(async () => + statusRow({ token_id: 'cf-token-id', token_expires_on: '2026-12-31T00:00:00Z' }), + ); + await emailDomainStatus({ getEmailDomain }, 'prj_1', 'acme.com'); + + const block = notedBlocks(); + expect(block).toContain('Domain: acme.com'); + expect(block).toContain('Mode: apex'); + expect(block).toContain('Credential: OAuth grant · active'); + expect(block).toContain('Token: id cf-token-id · expires 2026-12-31T00:00:00Z'); + expect(block).toContain('Relay: void-email-relay v1'); + expect(getEmailDomain).toHaveBeenCalledWith('prj_1', 'acme.com'); + }); + + it('points at sync when the relay drifted or went missing', async () => { + await emailDomainStatus( + { + getEmailDomain: vi.fn(async () => + statusRow({ relay_drift: true, current_relay_version: 2 }), + ), + }, + 'prj_1', + 'acme.com', + ); + expect(notedBlocks()).toContain('drifted (current is v2)'); + expect(printed(infoSpy)).toContain('void email domain sync acme.com'); + + await emailDomainStatus( + { getEmailDomain: vi.fn(async () => statusRow({ relay_missing: true })) }, + 'prj_1', + 'acme.com', + ); + expect(notedBlocks()).toContain('missing from the account'); + }); + + it('names the renewal path for a revoked or expired credential', async () => { + await emailDomainStatus( + { + getEmailDomain: vi.fn(async () => + statusRow({ status: 'token_revoked', credential_status: 'revoked' }), + ), + }, + 'prj_1', + 'acme.com', + ); + expect(printed(warnSpy)).toContain('Re-run `void email domain add acme.com`'); + expect(printed(warnSpy)).toContain('adding again replaces the credential, rules stay'); + }); + + it('prints the api error verbatim and the remaining human step', async () => { + await emailDomainStatus( + { + getEmailDomain: vi.fn(async () => + statusRow({ + status: 'pending', + mode: 'subdomain', + domain: 'mail.acme.com', + error: 'probe text safe to print', + setup_state: { remaining_steps: ['routing_subdomain'] }, + }), + ), + }, + 'prj_1', + 'mail.acme.com', + ); + expect(printed(errorSpy)).toContain('email: probe text safe to print'); + expect(printed(warnSpy)).toContain('Email Routing → acme.com → Settings → Subdomains'); + }); + + it('renders the catch-all state, and the sync hint only when it drifted', async () => { + await emailDomainStatus( + { getEmailDomain: vi.fn(async () => statusRow({ catch_all: 'points_here' })) }, + 'prj_1', + 'acme.com', + ); + expect(notedBlocks()).toContain('Catch-all: points_here'); + expect(printed(infoSpy)).not.toContain('re-point it'); + + await emailDomainStatus( + { + getEmailDomain: vi.fn(async () => + statusRow({ catch_all: 'points_elsewhere', catch_all_drift: true }), + ), + }, + 'prj_1', + 'acme.com', + ); + expect(notedBlocks()).toContain('Catch-all: points_elsewhere'); + expect(printed(infoSpy)).toContain('run `void email domain sync acme.com` to re-point it'); + }); +}); + +describe('emailDomainList', () => { + it('reports the empty state with the add hint', async () => { + await emailDomainList({ listEmailDomains: vi.fn(async () => []) }, 'prj_1'); + expect(printed(infoSpy)).toContain('No email domains.'); + expect(printed(infoSpy)).toContain('void email domain add '); + }); + + it('renders one line per domain with status and mode', async () => { + await emailDomainList( + { + listEmailDomains: vi.fn(async () => [ + domainRow({ domain: 'acme.com', status: 'active', mode: 'apex' }), + domainRow({ + id: 'edom_2', + domain: 'mail.example.org', + status: 'pending', + mode: 'subdomain', + }), + ]), + }, + 'prj_1', + ); + const block = notedBlocks(); + expect(block).toContain('acme.com'); + expect(block).toContain('mail.example.org'); + expect(block).toContain('subdomain'); + }); +}); + +describe('emailDomainSync', () => { + it('renders the redeploy + rotation on success', async () => { + const syncEmailDomain = vi.fn(async () => domainRow({ relay_version: 2 })); + await emailDomainSync({ syncEmailDomain }, 'prj_1', 'acme.com'); + expect(printed(successSpy)).toContain('Relay redeployed at v2 with a rotated secret.'); + expect(syncEmailDomain).toHaveBeenCalledWith('prj_1', 'acme.com'); + }); + + it('renders a failed sync with the failed step', async () => { + const syncEmailDomain = vi.fn(async () => + domainRow({ + status: 'failed', + relay_version: null, + setup_state: { failed_step: 'deploy_relay' }, + error: 'PUT script failed', + }), + ); + await emailDomainSync({ syncEmailDomain }, 'prj_1', 'acme.com'); + expect(printed(errorSpy)).toContain('failed at deploy relay'); + expect(printed(errorSpy)).toContain('PUT script failed'); + expect(printed(successSpy)).not.toContain('Relay redeployed'); + }); + + it('prints the catch-all outcome when the response carries one', async () => { + const syncEmailDomain = vi.fn(async () => ({ ...domainRow(), catch_all: 'ensured' as const })); + await emailDomainSync({ syncEmailDomain }, 'prj_1', 'acme.com'); + expect(printed(infoSpy)).toContain('Catch-all: ensured'); + expect(printed(warnSpy)).not.toContain('NOT overwritten'); + }); + + it('warns instead of claiming the catch-all when it points at a different worker', async () => { + const syncEmailDomain = vi.fn(async () => ({ + ...domainRow(), + catch_all: 'foreign_conflict' as const, + })); + await emailDomainSync({ syncEmailDomain }, 'prj_1', 'acme.com'); + expect(printed(warnSpy)).toContain("the zone's catch-all points at a different worker"); + expect(printed(warnSpy)).toContain('NOT overwritten'); + expect(printed(infoSpy)).not.toContain('Catch-all:'); + }); + + it('prints no catch-all line when the response omits it (a row with no zone_id)', async () => { + const syncEmailDomain = vi.fn(async () => domainRow()); + await emailDomainSync({ syncEmailDomain }, 'prj_1', 'acme.com'); + expect(printed(infoSpy) + printed(warnSpy)).not.toContain('Catch-all'); + }); +}); + +describe('emailDomainRemove', () => { + function removeClient(body: RemoveEmailDomainResponse): Pick< + PlatformClient, + 'removeEmailDomain' + > & { + removeEmailDomain: ReturnType; + } { + return { removeEmailDomain: vi.fn(async () => body) }; + } + + it('renders a clean removal with no warnings', async () => { + const client = removeClient({ ok: true, removed: true }); + await emailDomainRemove(client, 'prj_1', 'acme.com'); + expect(client.removeEmailDomain).toHaveBeenCalledWith('prj_1', 'acme.com', undefined); + expect(printed(successSpy)).toContain( + 'Removed acme.com — the platform row, the stored credential and the relay secret are gone.', + ); + expect(printed(warnSpy)).toBe(''); + expect(printed(errorSpy)).toBe(''); + }); + + it('passes --force through to the api', async () => { + const client = removeClient({ ok: true, removed: true }); + await emailDomainRemove(client, 'prj_1', 'acme.com', { force: true }); + expect(client.removeEmailDomain).toHaveBeenCalledWith('prj_1', 'acme.com', true); + }); + + it('kept for retry: names the failed steps, points at retry and --force, exits 1', async () => { + const client = removeClient({ + ok: false, + removed: false, + failed_steps: ['catch_all', 'delete_relay'], + }); + const exit = exitSpy(); + await expect(emailDomainRemove(client, 'prj_1', 'acme.com', { exit })).rejects.toThrow( + 'exit 1', + ); + expect(printed(errorSpy)).toContain('failed Cloudflare-side steps: catch_all, delete_relay'); + expect(printed(infoSpy)).toContain('The registration was kept'); + expect(printed(infoSpy)).toContain('retry `void email domain remove acme.com`'); + expect(printed(infoSpy)).toContain('re-run with --force to drop the row anyway'); + expect(exit).toHaveBeenCalledWith(1); + }); + + it('forced: success plus a warning naming the failed steps and the manual cleanup', async () => { + const client = removeClient({ + ok: true, + removed: true, + forced: true, + failed_steps: ['delete_relay', 'catch_all'], + }); + await emailDomainRemove(client, 'prj_1', 'acme.com', { force: true }); + expect(printed(successSpy)).toContain('Removed acme.com'); + expect(printed(warnSpy)).toContain('delete_relay, catch_all'); + expect(printed(warnSpy)).toContain('delete the relay worker and reset the catch-all'); + expect(printed(warnSpy)).toContain("the zone's Email Routing settings"); + }); + + it('a grant-revoke failure alone is a one-line note, not a warning', async () => { + const client = removeClient({ ok: true, removed: true, failed_steps: ['revoke_grant'] }); + await emailDomainRemove(client, 'prj_1', 'acme.com'); + expect(printed(successSpy)).toContain('Removed acme.com'); + expect(printed(infoSpy)).toContain('the Cloudflare grant could not be revoked'); + expect(printed(infoSpy)).toContain('no mail impact'); + expect(printed(warnSpy)).toBe(''); + }); +}); + +describe('PlatformClient.removeEmailDomain', () => { + const apiUrl = 'https://api.test'; + let originalFetch: typeof globalThis.fetch | undefined; + + beforeEach(() => { + originalFetch = globalThis.fetch; + }); + + afterEach(() => { + if (originalFetch) { + globalThis.fetch = originalFetch; + } + }); + + it('DELETEs the domain URL, appending ?force=1 only when forced', async () => { + const fetchMock = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response(JSON.stringify({ ok: true, removed: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), + ); + globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch; + const client = new PlatformClient('tok', { apiUrl }); + + await client.removeEmailDomain('prj_1', 'acme.com'); + const [plainUrl, plainInit] = fetchMock.mock.calls[0]!; + expect(String(plainUrl)).toBe(`${apiUrl}/projects/prj_1/email/domains/acme.com`); + expect(plainInit?.method).toBe('DELETE'); + + await client.removeEmailDomain('prj_1', 'acme.com', true); + const [forceUrl, forceInit] = fetchMock.mock.calls[1]!; + expect(String(forceUrl)).toBe(`${apiUrl}/projects/prj_1/email/domains/acme.com?force=1`); + expect(forceInit?.method).toBe('DELETE'); + }); +}); diff --git a/packages/void/test/unit/email-domain-args.test.ts b/packages/void/test/unit/email-domain-args.test.ts new file mode 100644 index 000000000..7b1f0ff91 --- /dev/null +++ b/packages/void/test/unit/email-domain-args.test.ts @@ -0,0 +1,189 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { parseEmailArgs } from '../../src/cli/email-args.ts'; + +/** + * The nested `void email domain ` group (design doc 0078, "Custom + * domains on Cloudflare"). `runSubcommandGroup` handles one level, so the + * group parses its own positionals: verb first, domain second. + */ +describe('parseEmailArgs — domain group', () => { + it('parses domain add with a domain', () => { + expect(parseEmailArgs(['domain', 'add', 'acme.com'])).toEqual({ + subcommand: 'domain', + domainVerb: 'add', + domain: 'acme.com', + subdomain: undefined, + projectSlug: undefined, + limit: undefined, + platform: undefined, + }); + }); + + it('parses status, sync and remove with a domain, and list without one', () => { + for (const verb of ['status', 'sync', 'remove'] as const) { + expect(parseEmailArgs(['domain', verb, 'mail.acme.com'])).toMatchObject({ + subcommand: 'domain', + domainVerb: verb, + domain: 'mail.acme.com', + }); + } + expect(parseEmailArgs(['domain', 'list'])).toMatchObject({ + subcommand: 'domain', + domainVerb: 'list', + domain: undefined, + }); + }); + + it('parses --project on every domain verb', () => { + expect(parseEmailArgs(['domain', 'add', 'acme.com', '--project', 'my-app'])).toMatchObject({ + domainVerb: 'add', + domain: 'acme.com', + projectSlug: 'my-app', + }); + expect(parseEmailArgs(['domain', 'list', '--project=my-app'])).toMatchObject({ + domainVerb: 'list', + projectSlug: 'my-app', + }); + }); + + it('parses --subdomain on domain add (space and = forms)', () => { + expect(parseEmailArgs(['domain', 'add', 'acme.com', '--subdomain', 'mx'])).toMatchObject({ + domainVerb: 'add', + domain: 'acme.com', + subdomain: 'mx', + }); + expect( + parseEmailArgs(['domain', 'add', 'acme.com', '--subdomain=mail.acme.com']), + ).toMatchObject({ + domainVerb: 'add', + domain: 'acme.com', + subdomain: 'mail.acme.com', + }); + }); + + it('errors on a missing or unknown domain verb', () => { + expect(() => parseEmailArgs(['domain'])).toThrow( + 'email: Usage: void email domain [] [--project ].', + ); + expect(() => parseEmailArgs(['domain', 'frobnicate', 'acme.com'])).toThrow( + /Usage: void email domain/, + ); + }); + + it('errors when a domain verb is missing its domain', () => { + for (const verb of ['add', 'status', 'sync', 'remove']) { + expect(() => parseEmailArgs(['domain', verb])).toThrow( + `email: Usage: void email domain ${verb} [--project ].`, + ); + } + }); + + it('errors when domain list receives a domain', () => { + expect(() => parseEmailArgs(['domain', 'list', 'acme.com'])).toThrow( + 'email: `void email domain list` takes no domain argument.', + ); + }); + + it('errors on extra positionals, naming them like the allow rule does', () => { + expect(() => parseEmailArgs(['domain', 'add', 'a.com', 'b.com'])).toThrow( + /`void email domain add` takes exactly one domain argument \(got 2: "a.com", "b.com"\)/, + ); + expect(() => parseEmailArgs(['domain', 'status', 'a.com', 'b.com', 'c.com'])).toThrow( + /takes exactly one domain argument \(got 3/, + ); + }); + + it('rejects --subdomain on the other domain verbs and on non-domain subcommands', () => { + for (const args of [ + ['domain', 'status', 'acme.com', '--subdomain', 'mx'], + ['domain', 'list', '--subdomain=mx'], + ['domain', 'remove', 'acme.com', '--subdomain', 'mx'], + ]) { + expect(() => parseEmailArgs(args)).toThrow( + 'email: --subdomain applies to `void email domain add` only.', + ); + } + expect(() => parseEmailArgs(['usage', '--subdomain', 'mx'])).toThrow( + 'email: --subdomain applies to `void email domain add` only.', + ); + expect(() => parseEmailArgs(['allow', 'a@x.dev', '--subdomain', 'mx'])).toThrow( + 'email: --subdomain applies to `void email domain add` only.', + ); + }); + + it('parses --force on domain remove only', () => { + expect(parseEmailArgs(['domain', 'remove', 'acme.com', '--force'])).toMatchObject({ + domainVerb: 'remove', + domain: 'acme.com', + force: true, + }); + // Off by default, on every verb. + expect(parseEmailArgs(['domain', 'remove', 'acme.com'])).toMatchObject({ + domainVerb: 'remove', + force: undefined, + }); + for (const args of [ + ['domain', 'add', 'acme.com', '--force'], + ['domain', 'status', 'acme.com', '--force'], + ['domain', 'sync', 'acme.com', '--force'], + ['domain', 'list', '--force'], + ['usage', '--force'], + ['disallow', 'a@x.dev', '--force'], + ]) { + expect(() => parseEmailArgs(args)).toThrow( + 'email: --force applies to `void email domain remove` only.', + ); + } + }); + + it('rejects --force with a value or repeated', () => { + expect(() => parseEmailArgs(['domain', 'remove', 'acme.com', '--force=yes'])).toThrow( + 'email: --force takes no value.', + ); + expect(() => parseEmailArgs(['domain', 'remove', 'acme.com', '--force', '--force'])).toThrow( + 'email: --force can only be specified once.', + ); + }); + + it('rejects --subdomain without a value, with an empty value, or repeated', () => { + expect(() => parseEmailArgs(['domain', 'add', 'acme.com', '--subdomain'])).toThrow( + 'email: --subdomain requires a value (a subdomain label or host).', + ); + expect(() => + parseEmailArgs(['domain', 'add', 'acme.com', '--subdomain', '--project', 'x']), + ).toThrow(/--subdomain requires a value/); + expect(() => parseEmailArgs(['domain', 'add', 'acme.com', '--subdomain='])).toThrow( + /--subdomain requires a value/, + ); + expect(() => + parseEmailArgs(['domain', 'add', 'acme.com', '--subdomain', 'mx', '--subdomain', 'mg']), + ).toThrow('email: --subdomain can only be specified once.'); + }); + + // Mode B (0078): the developer's own zone needs none of this group — same + // rejection the platform-only subcommands already had. + it('rejects --platform cloudflare on the domain group, accepts --platform void', () => { + expect(() => parseEmailArgs(['domain', 'add', 'acme.com', '--platform', 'cloudflare'])).toThrow( + 'email: --platform cloudflare applies to `void email status` and `void email setup` only (`domain` is a Void platform command).', + ); + expect(() => parseEmailArgs(['domain', 'list', '--backend', 'cloudflare'])).toThrow( + /applies to `void email status` and `void email setup` only/, + ); + expect(parseEmailArgs(['domain', 'list', '--platform', 'void'])).toMatchObject({ + domainVerb: 'list', + platform: 'void', + }); + }); + + it('keeps the existing subcommands parsing unchanged with the group registered', () => { + // The shared flag rules still bind inside the group. + expect(() => parseEmailArgs(['domain', 'list', '--project', 'a', '--project', 'b'])).toThrow( + 'email: --project can only be specified once.', + ); + expect(() => parseEmailArgs(['domain', 'add', 'acme.com', '--project='])).toThrow( + 'email: --project requires a value (a project name).', + ); + // And the top-level usage error names the group. + expect(() => parseEmailArgs(['nope'])).toThrow(/email: Usage: void email .*domain/); + }); +}); diff --git a/packages/void/test/unit/email-inbound.test.ts b/packages/void/test/unit/email-inbound.test.ts index 84d16ce07..2a502b910 100644 --- a/packages/void/test/unit/email-inbound.test.ts +++ b/packages/void/test/unit/email-inbound.test.ts @@ -650,6 +650,47 @@ describe('generated __emailHandler dispatch (behavioural)', () => { expect(seen).toEqual([{ ticket: 'T-42' }]); }); + it('runs a relayed (viaDomain) recipient in no-prefix mode even when a slug is passed', async () => { + // The relay lane of "Custom domains on Cloudflare" (design doc 0078): + // the platform router proves the domain's relay secret and sets + // `viaDomain`; the recipient carries no `+` prefix. A platform + // deployment still injects `__VOID_PROJECT_SLUG`, and the generated + // handleEmail suppresses it for this lane — and createMessageProxy + // itself ignores a slug passed alongside viaDomain, so a slug equal to + // the local-part prefix cannot strip `support+` off the address either. + const seen: Array = []; + const dispatch = buildEmailDispatcher(compile({ ...SUPPORT, defaultHandler: '_default.ts' }), { + '/e/support.ts': { default: () => seen.push('static') }, + '/e/support+[ticket].ts': { + default: (_m: unknown, _e: unknown, _c: unknown, info: { params: unknown }) => + seen.push(info.params), + }, + '/e/_default.ts': { default: () => seen.push('default') }, + }); + + const { message } = createMessageProxy( + { + from: 'sender@example.com', + to: 'support+T-42@acme.com', + headers: {}, + raw: new Uint8Array(), + rawSize: 0, + viaDomain: 'acme.com', + }, + { slug: 'support' }, + ); + + // Unstripped: the address IS the one the handler author wrote, and no + // wire-form `__voidPlatformTo` was preserved because nothing was stripped. + expect(message.to).toBe('support+T-42@acme.com'); + expect((message as { __voidPlatformTo?: string }).__voidPlatformTo).toBeUndefined(); + expect((message as { __voidRelayDomain?: string }).__voidRelayDomain).toBe('acme.com'); + + await dispatch(message, {}, {}, { slug: undefined }); + + expect(seen).toEqual([{ ticket: 'T-42' }]); + }); + it('routes an unprefixed recipient nothing matches to _default', async () => { const hits: Array = []; const dispatch = buildEmailDispatcher(compile({ ...SUPPORT, defaultHandler: '_default.ts' }), { diff --git a/packages/void/test/unit/email-own-account.test.ts b/packages/void/test/unit/email-own-account.test.ts index 8d87cdf20..945ac37fe 100644 --- a/packages/void/test/unit/email-own-account.test.ts +++ b/packages/void/test/unit/email-own-account.test.ts @@ -329,7 +329,12 @@ const INBOUND_MIME = * the actions" and "enact them on the native message" is what is under test. */ function buildHandleEmail( - userHandler: (message: ForwardableEmailMessage, env: unknown, ctx: unknown) => Promise, + userHandler: ( + message: ForwardableEmailMessage, + env: unknown, + ctx: unknown, + opts?: { slug?: string }, + ) => Promise, ): (envelope: unknown, env: unknown, ctx: unknown) => Promise { const code = compileWorkerEntry({ hasEmail: true }); const start = code.indexOf('async function handleEmail'); @@ -686,3 +691,103 @@ describe('generated handleEmail on a native ForwardableEmailMessage', () => { expect(isForwardableEmailMessage(envelope)).toBe(false); }); }); + +/** + * The relay lane (design doc 0078, "Custom domains on Cloudflare"): the + * envelope arrives over the platform router's `/email/relay` RPC with + * `viaDomain` set and a recipient that carries NO `+` prefix, while + * provisioning still injects `__VOID_PROJECT_SLUG` unconditionally. The + * generated `handleEmail` must suppress the slug so the dispatcher runs in + * no-prefix mode (Mode B item 4) — left applied, the strip would take + * everything up to the first `+` and `support+T-42@acme.com` would dispatch + * as `T-42` to `_default` or a wrong `[user]` param. + */ +describe('generated handleEmail on a relayed envelope (viaDomain)', () => { + function relayEnvelope(to = 'support+T-42@acme.com') { + return { + from: 'sender@example.com', + to, + headers: {}, + raw: new TextEncoder().encode(INBOUND_MIME), + rawSize: INBOUND_MIME.length, + viaDomain: 'acme.com', + }; + } + + it('suppresses the injected slug: the recipient reaches the handler unstripped', async () => { + const seen: Array<{ to: string; slug: unknown; platformTo: unknown }> = []; + const handleEmail = buildHandleEmail(async (message, _env, _ctx, opts) => { + seen.push({ + to: message.to, + slug: opts?.slug, + platformTo: (message as { __voidPlatformTo?: unknown }).__voidPlatformTo, + }); + }); + + // The slug deliberately equals the local-part prefix: stripping keyed on + // the slug alone would turn `support+T-42@` into `T-42@`. + const actions = await handleEmail(relayEnvelope(), { __VOID_PROJECT_SLUG: 'support' }, {}); + + expect(seen).toEqual([{ to: 'support+T-42@acme.com', slug: undefined, platformTo: undefined }]); + expect(actions).toEqual([]); + }); + + it('still strips the slug for a platform-lane envelope (no viaDomain)', async () => { + const seen: Array<{ to: string; slug: unknown }> = []; + const handleEmail = buildHandleEmail(async (message, _env, _ctx, opts) => { + seen.push({ to: message.to, slug: opts?.slug }); + }); + const envelope = { + from: 'sender@example.com', + to: 'acme+support@mail.void.cloud', + headers: {}, + raw: new TextEncoder().encode(INBOUND_MIME), + rawSize: INBOUND_MIME.length, + }; + + await handleEmail(envelope, { __VOID_PROJECT_SLUG: 'acme' }, {}); + + expect(seen).toEqual([{ to: 'support@mail.void.cloud', slug: 'acme' }]); + }); + + it('defaults replyEmail from to the receiving address on the customer domain', async () => { + const handleEmail = buildHandleEmail(async (message) => { + await replyEmail(message, { text: 'ack' }); + }); + + const actions = (await handleEmail( + relayEnvelope(), + { __VOID_PROJECT_SLUG: 'acme', __VOID_EMAIL_DOMAIN: 'mail.void.cloud' }, + {}, + )) as Array<{ type: string; from: string; to: string }>; + + // The spec's "Inbound identity": a reply to a relayed message leaves + // from the address that received it, on the customer domain — the + // platform's reply pin accepts exactly that shape for the receiving + // project, and the shared-sender `+noreply@` default would fail it. + expect(actions).toMatchObject([ + { type: 'reply', from: 'support+T-42@acme.com', to: 'sender@example.com' }, + ]); + }); + + it('keeps the shared-sender reply default on the platform lane', async () => { + const handleEmail = buildHandleEmail(async (message) => { + await replyEmail(message, { text: 'ack' }); + }); + const envelope = { + from: 'sender@example.com', + to: 'acme+support@mail.void.cloud', + headers: {}, + raw: new TextEncoder().encode(INBOUND_MIME), + rawSize: INBOUND_MIME.length, + }; + + const actions = (await handleEmail( + envelope, + { __VOID_PROJECT_SLUG: 'acme', __VOID_EMAIL_DOMAIN: 'mail.void.cloud' }, + {}, + )) as Array<{ type: string; from: string }>; + + expect(actions).toMatchObject([{ type: 'reply', from: 'acme+noreply@mail.void.cloud' }]); + }); +}); diff --git a/platform/meta/design-docs/0078-email-cf-native.md b/platform/meta/design-docs/0078-email-cf-native.md index fe0215186..6a8afedd6 100644 --- a/platform/meta/design-docs/0078-email-cf-native.md +++ b/platform/meta/design-docs/0078-email-cf-native.md @@ -203,12 +203,724 @@ semantics as production. Inbound parsing consumes a stream; handlers choose when to parse it. Threaded replies treat sender-supplied headers as untrusted and fall back safely when threading metadata is malformed. +## Custom domains on Cloudflare + +A project can send as and receive at its own domain — `support@acme.com`, +`noreply@mail.acme.com` — when that domain's DNS zone is on Cloudflare. The +zone stays in the customer's own Cloudflare account. The customer grants the +platform a scoped credential once; the platform configures the zone and runs +both directions on the customer's behalf. Inbound crosses accounts in a +**relay worker** deployed into the customer's account; outbound crosses back +as a REST send with the same credential. The relay needs no operator mail +zone, so custom domains work identically on a self-hosted platform, and the +raw MIME arrives unmodified — no `To:` recovery, no BCC loss, no SRS/ARC +hop, no destination verification click. The price is one wider token scope — +`Workers Scripts: Write` — which the customer sees on the token form. + +"On Cloudflare" means a zone under Cloudflare DNS in an account the customer +controls. A domain that only CNAMEs to Void through Cloudflare for SaaS is +**not** on Cloudflare in this sense and stays out of scope: Email Routing +needs MX records on a Cloudflare zone, and RFC 2181 forbids MX beside a +CNAME. Those customers keep the provider path in [Future Work](#future-work). + +### Why this model + +| Model | What it needs from the customer | Why it is or is not the one | +| ------------------------------------------------ | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| **Bring your zone — a scoped token** _(adopted)_ | create one API token, one dashboard step for a subdomain | zone stays theirs; apex MX untouched; works on Free for routing, Paid for sending; the domain signs its own DKIM, so reputation is per customer | +| NS delegation of the whole domain to our account | move all of their DNS to us | we would own and have to manage every record they have; greenfield DNS UI | +| `mail.acme.com` as its own zone in our account | delegate one subdomain | Cloudflare's subdomain setup is **Enterprise-only** | +| Self-hosted SMTP relay | nothing | reinvents what Email Routing gives for free | + +The "users never touch Cloudflare" premise is kept for the managed +platform's shared sender and dropped for a customer's **own domain**: the +customer already touches Cloudflare to own the zone, and the credential is +the same act of trust they give `wrangler login`. The rule that survives is +the one from [Hosting modes and lifecycle](#hosting-modes-and-lifecycle): +after the one-time grant, a developer sees an address, recipients, a counter +and an error code — never a zone, a rule or a token scope. + +### The two paths + +A routing rule can only name a worker in its own account — the rule's action +value is a bare worker name, and worker names are unique per account — so +inbound from a customer zone cannot reach `void-proxy` directly. It crosses +accounts inside a **relay worker** the platform deploys into the customer's +account with the stored credential, and outbound crosses back as a **REST +send** with the same credential. + +``` +INBOUND support+T-42@acme.com + │ MX in the customer's account (mail.acme.com, or the apex when its MX is empty) + ▼ + catch-all rule → void-email-relay (a worker in the customer's account, deployed by setup) + │ envelope recipient exact — To:, Cc: and BCC alike · raw MIME unmodified + ▼ + POST proxy.void.cloud/email/relay Authorization: the domain's relay secret + │ secret → registered domain → project + ▼ + project worker email() to = support+T-42@acme.com viaDomain = acme.com + dispatcher runs in no-prefix mode (Mode B item 4) + +OUTBOUND sendEmail({ from: "noreply@acme.com", … }) + │ proxy: from-domain is registered to this project → use that domain's credential + ▼ + POST /accounts/{customer}/email/sending/send_raw { from, recipients, mime_message } + DKIM = acme.com (or mail.acme.com) · quota = the customer's · message_id returned +``` + +**The relay worker.** One per registered domain, named `void-email-relay` +(suffixed `-2`, `-3`… on collision within the account, up to 50). It is ~30 +lines: the `email()` handler streams `message.raw` straight into a POST with +the domain's relay secret — no parsing, no buffering, so it stays inside +Workers Free CPU limits, and messages over the 25 MiB inbound cap never +reach it (Cloudflare rejects them first). The stream rides through a +`FixedLengthStream(rawSize)`: the runtime derives Content-Length from the +body and ignores a hand-set one, so a plain stream would go out chunked — +and the proxy refuses a length-less body before any crypto. `message.to` is a single address +(the envelope RCPT TO), so a multi-recipient message arrives as one +invocation per recipient. The catch-all is zone-scoped with no domain +parameter, so mail for a second domain on the same zone can land on the +first domain's relay: the relay refuses any message whose recipient domain +is not its own (`setReject` — a loud bounce, not a silent drop), and the +proxy's `/email/relay` branch independently 403s when the declared +`X-Void-Email-Domain` header does not equal the recipient's domain, keying +its mirror lookup on the recipient's domain. Attribution binds to the +envelope recipient, never the relay's claim. + +Setup deploys the relay with the stored credential (`PUT +/accounts/{a}/workers/scripts/{name}` — one `Workers Scripts: Edit` token +covers both the script PUT and the secret PUT) and points the zone's +catch-all at it: + +``` +PUT /zones/{z}/email/routing/rules/catch_all +{ "matchers": [{ "type": "all" }], + "actions": [{ "type": "worker", "value": ["void-email-relay"] }], + "enabled": true } +``` + +`value` is an array with exactly one entry, and a catch-all holds exactly +one action. Omitted `source` defaults to `api`, which has one edge: if the +customer later runs `wrangler deploy` with an `addresses` array on the same +zone, wrangler reports our rule as an externally-managed conflict and asks +before taking over. Documented in `status` output, not fought. The name is +stable once chosen: renaming a worker detaches every routing rule pointing +at it, so `sync` redeploys in place and never renames. A walked name is +claimed on the row BEFORE the script upload and secret PUT (see the +concurrency backstops), so a failed write still leaves the row knowing its +relay — a retry redeploys in place and a remove can find the worker; name +exhaustion fails the deploy with no name recorded (nothing was uploaded). The code is ours but the worker is the +customer's: they can read it, edit it or delete it, and `status` reports +drift on the next probe rather than fighting it. When the relay code +changes, `status` shows the deployed version and `void email domain sync` +redeploys with the stored credential. A leaked secret lets a stranger push +mail into one project's inbound, nothing else; `sync` rotates it. Worker +secrets are write-only — not even the account owner can read one back — so +rotation is overwrite with a new value, never read-compare. + +**Inbound identity.** The relay sees the envelope recipient, so the address +the sender wrote arrives exact — a BCC included. The raw MIME passes through +unmodified: no SRS rewrite, no ARC seal, no `To:` recovery. `replyEmail` on +a relayed message defaults `from` to the address that received it, on the +customer domain, and goes out over the REST path. + +**Trust.** The proxy accepts a relayed message only with the domain's relay +secret, generated by the platform at setup and stored on the row; the secret +maps to exactly one registered domain of one project, so `viaDomain` cannot +be forged without it. The proxy's auth branch applies header/length bounds +before any crypto, looks the domain's mirror up in ROUTING KV, compares the +secret's sha256 in constant time, and refuses any mirror whose status is not +`active` — a revoked or removed domain stops receiving at the proxy, not at +the relay. The reply-sender pin gains a second accepted shape: any address +on a domain registered to the receiving project. A reply send then runs +through the FROM domain's own mirror and credential lease — two domains of +one project can live in different customer accounts, and Email Service +rejects a sender outside the sending account's verified zones. + +### The flow — `void email domain add acme.com` + +Mirrors `void domain add`: a row that goes `pending → active`, printed +instructions for the steps only a human can do, and `status` to poll. + +``` +$ void email domain add acme.com + MX acme.com carries MX for google.com → apex is off limits + using mail.acme.com [change with --subdomain] + Grant opening Cloudflare's consent page — it names Wrangler; that is expected [Allow] + ◀ access + refresh token · zone:read · email_routing:write · email_sending:write · workers_scripts:write + (no browser here, or the consent fails? Enter switches to the template-link token path) + Verify grant works · zone acme.com found in account …f721 + Stored refresh token on the platform, encrypted for this project · nothing kept on this machine + Routing mail.acme.com is not on Email Routing yet + → add it: Email Routing → acme.com → Settings → Subdomains (dashboard only) + Sending mail.acme.com onboarded — cf-bounce MX, SPF, DKIM, DMARC added + Relay void-email-relay deployed into account …f721 · catch-all → relay + Status pending · run `void email domain status acme.com` +``` + +Who does what: + +| Step | Who | How | +| ------------------------ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| grant | customer, one click | the CLI runs Cloudflare's OAuth consent on wrangler's public client; no browser or a failed consent falls back to the three-click template link | +| zone lookup, MX check | platform | `GET /zones?name=`, public DNS — no token needed for MX | +| routing on the apex | platform | `POST /zones/{z}/email/routing/dns`, only when MX is empty | +| routing on a subdomain | customer, once | dashboard — no API exists; the CLI prints the exact path and polls | +| Email Sending onboarding | platform | `POST /zones/{z}/email/sending/subdomains { name }` | +| relay worker | platform | `PUT /accounts/{c}/workers/scripts/void-email-relay` + the relay secret as a worker secret | +| catch-all → relay | platform | `GET` then `PUT /zones/{z}/email/routing/rules/catch_all`, action `worker` naming the relay — never written over an enabled foreign rule | +| status → active | platform | every probe green; the map printed | + +The catch-all is never written blind. Setup reads it first (`GET +…/rules/catch_all`): an enabled rule naming anything but this row's relay +fails the row at `catch_all` with a conflict message — one zone routes one +email domain — and a rule already naming it makes the write a no-op. +`remove` resets the rule only when the same read shows it still naming this +row's relay; a foreign or unreadable rule is left alone (the latter reports +`catch_all` in `failed_steps`). The sending-onboard read-back paginates — +CF's list endpoint returns 20 per page, so confirmation walks +`?page=N&per_page=50` until a short page. + +Email Sending is paid-plan-only while Email Routing is not, so an +entitlement refusal (CF error codes 2036/10105 — a Workers Free account) +does not fail setup: the relay and catch-all still deploy, and the row +lands `active` with `remaining_steps: ['sending_onboarding']`. Inbound +works; only the outbound lane (`send_raw`) stays refused at Cloudflare +until a plan upgrade, and the CLI prints that hint. Only the +inbound-blocking step gates the row: `routing_subdomain` holds it at +`pending`, while `sending_onboarding` rides along on an active row. + +`void email domain status`, `list`, `sync`, `remove`. `sync` redeploys the +relay in place, rotates its secret, and runs the catch-all ensure whenever +the row carries a zone: missing, disabled or non-worker rules are repointed +(`ensured`); a rule already naming this row's relay is left alone +(`already_set`); an enabled rule naming a DIFFERENT worker is reported +(`foreign_conflict`) and never overwritten; a probe failure is +`probe_failed`. The status GET is read-only: it reports `catch_all` +(`points_here` / `points_elsewhere` / `missing` / `disabled` / `unknown`) +and `catch_all_drift` on live rows; healing is the sync POST, which the +CLI's drift hint names. A `pending` row whose only remaining step is +`routing_subdomain` self-clears: the status GET probes public DNS for MX +naming Cloudflare's inbound exchanges (`route1..3.mx.cloudflare.net`) — the +dashboard form's observable effect — and on evidence flips the row to +`active` and the mirror follows. The `sending_onboarding` step self-clears +the same way on its own evidence — the customer-credential read-back +showing the subdomain onboarded — and `sync` re-attempts the onboarding +POST outright, so a Workers Paid upgrade completes the row without +re-adding. The self-clear write is fenced on the probed status and setup +state, and is suppressed while a removal failure (`failed_step: 'remove'`) +is pending, so a poll never rewrites a row that a concurrent revocation or +an unfinished removal just changed. The customer can also revoke the credential +at Cloudflare at any time; the next probe sees it and the row reads +`token_revoked` / `token_expired`, with inbound continuing until they delete +the rule or the relay themselves. + +### Setup is re-runnable + +Re-adding a `failed` row re-runs the full engine against the row's recorded +progress, and a re-run never erases what the row already learned: the engine +seeds its returned progress from the row (`zone_id` / `account_id` / `mode` +/ `relay_worker_name`), so a re-run that fails early (a dead credential at +`verify_credential`) still persists them. A recorded mode skips the MX check +(the first attempt's enable_routing put OUR MX on the domain), a recorded +relay name redeploys in place rather than walking to a fresh `-2`, and an +"already done" 400/409 from enable_routing/onboard_sending is believed only +when a read-back of the actual zone state confirms it (`GET email/routing`'s +`enabled`, resp. the sending-subdomain list) — fail-closed otherwise. +Healthy rows (active / pending / credential renewal) take the sync-only +path. + +### Concurrency and durability backstops + +- **Two partial unique indexes backstop the engine's check-then-write.** One + live row per zone (`status IN ('active','pending')`, so a `failed` row can + still record the zone it failed in) and one relay name per account + (`relay_worker_name IS NOT NULL` — a deployed relay really exists). Setup + CLAIMS its walked relay name on its own row against the relay index + BEFORE any upload, so two setups racing one account serialize + first-to-claim: a concurrent claim blocks on the winner's uncommitted + UPDATE, then 23505s past its commit (the walk advances to the next + suffix) or proceeds past its rollback. First-to-claim, never + last-write-wins — the loser's walk never writes a worker the winner may + already be using, and an engine throw after a successful claim restores + the row's locked pre-engine values so the claim does not outlive its + setup. A racing loser that still violates an index (the zone race, or a + row written before the claim existed) gets a 409; the + constraint name classifies the race, read by walking the error's cause + chain (both drivers — PGlite and `pg` — expose it as `constraint` on the + frame that carries the code). The loser's CF-side work is compensated + best-effort from what its engine returned: a zone race fully removes, a + relay-name race never deletes the contested worker — only its zone rule is + conditionally detached, because the destructive misclassification would be + deleting a worker another live row owns. +- **A deploy checkpoint closes the catch-all race structurally.** The engine + fires a `persistProgress` dep once — after the relay deploy + secret PUT, + before the catch-all write — and the route persists it + (`applyEmailDomainDeployCheckpoint`, an UPDATE…RETURNING). With the + zone index, a racing loser 23505s at the checkpoint and never writes its + zone rule, so the last-write-wins window (loser's rule overwritten onto + the zone, winner's row live but unrouted) cannot occur for fresh adds. + (The relay-name race is closed earlier, at the pre-upload claim — on a + fresh setup the checkpoint's name and account writes are same-value + no-ops.) Checkpoints are skipped on in-place redeploys — a row that + already carries `relay_worker_name` already knows. +- **Any checkpoint failure compensates from the captured payload.** A + non-unique checkpoint error, or the row cascade-deleted by teardown + mid-setup, leaves the relay deployed but unrecorded; the route runs + `removeEmailDomain` from the in-memory checkpoint before propagating (the + catch-all was never written, so the conditional reset is a no-op). A gone + row switches the grant refresh to the engine default, which acts on the + held credential — the serialized chain needs the row — and 409s as + `project is being deleted`; other failures rethrow. +- **A re-run that 23505s at the final apply repoints rather than resets.** + The compensation does a winner lookup (`zone_id` + the index's live + statuses + relay non-null, excluding the loser) and hands + `repoint_catch_all_to` to the engine, which REPOINTS an owned rule at the + winner instead of resetting it — the winner's existence is probed before + AND after the PUT, and a lookup failure degrades to the plain reset. One + zone keeps working mail through the conflict. +- **A non-unique apply failure does not orphan the relay.** The apply + wrapper re-reads the row: committed (relay name AND `relay_version` match + — the checkpoint never writes the version, so the pair distinguishes a + committed apply from a checkpoint write) → the row stands as applied; + otherwise the possibly-deployed CF state is compensated from the engine's + result with its own account_id and the original error rethrows. A re-read + failure logs and rethrows; a null relay (setup failed before the deploy) + never compensates. The sync route's live-status flip can also 23505 (a + `failed` row rejoining the live set while a winner holds its zone) — + mapped to the same 409 zone message, deliberately without compensation. +- **Sync serializes the whole rotation under the project and credential + row locks, in teardown's order.** Relay redeploy, secret PUT, row apply + and mirror publication run in one transaction that takes the project row + FOR UPDATE first — refusing when teardown has marked it `deleting`, so a + sync that raced the route's entry guard can never redeploy or republish + state teardown already cleared — and then the domain row FOR UPDATE, the + lease chain's own. The row — credential included — is re-read under the + lock: a credential replace that lands while a sync waits is synced as + the new credential, never verified as the superseded one, and two + overlapping syncs publish the worker secret and its mirror hash in the + same order. A mirror PUT failure rolls the row apply back with it. +- **The add path serializes the same way, in two transactions.** The row + insert (credential + fresh relay secret) commits under the project lock + with the `deleting` verdict re-read inside — so teardown's one-time + cleanup enumerations can never miss an in-flight add — and the engine + then runs in the follow-up serialized section, which re-takes both locks + and decides sync vs full setup on the LOCKED row. A retry that queued + behind a completed setup takes the sync branch, so two concurrent retries + of an incomplete setup cannot write one secret to the worker and record + another on the row and mirror. The engine's checkpoint and apply writes + ride savepoints inside that transaction, keeping it committable when an + expected 23505 lands; the compensations above then run outside it. +- **A lease-time revocation publishes its mirror under the row lock, + conditioned on the revoked credential.** When a lease refresh hits + `invalid_grant` the `token_revoked` flip commits inside the lease + transaction, and the ROUTING mirror write that must follow runs in a + second locked section: the row is re-read FOR UPDATE and the mirror is + published from the LOCKED row — the relay hash is never a stale + snapshot — and only while the row still holds the credential that was + revoked. A credential replace that committed in between published its + own active mirror under the same lock, so the revocation write skips + rather than overwrite it and leave an active row with dead mail. + +### Removal and teardown + +- **Removal detaches before it deletes.** `removeEmailDomain` resets the + zone catch-all (when the ownership read shows it still naming this row's + relay) BEFORE deleting the relay script; if the read or the reset fails, + the delete is deliberately skipped and both steps report failed — an + enabled catch-all never points at a deleted worker; rule and relay stay a + consistent pair. +- **A failed removal keeps the row.** DELETE's CF cleanup failing on a + destructive step (`catch_all` or `delete_relay`) marks the row + `setup_state.failed_step = 'remove'` + `removal_failed_steps` (both ride + the existing jsonb — no migration) and answers `200 { ok: false, removed: +false, failed_steps }`. The owner retries once the CF-side problem is + fixed, or forces with `?force=1` (`removed: true, forced: true`). Two + exceptions still delete unconditionally: `token_revoked` rows (the grant + is already dead, keeping buys no retry leverage) and a `revoke_grant`-only + failure (a stranded grant breaks no mail). While a row carries the removal + mark the status GET suppresses its mirror repair — the proxy's view must + not be "repaired" against a removal the operator is about to finish. The + CLI mirrors the contract: `--force`, exit 1 with retry guidance on + `removed: false`, and manual-cleanup hints on a forced removal. +- **Removal runs under the same row lock.** The owner DELETE re-reads the + row — credential included — inside the lease chain's FOR UPDATE and + builds its cleanup from what the row holds at lock time: a replace that + commits while a removal waits is removed as the NEW credential (its + grant revoked), never orphaned by a row delete built on the stale + snapshot — the replace never invalidates an old API token, so the stale + cleanup would have succeeded and the new grant's only handle would have + been deleted with the row. Mirror clear and row delete stay inside the + same transaction; a KV failure rolls the row delete back with it. +- **Project teardown cleans the customer side.** After the KV mirrors are + revoked (fail-closed) and before the DB cascade, teardown runs + `removeEmailDomain` for each registered domain with a deployed relay, + best-effort and never throwing: the mirrors being gone makes a stranded + relay inert, and the grant refresh goes through the row's serialized chain + so a crash before the cascade leaves the credential live for the retry. +- **The admin surface follows the same order.** The full-removal route + runs under the same row lock with the row — credential included — + re-read inside it (a credential replace committed mid-removal is cleaned + up as the NEW credential, never orphaned by a stale-snapshot delete), + clears the ROUTING mirror first, runs the same engine removal (with the + grant deps below), then deletes the row; a mirror-clear failure keeps the + row and runs nothing destructive. The operator escape hatch `POST +/admin/email/:projectId/domains/:domain/revoke-grant` kills one domain's + grant without tearing the domain down: the whole operation runs as one + serialized section under the same row lock with the row — credential + included — re-read inside it, so the grant it revokes is the row's live + head at lock time (a credential replace committed before the lock is + revoked as the NEW grant, never stranded live under a `token_revoked` + row). It writes the mirror as `token_revoked` FIRST (the proxy's relay + auth checks `active`, so inbound stops here), then revokes, then flips + the row. A failed revoke answers 502 with the row still active, and the + next status GET repairs the mirror — the same self-heal as any drift. + +### Data and the credential + +- `email_domains` — `project_id`, `domain` (the address domain, apex or + subdomain), `zone_id`, `account_id`, `mode: 'apex' | 'subdomain'`, + `status: 'pending' | 'active' | 'token_revoked' | 'token_expired' | +'failed'`, `relay_worker_name`, `relay_version`, the relay secret + ciphertext triple, `setup_state` (a jsonb carrying `failed_step`, + `remaining_steps` or `removal_failed_steps`), `attempt_id` (the CLI add + attempt that last wrote the credential — null on rows an older CLI + wrote), `token_id` and + `token_expires_on` from `GET /user/tokens/verify` (so `status` can name + the token to revoke and warn before a TTL runs out), timestamps. The two + partial unique indexes from the backstops section ride the same table. +- The credential is stored with `encryptProjectSecret` under the project's + envelope key, per domain, and only the api and proxy ever decrypt it. It + is never written to a manifest or a log — the one worker it deploys is the + relay, and the relay carries only its own domain's secret, never the + credential. The relay secret is encrypted on the same envelope. The AAD is + `${projectId}:${name}` with fixed per-row names — + `email-domain-token:` and `email-domain-relay:`. +- The proxy never reads the row: the api mirrors what the proxy needs to + ROUTING KV as `email-domain:` — `{ projectId, status, +relaySecretSha256, relayWorkerName, accountId, zoneId, mode }` — rewritten + on every status transition and secret rotation, tightened before any + revoke, deleted on removal, and repaired by the status GET when it drifts + (the repair re-reads the row under the lock and re-checks drift against + it, so a rotation committed mid-poll is never overwritten back to the + pre-rotation hash). +- Scopes, minimum: zone-scoped `Zone Read` (to find the zone id), `Email +Routing Rules Edit` (the catch-all) and `Zone Settings Edit` (the routing + POST, both paths); account-scoped `Workers Scripts: Write` (to deploy and + update the relay) and `Email Sending Edit`. `Email Routing Addresses Edit` + is not needed — there is no destination address to manage — and `DNS Read` + is not needed — MX is read over public DNS. Account-level scopes are + necessarily account-wide, and `Workers Scripts: Write` is the wide one: + per-script scoping does not exist (the token resource picker stops at the + account), so it covers every script in the account, and the token summary + page shows that before the customer clicks **Create Token**. That breadth + is the honest price of "connect and we configure it for you" — Mode B + already asks for the same trust through `wrangler login`. + +### The OAuth grant on wrangler's client + +The primary credential path is Cloudflare's OAuth consent on **wrangler's +public OAuth client**: the CLI opens the consent page with wrangler's +`client_id` (a public PKCE client with no secret; endpoints +`dash.cloudflare.com/oauth2/{auth,token,revoke}`), the customer clicks +**Allow**, and the platform stores the refresh token. The CLI uses a +`localhost:8976/oauth/callback` redirect, as wrangler does; every observed +third-party flow on this client id redirects to localhost, so whether +Cloudflare accepts any other redirect URI for it is unverified (probe 8) — +which is why the dashboard ships the template link + paste box either way. + +What it costs, recorded with the decision: + +- **Breadth.** An OAuth grant is user-wide — every account the user belongs + to, every zone in them, for the granted scopes. `wrangler whoami` shows + this today. A template-link token can be narrowed to one zone; a grant + cannot. The template link stays as the narrow option for a company with + many zones; the grant is the default for everyone else. +- **Refresh.** The access token lives about an hour. Refresh tokens are + **single-use and rotate**, so the platform runs its own grant chain — it + never touches the refresh token in the developer's `~/.wrangler`, which + would race wrangler's own refreshes and kill both. Refresh is serialized + per domain row and the rotated token is persisted atomically with it + (the credential lease). A revoked grant surfaces as `token_revoked`. +- **Scopes.** The grant asks for wrangler's own names: `zone:read`, + `email_routing:write` ("settings, rules, and destination addresses"), + `email_sending:write`, `workers_scripts:write`, plus `offline_access`. + There is **no `zone_settings` OAuth scope** — the session reaches the + email zone-settings endpoints under `email_routing:write`'s "settings" + wording. +- **The consent screen names Wrangler.** It is Cloudflare's hosted page for + the wrangler client; it cannot say Void. The CLI prints one line before + opening the browser so the customer is not surprised. +- **The client id is not ours.** Cloudflare can rotate or revoke it any + day — so the template link + paste is not a legacy path, it is the + permanent fallback the CLI drops to when the consent flow fails. + +**The grant is revoked on every path that should kill it.** +`revokeOauthGrant` POSTs the RFC 7009 form to +`dash.cloudflare.com/oauth2/revoke` (wrangler's client id, +`token_type_hint=refresh_token`, no Authorization header — a public client +authenticates with the token itself, exactly wrangler's `logout`). It throws +on a network failure or non-2xx — CF answers 200 even for a bogus token, so +a failure leaves the grant's state genuinely unknown and callers record +`revoke_grant` in `failed_steps` — and it never logs the token. Removal +revokes LAST, with the rotated chain head (a transient refresh failure +revokes the original stored token instead; `invalid_grant` skips — CF +already killed it). Credential replace revokes the old grant after the +commit — a re-pasted identical grant is skipped (revoking it would brick the +just-stored credential) and a revoke failure is logged, never fatal. +Teardown and admin removal revoke. Conflict compensation deliberately does +NOT — the loser's credential may survive on another row. A REJECTED add +attempt revokes too: the CLI mints a fresh grant per attempt and drops its +only copy on ANY error response, so every rejection — validation 400, +cross-project conflict 409, teardown 409, and the project guards' 404/403 — +revokes the posted grant first. Revocation asks for no ownership: for a +public client the token itself is the only credential the RFC 7009 endpoint +wants, so revoking what was posted grants the caller nothing they did not +already hold. One guard: a re-pasted grant equal to the conflicting row's +stored credential is kept (revoking it would brick the live row). A LOST answer is not a +rejection either: every add attempt carries a random attempt id, stamped +on the row at insert and at credential replace, and always serialized on +the status GET (null on rows an older CLI wrote — an api predating +attempt identity omits the key, and key presence is how a new CLI detects +one). When the POST's response never arrives — or the answer is ambiguous: +a 5xx, or a 401/403/413/426/429 from middleware or the edge; only the +route's deliberate 400/404/409 rejections prove a server-side revoke (a +403 is ambiguous: middleware answers it before the route ever parses the +body — a suspended account, a mis-scoped deploy token — so it may carry +no revoke at all, and the CLI cannot tell the two 403s apart) — the CLI +polls the status, 15 tries, 1s apart, because a lost answer does not stop +the api worker mid-commit. The row carrying THIS attempt's id means the +add committed +(printed, done, never revoked). A row stamped with a DIFFERENT id — or +null — kept its existing credential: a committed add of mine would have +stamped my id, so this attempt's grant was never stored and is revoked, +and the failure says to re-run. A 404 at every poll means nothing +persisted: the held grant is revoked (via the CLI's own best-effort copy +of the same RFC 7009 POST). A row from an api without the key is trusted +like the pre-attempt flow, never revoked — a committed add there is +indistinguishable from a pre-existing row. And no informative read at all +is reported as unknown — a blind revoke could brick a row that did +commit. Where the CLI does revoke, it claims the revocation only when +Cloudflare confirms it (200 — CF answers 200 even for a bogus token); a +failed revoke is reported with manual-revocation steps, never claimed. +The consent flow's own straggler dies the same way: an exchange that +completes after the flow settled (Enter, an abort, the timeout) minted a +grant only the CLI holds, so it is revoked fire-and-forget and the browser +tab gets a cancelled page rather than hanging on the closed server. The +revocation's cascade scope (access tokens minted from the grant) is +undocumented and unprobed — accepted. + +And the path that does **not** work, so nobody designs it again: minting a +long-lived scoped API token from the session (`POST /user/tokens` with the +bearer). Token creation requires the `API Tokens Write` group, which is not +in wrangler's OAuth scope set and does not exist as an OAuth scope at all. +The session bearer alone is no substitute either: it expires in an hour, and +its refresh chain belongs to wrangler — borrowing the **access** token via +`wrangler auth token` is safe (wrangler refreshes it); refreshing it outside +wrangler races the single-use rotation. + +### Creating the token in three clicks + +The fallback grant path, for a browserless terminal, a failed consent flow, +or a company that wants a zone-narrowed token. Cloudflare's dashboard +accepts a template URL that pre-fills the token form — name, permission +groups, resources. The CLI opens it; the customer clicks **Continue to +summary**, **Create Token**, **Copy** — and the CLI takes the token from the +clipboard. Three clicks, nothing typed (plus a login if the browser has +none). + +``` +CLI browser CLI + │ MX check over public DNS │ │ + │ → apex or subdomain decided │ │ + │ build the link (scopes fit the path)│ │ + │ snapshot the clipboard │ │ + │ open ─────────────────────────────▶ │ form is pre-filled │ + │ watch the clipboard (≤ 10 min) │ 1 Continue to summary │ + │ │ 2 Create Token │ + │ ◀──────────────────────── clipboard │ 3 Copy │ + │ shape ok → GET /user/tokens/verify → clear the clipboard │ + │ GET /zones?name=acme.com · scope check │ + │ send over TLS → platform stores with encryptProjectSecret │ + │ drop it from memory · continue with Zone / Routing … │ +``` + +| Branch | What the developer sees | +| ------------------------------------- | ------------------------------------------------------------------------------------------------ | +| clipboard unchanged, or wrong shape | nothing; still waiting. Enter switches to the paste prompt | +| verify says not active | "that is not an active Cloudflare token — still waiting" | +| 10 minutes, nothing | the paste prompt; Esc cancels with nothing stored anywhere | +| zone not found with this token | `failed · acme.com is not in an account this token can see` → re-run `add` | +| 403 on a scope probe | `failed · missing Workers Scripts Edit` → re-run `add`; the link carries the key | +| `expires_on` passed, or revoked at CF | `status` reads `token expired` / `token revoked`; `add` again replaces the token, rules stay | +| `remove` | catch-all rule and relay worker deleted with the token, best effort; then the row and ciphertext | + +**The clipboard watch** reads only between opening the link and getting a +token, never otherwise, and says so on screen. It ignores whatever was on +the clipboard before the link opened (the snapshot) and accepts only a _new_ +value shaped like a Cloudflare token: the current `cfut_` format (prefix, 40 +characters, checksum) or a legacy 40-character `[A-Za-z0-9_-]` value; other +vendor prefixes (`ghp_`, `github_pat_`, `sk-`, `xox`, `cfk_`) are refused +without a network call. Only a value that passes the shape check is sent to +`GET /user/tokens/verify`, and only `status: active` is accepted. It clears +the clipboard once it has the token, so the token does not sit there for the +next paste — a clipboard manager's history is outside our reach, and the CLI +says so once. Enter at any time switches to the masked paste prompt; no +clipboard tool (SSH, CI, a Wayland session without `wl-paste`) falls back to +it silently. Nothing on the clipboard is ever printed or logged. + +The link: + +``` +https://dash.cloudflare.com/profile/api-tokens + ?permissionGroupKeys= + &accountId=* # required by the form; "all accounts" — the customer narrows it in the summary if they like + &zoneId=all # required by the form; narrow to acme.com in the summary (undocumented whether honoured) + &name=Void%20email%20%E2%80%94%20acme.com +``` + +```json +[ + { "key": "zone", "type": "read" }, + { "key": "email_routing_rule", "type": "edit" }, + { "key": "email_sending", "type": "edit" }, + { "key": "workers_scripts", "type": "edit" }, + { "key": "zone_settings", "type": "edit" } +] +``` + +Every key rides every link — there is no apex-only key, because `Zone +Settings Edit` gates the routing POST on both paths. The documented key +table stops at `workers_*` / `zone_settings`; the two email keys are +community-verified (`email_routing_rule` from the dashboard permission-group +dump, `email_sending` from erxes' shipped config), and unknown keys are +silently dropped — so the docs also show the manual token-creation steps +rather than relying on the pre-fill alone. + +What this path does not do, so nobody expects it: + +- The dashboard never hands the token back. There is no redirect, no + callback, no local listener to receive it — the paste is the transport. +- Creating the token by API (`POST /accounts/{id}/tokens`) needs a token + with `API Tokens: Edit` first — the same chicken, one egg earlier. +- The developer's local `wrangler login` session cannot replace the stored + grant: the bearer expires in an hour and its refresh chain belongs to + wrangler, and the session cannot mint the platform a long-lived token + (above). + +**Where the token lives.** On the platform, encrypted per project with +`encryptProjectSecret` — the proxy sends with it at runtime and the api +re-probes with it, so that copy is the one that must exist. On the +developer's machine: nowhere. The CLI holds it in memory, hands it to the +platform over TLS as its first call, and drops it; every later step +(`status`, `remove`, repair) goes through the platform. The one thing the +platform copy does not solve is a **TTL** the customer set on the form: +sends stop when it expires, `status` reads `token expired`, and `void email +domain add` again is the renewal. The account-token form is the better home +for a company, because the token survives the employee — but it needs an +Administrator and cannot carry `accountId`/`zoneId` parameters, so the user +token is the default. + +### What changes in the existing rules + +- **Reply-sender pin** — accepts the receiving slug on the shared domain + _or_ any address on a domain registered to the project. +- **Recipient allowlist** — does not gate custom-domain sends, relayed + forward/reply actions included: Cloudflare's verified-destination gate is + lifted by the customer's own onboarding, and the reputation at stake is + the customer's own. The burst cap and the kill switch still apply. +- **Quotas and kill switch** — the platform's burst cap and suspend switch + keep applying to every send that passes through the proxy, custom domain + or not; the daily quota is the customer's account's. +- **The 200-destination cap is untouched** — a relay consumes no destination + address in either account. +- **One worker of ours lives in their account** — readable, editable and + deletable by the customer, as everything in their account is. `status` + reports drift; it does not fight it. + +### Limits, stated plainly + +- The customer's account must be on **Workers Paid** to send; routing alone + works on Free. +- Two steps stay human: the credential grant (one Allow click, or three + clicks and a paste) and the routing-subdomain dashboard form. +- The credential asks for `Workers Scripts: Write` — account-wide, and the + customer sees that on the token form — and one relay worker lives in the + customer's account. +- Inbound messages cap at 25 MiB (Cloudflare rejects larger ones before the + relay runs), a zone holds at most 30 email domains, and a domain holds at + most 200 routing rules. +- The relay name-walk caps at 50 names per account (`void-email-relay` + through `-50`); exhaustion fails the deploy step with nothing uploaded. +- A domain that is not on Cloudflare DNS is not covered. + +### Mode B + +The developer's own zone needs none of this. Their worker holds the +`send_email` binding, the rules target their worker directly, and there is +no relay and no stored credential — [Mode +B](#mode-b--the-developers-own-cloudflare-account) already covers it. + +### Verified against live Cloudflare + +Probed on a real zone (voidcloud.dev, restored byte-identical afterward), +2026-09-17: `POST …/email/routing/dns {name}` enables a subdomain (200, +three MX auto-created); sending onboard with a user API token succeeds (200) +— the schema declares Global-key-only, so the declared auth lags the +endpoint — and also stamps the apex SPF + DKIM; apex enable is an empty-body +POST; ONE zone-scoped catch-all (auto-created drop+disabled on first +enable) covers apex and subdomain — there is no per-email-domain rule; relay +script PUT + secret PUT + catch-all PUT all accept an API token (200/201/200 + +- read-back enabled); `send_raw` takes the JSON envelope `{from, recipients, +mime_message}` (a raw `message/rfc822` body earns `10001 +invalid_request_schema`) and returns `200 queued` with a message_id. The + revocation endpoint is advertised by the OIDC discovery document and answers + 200 even for a bogus token. `routing/dns` is authorized by Zone Settings + Write and rules by Email Routing Rules Write; `10103 bad_token_type` is + Email Sending's credential-type rejection; `send_raw` accepts user and + account tokens (account-owned recommended). CF's cleanup does not remove + `_dmarc.` on subdomain/routing deletion — the engine never touches DNS + by design, and the CLI prints the manual cleanup list. + +Still open: the dashboard-UI probes, the browser PKCE run (what the consent +screen says, whether a non-localhost redirect is accepted, rotation over a +few cycles, whether the grant's `email_routing:write` covers the two calls +wrangler never makes), a message-level inbound E2E (needs observability an +API token cannot reach), and the narrow template-token variants. + +### Where each piece lives + +- **CF calls from the api** follow `cfFetch` + (`platform/packages/api/src/provisioning/cloudflare-api.ts`). The relay + deploy is a plain `PUT /accounts/{a}/workers/scripts/{name}` with a + multipart FormData body, plus a non-namespace variant of `putWorkerSecret`. +- **The relay source is an embedded asset in the api worker** — one constant + module plus a `relay_version`; `sync` redeploys it. +- **`/email/relay` in the proxy** is a branch in the global auth middleware, + modelled on the `/email/internal/` branch: size bounds before any crypto, + secret → mirror → project, then the second half of `routeInbound` + (envelope → `stub.email` → `enactActions`) keyed by the domain's project + instead of a slug parsed from the recipient. The relayed header summary + is bounded on two axes, like the platform lane's pre-buffering: a + distinct-name cap, and a total-pieces cap charged per header piece + (distinct names + repeat occurrences + folds) — one name repeated inside + the MIME cap otherwise allocates unboundedly in the shared isolate. +- **Schema:** `email_domains` follows the `emailDestinations` template + (`status` as a `$type` union, CHECK constraints declared in the schema so + drizzle-kit doesn't diff them away); migration `0039_email_domains`. +- **CLI:** `void email domain …` verbs under the email group; API calls join + `PlatformClient`'s `/projects/:id/email/…` methods; the owner-guard routes + live in `routes/email.ts`; the admin section in `admin/routes/email.tsx`. + ## Deferred decisions -Custom sender domains on the managed platform, third-party provider wrappers, -component templates, typed sender discovery and persistent delivery logs are -not implemented by this record. Users can call a provider SDK directly where -appropriate. +Custom sender domains on the managed platform ARE implemented — see +[Custom domains on Cloudflare](#custom-domains-on-cloudflare). Third-party +provider wrappers, component templates, typed sender discovery and persistent +delivery logs are not implemented by this record. Users can call a provider +SDK directly where appropriate. Native setup currently detects email at the feature level rather than separately onboarding inbound-only apps. Splitting that detection would also diff --git a/platform/meta/lessons.md b/platform/meta/lessons.md index 5ea7ed1a0..75ef7ce2f 100644 --- a/platform/meta/lessons.md +++ b/platform/meta/lessons.md @@ -22,6 +22,10 @@ - `vp run