Skip to content

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-gate): throw on upstream 5xx and network errors for SMTP 4xx tempfail (#216)

cicada525afe82bc28
diff --git a/workers/email-gate/src/index.test.ts b/workers/email-gate/src/index.test.ts
index 3e37919..a909c4f 100644
--- a/workers/email-gate/src/index.test.ts
+++ b/workers/email-gate/src/index.test.ts
@@ -12,7 +12,7 @@
*/
import { test } from 'node:test'
import assert from 'node:assert/strict'
-import {
+import worker, {
recipientAccepted,
readArrayHeader,
toBase64,
@@ -133,3 +133,99 @@ test('attachment byte limits are sensibly ordered', () => {
assert.ok(MAX_ATTACHMENT_BYTES < MAX_TOTAL_ATTACHMENT_BYTES)
assert.ok(MAX_TOTAL_ATTACHMENT_BYTES * 1.34 < 25 * 1024 * 1024)
})
+
+/* ==================== email() handler error handling ======================= */
+
+function createFakeMessage() {
+ const rejected: string[] = []
+ const rawStream = new Response(
+ 'From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\nMessage-ID: <[email protected]>\r\n\r\nHello',
+ ).body!
+ const message = {
+ raw: rawStream,
+ setReject: (reason: string) => { rejected.push(reason) },
+ } as unknown as Parameters<typeof worker.email>[0]
+ return { message, rejected }
+}
+
+const fakeEnv = {
+ EMAIL_ROOT_DOMAINS: 'cumora.ai',
+ EMAIL_INBOUND_HMAC_SECRET: 'test-secret-value-12345',
+ CUMORA_INBOUND_URL: 'http://upstream.local/inbound',
+} as unknown as Parameters<typeof worker.email>[1]
+
+const fakeCtx = {
+ waitUntil: (promise: Promise<unknown>) => { void promise.catch(() => {}) },
+ passThroughOnException: () => {},
+} as unknown as Parameters<typeof worker.email>[2]
+
+test('email handler throws on upstream network error (triggering SMTP tempfail)', async () => {
+ const { message, rejected } = createFakeMessage()
+ const originalFetch = globalThis.fetch
+ globalThis.fetch = async () => {
+ throw new Error('connection reset by peer')
+ }
+ try {
+ await assert.rejects(
+ () => worker.email(message, fakeEnv, fakeCtx),
+ /Upstream unreachable: connection reset by peer/,
+ )
+ assert.deepEqual(rejected, [], 'setReject must NOT be called on transient network error')
+ } finally {
+ globalThis.fetch = originalFetch
+ }
+})
+
+test('email handler throws on upstream 5xx error (triggering SMTP tempfail)', async () => {
+ const { message, rejected } = createFakeMessage()
+ const originalFetch = globalThis.fetch
+ globalThis.fetch = async () => new Response('Internal Server Error', { status: 502 })
+ try {
+ await assert.rejects(
+ () => worker.email(message, fakeEnv, fakeCtx),
+ /Upstream temporary failure \(502\)/,
+ )
+ assert.deepEqual(rejected, [], 'setReject must NOT be called on 5xx error')
+ } finally {
+ globalThis.fetch = originalFetch
+ }
+})
+
+test('email handler rejects with 550 bounce on 404 no recipient', async () => {
+ const { message, rejected } = createFakeMessage()
+ const originalFetch = globalThis.fetch
+ globalThis.fetch = async () => new Response('Not Found', { status: 404 })
+ try {
+ await worker.email(message, fakeEnv, fakeCtx)
+ assert.deepEqual(rejected, ['No such recipient'])
+ } finally {
+ globalThis.fetch = originalFetch
+ }
+})
+
+test('email handler rejects with 550 bounce on 4xx client errors', async () => {
+ const { message, rejected } = createFakeMessage()
+ const originalFetch = globalThis.fetch
+ globalThis.fetch = async () => new Response('Bad Request', { status: 400 })
+ try {
+ await worker.email(message, fakeEnv, fakeCtx)
+ assert.deepEqual(rejected, ['Upstream 400'])
+ } finally {
+ globalThis.fetch = originalFetch
+ }
+})
+
+test('email handler accepts email on 200 response without setReject', async () => {
+ const { message, rejected } = createFakeMessage()
+ const originalFetch = globalThis.fetch
+ globalThis.fetch = async () => new Response('OK', { status: 200 })
+ try {
+ await worker.email(message, fakeEnv, fakeCtx)
+ assert.deepEqual(rejected, [])
+ } finally {
+ globalThis.fetch = originalFetch
+ }
+})
+
diff --git a/workers/email-gate/src/index.ts b/workers/email-gate/src/index.ts
index ee102da..d01b6c0 100644
--- a/workers/email-gate/src/index.ts
+++ b/workers/email-gate/src/index.ts
@@ -226,27 +226,27 @@ export default {
body,
})
} catch (e) {
- message.setReject('Upstream unreachable')
console.error('[email-gate] POST failed:', e instanceof Error ? e.message : String(e))
- return
+ // Transient network or connection error — throw to signal a temporary failure
+ // (SMTP 4xx tempfail) in Cloudflare Email Routing so the sending MTA retries delivery later.
+ throw new Error(`Upstream unreachable: ${e instanceof Error ? e.message : String(e)}`)
}
if (res.status === 404) {
- // Server says no agent matches this recipient — bounce.
+ // Server says no agent matches this recipient — permanent rejection (SMTP 550 bounce).
message.setReject('No such recipient')
return
}
+ if (res.status >= 500) {
+ // 5xx upstream failure (server restarting, deploy in progress, database blip).
+ // Cloudflare Email Routing signals a temporary SMTP failure (4xx tempfail) when the
+ // handler throws, allowing sending MTAs (Gmail, Outlook, etc.) to retry delivery later.
+ const errorText = await res.text().catch(() => '')
+ console.error(`[email-gate] upstream ${res.status}: ${errorText.slice(0, 400)}`)
+ throw new Error(`Upstream temporary failure (${res.status}): ${errorText.slice(0, 200)}`)
+ }
if (!res.ok) {
- // 4xx other than 404, or 5xx.
- //
- // KNOWN GAP: this *should* tempfail on 5xx so the sender's MTA retries,
- // but setReject() is a PERMANENT rejection — a single upstream blip
- // loses the mail for good. Cloudflare issues a temporary failure when
- // the handler throws, so the fix is to throw here on 5xx and keep
- // setReject for 4xx. Not changed yet because it flips real delivery
- // behaviour and wants its own test + rollout.
- //
- // Reading the body keeps the response from leaking; ctx.waitUntil so
- // we don't block the email return.
+ // 4xx other than 404 (e.g. 400 bad request, 401 unauthorized HMAC, 413 payload too large).
+ // Permanent client rejection — retrying will not change the outcome.
ctx.waitUntil(res.text().then((t) => console.error(`[email-gate] upstream ${res.status}: ${t.slice(0, 400)}`)))
message.setReject(`Upstream ${res.status}`)
return