Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(email): an unauthenticated From is no longer a workspace member (#319)
OKNOTOK5e1d8e5c7150
diff --git a/SECURITY.md b/SECURITY.mdindex 0346a74..055f5d7 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -79,14 +79,15 @@ compensating controls are written down in[`server/k8s/gke.md`](server/k8s/gke.md) under "Agent policy and runtimesecurity prerequisites".-**Inbound email is not authenticated.** `workers/email-gate` accepts mail-whose recipient domain is listed. It does not read `Authentication-Results`-and does not check SPF, DKIM, or DMARC. The server then maps the `From:`-header onto an agent or a human in the recipient's workspace. A spoofed-`From:` can show up as an internal author and enter an agent's context.-The HMAC on `/webhooks/email/inbound` authenticates the worker to the-server. It says nothing about the sender. Details are in-[`docs/email.md`](docs/email.md).+**Inbound email is authenticated before it can wear an internal identity.**+`workers/email-gate` accepts mail whose recipient domain is listed. It+reports Cloudflare's `Authentication-Results` (`mx.cloudflare.net` only) as+`authVerdict`, plus the SMTP envelope sender. The server maps the `From:`+header onto an agent or a human in the recipient's workspace only when that+verdict is `aligned` and the envelope mailbox is the same address.+Otherwise the author is `external:<addr>`. The HMAC on+`/webhooks/email/inbound` authenticates the worker to the server. Details+are in [`docs/email.md`](docs/email.md).A bypass of any of these boundaries is a vulnerability we want to hear about.diff --git a/docs/API.md b/docs/API.mdindex e8526c1..8392f05 100644--- a/docs/API.md+++ b/docs/API.md@@ -20,8 +20,10 @@ JSON body. It is mounted beside `/api`, not under it.`POST /webhooks/email/inbound` does not use either of those. It checks`x-cumora-signature` against `EMAIL_INBOUND_HMAC_SECRET`. The signature-proves the worker sent the body. It does not prove who the `From:` header is.-See [email.md](email.md).+proves the worker sent the body. The worker's `authVerdict` and+`envelopeFrom` are what prove the `From:` header. The server attributes the+message to a workspace member only when the verdict is `aligned` and the+envelope mailbox matches. See [email.md](email.md).## Errors, pagination, idempotencydiff --git a/docs/email.md b/docs/email.mdindex 1a15cb9..5acf518 100644--- a/docs/email.md+++ b/docs/email.md@@ -46,19 +46,35 @@ send / reply / start a thread.## Trust model-**Inbound mail is not authenticated.** `workers/email-gate` accepts any-message whose recipient domain is in `EMAIL_ROOT_DOMAINS`. It does not read-`Authentication-Results` and performs no SPF, DKIM, or DMARC check. The-server then maps the `From:` header — which the sender sets — to an agent-in the recipient's company, then to a human member of that company, and-otherwise to a synthetic external author (`resolveSender` in-`server/src/api/inbound-email.ts`). A spoofed `From:` therefore produces a-message that renders as that participant and enters the agent's context as-theirs. The HMAC on `/webhooks/email/inbound` authenticates the worker to-the server. It says nothing about the sender.+`workers/email-gate` still accepts any message whose recipient domain is in+`EMAIL_ROOT_DOMAINS`. Who the message is **from** is a separate check.++The worker reads `Authentication-Results` from the Email Routing message+headers, not from the MIME the sender wrote. It trusts a record only when+exactly one of them names the authserv-id `mx.cloudflare.net`. A result word+counts as pass only when it is exactly `pass`. The verdict is `aligned` when+that record's DMARC results are all `pass`, or, when the record has no DMARC+method, when both SPF and DKIM are `pass`. Any other header, a second record+that claims the same authserv-id, or a missing header is `unaligned`.++The signed JSON includes `authVerdict` and `envelopeFrom` (the SMTP+`MAIL FROM`). The server maps the header `From:` onto an agent or a human+member of the recipient's company only when `authVerdict` is exactly+`aligned` and that address is the same mailbox as `envelopeFrom`+(`inboundSenderAuthenticated` in `server/src/api/inbound-email.ts`).+Otherwise the author is the synthetic `external:<addr>`, which renders as an+external sender. The message is still delivered, and the recipient agent+still wakes.++A payload with no `authVerdict` is unaligned. Deploy the worker+(`npx wrangler deploy` in `workers/email-gate`) with the server, or member+replies stay external until that deploy.++The HMAC on `/webhooks/email/inbound` authenticates the worker to the+server. It does not authenticate the sender. The verdict above does.The SPF and DKIM records in the setup section below are for **outbound**-mail through Resend. They do not validate inbound `From:` headers.+mail through Resend."Tenant isolation is enforced in the recipient resolver, not in DNS" meanswhich workspace receives the message. It does not mean the sender wasdiff --git a/server/src/__integration__/inbound.test.ts b/server/src/__integration__/inbound.test.tsindex a4e8975..528333a 100644--- a/server/src/__integration__/inbound.test.ts+++ b/server/src/__integration__/inbound.test.ts@@ -18,7 +18,7 @@ import { randomUUID } from 'node:crypto'import { createServer, type Server } from 'node:http'import {buildTestApp, ensureSchemaOnce, resetAllTables, seedCompanyWithAgent,- signInboundPayload, teardownAll,+ seedUserMembership, signInboundPayload, teardownAll,} from './_helpers.js'import { pool } from '../db/pool.js'@@ -180,6 +180,83 @@ test('[integration] dedups a re-delivered Message-ID', async () => {assert.equal(rows[0].n, 1, 'second delivery must not create a second email_messages row')})+test('[integration] an unauthenticated From is not attributed to a workspace member or agent', async () => {+ const { companyId, agentId, agentEmail } = await seedCompanyWithAgent()+ const userId = `u-${randomUUID().slice(0, 8)}`+ await seedUserMembership(userId, companyId, { email: '[email protected]', displayName: 'CEO' })++ const spoofedMember = await postInbound({+ messageId: 'spoof-member@host',+ from: 'CEO <[email protected]>',+ to: [agentEmail],+ subject: 'wire the money',+ text: 'body',+ })+ assert.equal(spoofedMember.status, 200)+ assert.equal(await inboundAuthor('spoof-member@host'), 'external:[email protected]')++ const spoofedAgent = await postInbound({+ messageId: 'spoof-agent@host',+ from: agentEmail,+ envelopeFrom: agentEmail,+ authVerdict: 'unaligned',+ to: [agentEmail],+ subject: 'from myself',+ text: 'body',+ })+ assert.equal(spoofedAgent.status, 200)+ assert.equal(await inboundAuthor('spoof-agent@host'), `external:${agentEmail}`)+ assert.notEqual(await inboundAuthor('spoof-agent@host'), agentId)++ const mismatchedEnvelope = await postInbound({+ messageId: 'mismatch@host',+ from: 'CEO <[email protected]>',+ envelopeFrom: '[email protected]',+ authVerdict: 'aligned',+ to: [agentEmail],+ subject: 'still not me',+ text: 'body',+ })+ assert.equal(mismatchedEnvelope.status, 200)+ assert.equal(await inboundAuthor('mismatch@host'), 'external:[email protected]')++ const realMember = await postInbound({+ messageId: 'real-member@host',+ from: 'CEO <[email protected]>',+ envelopeFrom: '[email protected]',+ authVerdict: 'aligned',+ to: [agentEmail],+ subject: 'real reply',+ text: 'body',+ })+ assert.equal(realMember.status, 200)+ assert.equal(await inboundAuthor('real-member@host'), userId)++ const realAgent = await postInbound({+ messageId: 'real-agent@host',+ from: `Agent <${agentEmail}>`,+ envelopeFrom: agentEmail,+ authVerdict: 'aligned',+ to: [agentEmail],+ subject: 'real agent',+ text: 'body',+ })+ assert.equal(realAgent.status, 200)+ assert.equal(await inboundAuthor('real-agent@host'), agentId)+})++async function inboundAuthor(smtpMessageId: string): Promise<string> {+ const { rows } = await pool.query<{ author_id: string }>(+ `SELECT m.author_id+ FROM messages m+ JOIN email_messages em ON em.message_id = m.id+ WHERE em.smtp_message_id = $1`,+ [smtpMessageId],+ )+ assert.equal(rows.length, 1)+ return rows[0].author_id+}+test('[integration] flags inbound auto_submitted when worker forwarded the header', async () => {const { agentEmail } = await seedCompanyWithAgent()const r = await postInbound({diff --git a/server/src/__tests__/inbound-sender-auth.test.ts b/server/src/__tests__/inbound-sender-auth.test.tsnew file mode 100644index 0000000..040d34d--- /dev/null+++ b/server/src/__tests__/inbound-sender-auth.test.ts@@ -0,0 +1,58 @@+/**+ * Pure gate in front of resolveSender. A spoofed From used to become the+ * workspace member with that address. Internal attribution now requires the+ * gate's aligned verdict and an envelope sender that is the same mailbox.+ */+import assert from 'node:assert/strict'+import { test } from 'node:test'++process.env.CUMORA_RUNTIME_CLIENT = 'http'+process.env.OPENAI_API_KEY ??= 'test-key'++const { inboundSenderAuthenticated } = await import('../api/inbound-email.js')++test('a missing or non-aligned verdict never maps onto an internal author', () => {+ assert.equal(inboundSenderAuthenticated({+ authVerdict: undefined,+ envelopeFrom: '[email protected]',+ headerFrom: 'CEO <[email protected]>',+ }), false)+ assert.equal(inboundSenderAuthenticated({+ authVerdict: 'unaligned',+ envelopeFrom: '[email protected]',+ headerFrom: '[email protected]',+ }), false)+ assert.equal(inboundSenderAuthenticated({+ authVerdict: 'aligned ',+ envelopeFrom: '[email protected]',+ headerFrom: '[email protected]',+ }), false)+ assert.equal(inboundSenderAuthenticated({+ authVerdict: 'aligned',+ envelopeFrom: undefined,+ headerFrom: '[email protected]',+ }), false)+})++test('an aligned verdict maps only when the envelope mailbox is the header From', () => {+ assert.equal(inboundSenderAuthenticated({+ authVerdict: 'aligned',+ envelopeFrom: '[email protected]',+ headerFrom: 'CEO <[email protected]>',+ }), true)+ assert.equal(inboundSenderAuthenticated({+ authVerdict: 'aligned',+ envelopeFrom: 'CEO <[email protected]>',+ headerFrom: '[email protected]',+ }), true)+ assert.equal(inboundSenderAuthenticated({+ authVerdict: 'aligned',+ envelopeFrom: '[email protected]',+ headerFrom: 'CEO <[email protected]>',+ }), false)+ assert.equal(inboundSenderAuthenticated({+ authVerdict: 'aligned',+ envelopeFrom: 'not-an-address',+ headerFrom: '[email protected]',+ }), false)+})diff --git a/server/src/api/inbound-email.ts b/server/src/api/inbound-email.tsindex 6a830f2..71a92ca 100644--- a/server/src/api/inbound-email.ts+++ b/server/src/api/inbound-email.ts@@ -9,9 +9,10 @@* 2. Parses recipients → resolves each to an in-tenant agent. Fans out* the same delivery to every recognized recipient (so a To: with two* agents creates messages in two threads, one per recipient).- * 3. Resolves the sender — known agent, known human (by users.email),- * else synthetic `external:<addr>` so the conversation has someone- * to be "from".+ * 3. Resolves the sender. A known agent or a known human (by users.email)+ * is used only when the gate reported authVerdict "aligned" and the+ * header From is the same mailbox as the SMTP envelope sender.+ * Otherwise the author is synthetic `external:<addr>`.* 4. Threading: in-reply-to / references → existing email_messages row* → existing conversation; else new one with subject as title.* 5. Persists messages + email_messages rows via the shared write path@@ -118,6 +119,13 @@ interface InboundPayload {/** Lowercased Auto-Submitted header value, or null when absent / "no".* Heartbeat uses this to skip auto-replying to automation. */autoSubmitted?: string | null+ /** Set by the email gate from Cloudflare's Authentication-Results.+ * Missing, or any value other than the exact string "aligned", means+ * the header From is not an internal author. */+ authVerdict?: unknown+ /** SMTP MAIL FROM observed by the gate. Internal attribution also+ * requires this mailbox to equal the header From. */+ envelopeFrom?: unknown/** Optional attachment list forwarded from the worker. Each entry's* contentBase64 is the raw bytes; truncated=true means the worker* refused to forward the body (oversize) and we should record metadata@@ -231,20 +239,46 @@ interface ResolvedSender {displayName: string | null}+/**+ * Internal attribution requires both halves. `aligned` means the gate saw+ * exactly one Cloudflare Authentication-Results record that passed. The+ * address comparison means that record belongs to this mailbox, not merely+ * to some other sender at the same domain. Anything else — a missing field+ * from a gate that has not been redeployed, a forged header, a bounce+ * address — stays on the external author path.+ */+export function inboundSenderAuthenticated(args: {+ authVerdict: unknown+ envelopeFrom: unknown+ headerFrom: string+}): boolean {+ if (args.authVerdict !== 'aligned') return false+ if (typeof args.envelopeFrom !== 'string') return false+ const header = parseAddress(args.headerFrom)+ const envelope = parseAddress(args.envelopeFrom)+ if (!header || !envelope) return false+ return header.addr === envelope.addr+}+/** Resolve "From:" to a participant in the recipient's company.- * Hierarchy: known agent → known human user → synthetic external. */+ * Hierarchy, and only when `allowInternal`: known agent → known human+ * user → synthetic external. Unauthenticated mail skips the first two+ * lookups so a spoofed From cannot wear a member's identity. */async function resolveSender(args: {fromAddr: stringfromName: string | nullcompanyId: string+ allowInternal: boolean}): Promise<ResolvedSender> {- // Same-tenant agent is the most common cross-agent case.- const agent = await findParticipantByAddress(args.fromAddr, args.companyId)- if (agent) return { participantId: agent.id, displayName: agent.name }- // A human in this workspace replied from their real email (e.g. yetone- // hits "reply" in Gmail to a thread an agent started).- const user = await findUserInCompanyByAuthEmail(args.fromAddr, args.companyId)- if (user) return { participantId: user.id, displayName: user.displayName }+ if (args.allowInternal) {+ // Same-tenant agent is the most common cross-agent case.+ const agent = await findParticipantByAddress(args.fromAddr, args.companyId)+ if (agent) return { participantId: agent.id, displayName: agent.name }+ // A human in this workspace replied from their real email (e.g. yetone+ // hits "reply" in Gmail to a thread an agent started).+ const user = await findUserInCompanyByAuthEmail(args.fromAddr, args.companyId)+ if (user) return { participantId: user.id, displayName: user.displayName }+ }// Stranger / external collaborator. Synthetic id keeps the foreign-key// shape happy without us inventing a participants row for every random// address that might never email us again. The "external:" prefix is@@ -471,6 +505,11 @@ inboundEmailRouter.post('/inbound', async (req: Request, res: Response) => {fromAddr: fromParsed.addr,fromName: fromParsed.name,companyId,+ allowInternal: inboundSenderAuthenticated({+ authVerdict: payload.authVerdict,+ envelopeFrom: payload.envelopeFrom,+ headerFrom: payload.from,+ }),})const allRecipientParticipantIds = companyRecipients.map((r) => r.participantId)const memberIds = Array.from(new Set([sender.participantId, ...allRecipientParticipantIds]))diff --git a/workers/email-gate/README.md b/workers/email-gate/README.mdindex 14f2b54..fd00434 100644--- a/workers/email-gate/README.md+++ b/workers/email-gate/README.md@@ -12,7 +12,7 @@ The worker:2. Reads the raw RFC 5322 message and parses it with `postal-mime`.3. Builds a JSON payload (message-id, in-reply-to, references, from, to, cc, subject, text, html, raw size, `autoSubmitted` per RFC 3834, and `attachments[]` as base64 — capped at 10 MB per attachment and 18 MB in total).4. HMAC-signs the payload with `EMAIL_INBOUND_HMAC_SECRET` and POSTs to `CUMORA_INBOUND_URL`.-5. Translates the server's response into accept or reject. A 404, and other 4xx responses, are permanent (`message.setReject`). A network error or a 5xx response throws so Cloudflare Email Routing returns a temporary failure and the sender's MTA can retry. The domain allowlist is the worker's only check on who sent the mail; it does not read `Authentication-Results`.+5. Translates the server's response into accept or reject. A 404, and other 4xx responses, are permanent (`message.setReject`). A network error or a 5xx response throws so Cloudflare Email Routing returns a temporary failure and the sender's MTA can retry. The domain allowlist decides which recipients are ours. Sender authentication is separate: the payload's `authVerdict` is derived from Cloudflare's `Authentication-Results` header (authserv-id `mx.cloudflare.net` only), and `envelopeFrom` is the SMTP `MAIL FROM`. The server maps `From:` onto a workspace member only when that verdict is `aligned` and the two addresses are the same mailbox.Outbound mail goes through Resend on the server side, **not** this worker — Cloudflare Email Workers can't send mail.diff --git a/workers/email-gate/src/auth-verdict.ts b/workers/email-gate/src/auth-verdict.tsnew file mode 100644index 0000000..720969a--- /dev/null+++ b/workers/email-gate/src/auth-verdict.ts@@ -0,0 +1,143 @@+/**+ * Decide whether Cloudflare Email Routing authenticated the sender.+ *+ * The sender can put `Authentication-Results` in the message they transmit.+ * Cloudflare prepends its own, with authserv-id `mx.cloudflare.net`, and a+ * forger can claim that same id. This trusts the header only when exactly+ * one record carries that id. Zero means nothing authenticated the message.+ * Two means we cannot tell Cloudflare's record from a copy, so the message+ * stays unaligned.+ *+ * A method counts as pass only when its result word is exactly `pass`.+ * `passfail`, `pass-not-really`, and `pass/fail` do not. `dmarc=pass` inside+ * a comment does not either. Any DMARC result other than pass, including+ * `fail` and `none`, stays unaligned. SPF and DKIM are consulted only when+ * the record has no DMARC method at all, and then both must be pass.+ */+export const CLOUDFLARE_AUTHSERV_ID = 'mx.cloudflare.net'++export type InboundAuthVerdict = 'aligned' | 'unaligned'++interface AuthRecord {+ id: string+ methods: Map<string, string[]>+}++type HeaderSource = Headers | Array<{ key: string; value: string }> | undefined | null++export function deriveAuthVerdict(headers: HeaderSource): InboundAuthVerdict {+ const trusted = trustedRecords(headers)+ if (trusted.length !== 1) return 'unaligned'+ return recordAligned(trusted[0]) ? 'aligned' : 'unaligned'+}++function trustedRecords(headers: HeaderSource): AuthRecord[] {+ const records: AuthRecord[] = []+ for (const value of headerValues(headers, 'authentication-results')) {+ for (const part of splitRecords(normalizeAuthHeader(value))) {+ const record = parseRecord(part)+ if (record) records.push(record)+ }+ }+ return records.filter((record) => record.id === CLOUDFLARE_AUTHSERV_ID)+}++function headerValues(headers: HeaderSource, name: string): string[] {+ if (!headers) return []+ const want = name.toLowerCase()+ if (Array.isArray(headers)) {+ return headers.filter((header) => header.key.toLowerCase() === want).map((header) => header.value)+ }+ const values: string[] = []+ headers.forEach((value, key) => {+ if (key.toLowerCase() === want) values.push(value)+ })+ return values+}++/** Drop RFC 5322 comments so a parenthetical `dmarc=pass` cannot satisfy the check. */+function stripComments(input: string): string {+ let out = ''+ let quote = false+ let depth = 0+ let escaped = false+ for (const ch of input) {+ if (escaped) {+ if (depth === 0) out += ch+ escaped = false+ continue+ }+ if (ch === '\\') {+ escaped = true+ if (depth === 0 && quote) out += ch+ continue+ }+ if (quote) {+ if (ch === '"') quote = false+ if (depth === 0) out += ch+ continue+ }+ if (ch === '"') {+ quote = true+ if (depth === 0) out += ch+ continue+ }+ if (ch === '(') {+ depth += 1+ continue+ }+ if (ch === ')' && depth > 0) {+ depth -= 1+ continue+ }+ if (depth === 0) out += ch+ }+ return out+}++function normalizeAuthHeader(value: string): string {+ return stripComments(value).replace(/[\r\n\t ]+/g, ' ').trim()+}++/**+ * A Fetch `Headers` object joins repeated fields with ", ". A new+ * Authentication-Results record then looks like ", mx.cloudflare.net;".+ * Require a dot in that id so a comma inside a property value does not split+ * the record.+ */+function splitRecords(normalized: string): string[] {+ if (!normalized) return []+ return normalized+ .split(/,\s*(?=[A-Za-z0-9.-]*\.[A-Za-z0-9.-]+\s*(?:\d+\s*)?;)/)+ .map((part) => part.trim())+ .filter(Boolean)+}++function parseRecord(value: string): AuthRecord | null {+ const parts = value.split(';').map((part) => part.trim()).filter(Boolean)+ if (parts.length === 0) return null+ const idMatch = /^([A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?)\.?(?:\s+\d+)?$/.exec(parts[0])+ if (!idMatch) return null+ const methods = new Map<string, string[]>()+ for (const part of parts.slice(1)) {+ const method = /^([A-Za-z0-9]+)\s*=\s*(\S+)/.exec(part)+ if (!method) continue+ const name = method[1].toLowerCase()+ const result = method[2].replace(/[;,]+$/, '').toLowerCase()+ const existing = methods.get(name)+ if (existing) existing.push(result)+ else methods.set(name, [result])+ }+ return { id: idMatch[1].toLowerCase(), methods }+}++/** Every result word is exactly `pass`. An empty list, or any other word, is not. */+function exactlyPass(results: string[] | undefined): boolean {+ return !!results && results.length > 0 && results.every((result) => result === 'pass')+}++function recordAligned(record: AuthRecord): boolean {+ const dmarc = record.methods.get('dmarc') ?? []+ if (dmarc.length > 0) return exactlyPass(dmarc)+ return exactlyPass(record.methods.get('spf')) && exactlyPass(record.methods.get('dkim'))+}diff --git a/workers/email-gate/src/index.test.ts b/workers/email-gate/src/index.test.tsindex 47165e6..157525f 100644--- a/workers/email-gate/src/index.test.ts+++ b/workers/email-gate/src/index.test.ts@@ -23,6 +23,7 @@ import worker, {MAX_ATTACHMENT_BYTES,MAX_TOTAL_ATTACHMENT_BYTES,} from './index.js'+import { deriveAuthVerdict } from './auth-verdict.js'/* ============================ recipientAccepted ============================ */@@ -127,6 +128,69 @@ test('getHeader returns first match', () => {assert.equal(getHeader(headers, 'X-Foo'), 'first')})+/* ============================== deriveAuthVerdict ========================= */++const cf = (value: string) => [{ key: 'Authentication-Results', value: `mx.cloudflare.net; ${value}` }]++test('authVerdict is derived from Cloudflare Authentication-Results', () => {+ assert.equal(deriveAuthVerdict(cf('dmarc=pass; spf=pass')), 'aligned')+ assert.equal(deriveAuthVerdict(cf('spf=pass; dkim=pass')), 'aligned')+ assert.equal(+ deriveAuthVerdict(cf('spf=pass; dkim=fail')),+ 'unaligned',+ 'SPF pass alone does not authenticate the header From',+ )+ assert.equal(+ deriveAuthVerdict([{ key: 'Authentication-Results', value: 'mx.cloudflare.net; dmarc=pass-not-really' }]),+ 'unaligned',+ 'a longer token that starts with "pass" is not a pass',+ )+ assert.equal(deriveAuthVerdict(cf('dmarc=passfail')), 'unaligned')+ assert.equal(deriveAuthVerdict(cf('dmarc=pass/fail')), 'unaligned')+})++test('authVerdict ignores a pass that only appears inside a comment', () => {+ assert.equal(deriveAuthVerdict(cf('spf=fail (dmarc=pass)')), 'unaligned')+})++test('authVerdict ignores a sender-forged Authentication-Results authserv-id', () => {+ assert.equal(+ deriveAuthVerdict([{ key: 'Authentication-Results', value: 'attacker.example; dmarc=pass' }]),+ 'unaligned',+ )+ assert.equal(deriveAuthVerdict(cf('xdmarc=pass')), 'unaligned')+ assert.equal(deriveAuthVerdict(undefined), 'unaligned')+})++test('authVerdict fails closed when two records claim Cloudflare', () => {+ assert.equal(deriveAuthVerdict([+ { key: 'Authentication-Results', value: 'mx.cloudflare.net; dmarc=pass' },+ { key: 'Authentication-Results', value: 'mx.cloudflare.net; dmarc=fail' },+ ]), 'unaligned')+ // Fetch Headers joins repeated fields with ", " before the worker sees them.+ const headers = new Headers()+ headers.append('authentication-results', 'mx.cloudflare.net; dmarc=pass')+ headers.append('authentication-results', 'mx.cloudflare.net; dmarc=fail')+ assert.equal(deriveAuthVerdict(headers), 'unaligned')+})++test('authVerdict uses the single Cloudflare record and ignores a forged one', () => {+ assert.equal(deriveAuthVerdict([+ { key: 'Authentication-Results', value: 'attacker.example; dmarc=pass' },+ { key: 'Authentication-Results', value: 'mx.cloudflare.net; dmarc=fail header.from=victim.test' },+ ]), 'unaligned')+ assert.equal(deriveAuthVerdict([+ { key: 'Authentication-Results', value: 'attacker.example; dmarc=fail' },+ { key: 'Authentication-Results', value: 'mx.cloudflare.net;\r\n\tdmarc=pass (p=REJECT) header.from=victim.test' },+ ]), 'aligned')+})++test('authVerdict treats any DMARC result other than pass as unaligned', () => {+ assert.equal(deriveAuthVerdict(cf('spf=pass; dkim=pass; dmarc=fail')), 'unaligned')+ assert.equal(deriveAuthVerdict(cf('spf=pass; dkim=pass; dmarc=none')), 'unaligned')+ assert.equal(deriveAuthVerdict(cf('DMARC=Pass')), 'aligned')+})+/* ============================== attachment caps =========================== */test('attachment byte limits are sensibly ordered', () => {@@ -233,6 +297,8 @@ test('email handler forwards the envelope recipient it admitted the message on',(posted as { envelopeTo?: string }).envelopeTo, '[email protected]','the address the handler admitted this message on was not forwarded — a Bcc\'d agent resolves to nobody and gets a 550',)+ assert.equal((posted as { authVerdict?: string }).authVerdict, 'unaligned')+ assert.equal((posted as { envelopeFrom?: string }).envelopeFrom, '[email protected]')// The visible header is still reported as-is; envelopeTo is additive.assert.deepEqual((posted as { to?: string[] }).to, ['[email protected]'])})@@ -331,6 +397,49 @@ test('synthesizeMessageId produces a shape the server will accept', async () =>assert.doesNotMatch(id, /[<>\s]/)})+test('email handler forwards an aligned verdict from Cloudflare headers', async () => {+ const rejected: string[] = []+ const message = {+ to: '[email protected]',+ from: '[email protected]',+ headers: new Headers({+ 'authentication-results': 'mx.cloudflare.net; dmarc=pass header.from=example.com',+ }),+ raw: new Response(+ 'From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\nMessage-ID: <[email protected]>\r\nAuthentication-Results: attacker.example; dmarc=fail\r\n\r\nHello',+ ).body!,+ setReject: (reason: string) => { rejected.push(reason) },+ } as unknown as Parameters<typeof worker.email>[0]++ let posted: { authVerdict?: string; envelopeFrom?: string } | null = null+ const originalFetch = globalThis.fetch+ globalThis.fetch = async (_url, init) => {+ posted = JSON.parse(String((init as RequestInit).body))+ return new Response('ok', { status: 200 })+ }+ try {+ await worker.email(message, fakeEnv, fakeCtx)+ } finally {+ globalThis.fetch = originalFetch+ }++ assert.deepEqual(rejected, [])+ assert.equal(posted?.authVerdict, 'aligned')+ assert.equal(posted?.envelopeFrom, '[email protected]')+})++test('the email handler derives authVerdict instead of forwarding the raw header', async () => {+ const source = await readFile(new URL('./index.ts', import.meta.url), 'utf8')+ const handler = source.slice(source.indexOf('export default {'))+ assert.match(handler, /deriveAuthVerdict\(message\.headers\)/)+ assert.match(handler, /envelopeFrom:\s*message\.from/)+ assert.doesNotMatch(+ handler,+ /dmarc=pass/,+ 'the handler must not match the Authentication-Results text itself',+ )+})+test('the email handler synthesizes its id instead of drawing a random one', async () => {// Every test above passes just as well against a handler that went back to// `randomUUID()` — they exercise the helper, not the call site. Read thediff --git a/workers/email-gate/src/index.ts b/workers/email-gate/src/index.tsindex 3a002ef..0fa1f4e 100644--- a/workers/email-gate/src/index.ts+++ b/workers/email-gate/src/index.ts@@ -5,8 +5,11 @@* 1. Reject (550) if the recipient domain isn't in EMAIL_ROOT_DOMAINS.* 2. Stream the raw MIME, parse with postal-mime.* 3. Build a JSON payload (message-id, in-reply-to, references, from,- * to, cc, subject, text, html, raw size, autoSubmitted, and- * attachments[] as base64 — see MAX_ATTACHMENT_BYTES / the total cap).+ * to, cc, subject, text, html, raw size, autoSubmitted,+ * authVerdict, envelopeFrom, and attachments[] as base64 — see+ * MAX_ATTACHMENT_BYTES / the total cap). authVerdict comes from+ * Cloudflare's Authentication-Results header, not from the sender's+ * copy of that header. See auth-verdict.ts.* 4. Sign with HMAC-SHA256(EMAIL_INBOUND_HMAC_SECRET, body) and POST* to CUMORA_INBOUND_URL.* 5. Reject (550) if the server says "no recipient resolved" so the@@ -16,6 +19,7 @@* goes through Resend on the server side.*/import PostalMime from 'postal-mime'+import { deriveAuthVerdict, type InboundAuthVerdict } from './auth-verdict.js'interface Env {EMAIL_INBOUND_HMAC_SECRET: string@@ -56,6 +60,12 @@ interface InboundPayload {* server can flag the row + refuse heartbeat auto-reply on it. null* when the header was absent or set to "no". */autoSubmitted: string | null+ /** `aligned` only when Cloudflare's own Authentication-Results record+ * authenticated this message. The server will not map `from` onto a+ * workspace member for any other value. */+ authVerdict: InboundAuthVerdict+ /** SMTP MAIL FROM, as Email Routing reported it in `message.from`. */+ envelopeFrom: stringattachments: InboundAttachment[]}@@ -252,6 +262,8 @@ export default {html: parsed.html ?? null,rawSizeBytes: rawBytes.byteLength,autoSubmitted,+ authVerdict: deriveAuthVerdict(message.headers),+ envelopeFrom: message.from,attachments,}if (payload.to.length === 0) payload.to = [message.to]