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): derive the fallback Message-Id instead of drawing one

zhuangxialiee4cfd929ecfd
diff --git a/workers/email-gate/src/index.test.ts b/workers/email-gate/src/index.test.ts
index a909c4f..78da270 100644
--- a/workers/email-gate/src/index.test.ts
+++ b/workers/email-gate/src/index.test.ts
@@ -11,9 +11,12 @@
* Run: npm test (from repo root)
*/
import { test } from 'node:test'
+import { readFile } from 'node:fs/promises'
import assert from 'node:assert/strict'
import worker, {
recipientAccepted,
+ synthesizeMessageId,
+ SYNTH_ID_BUCKET_MS,
readArrayHeader,
toBase64,
getHeader,
@@ -229,3 +232,74 @@ test('email handler accepts email on 200 response without setReject', async () =
}
})
+
+/* ========================= synthesizeMessageId ========================= */
+//
+// A message with no `Message-Id:` gets one fabricated here. It has to be
+// DERIVED, not random: the worker throws on an upstream 5xx or a network
+// failure so the sending MTA tempfails and retries, and that retry runs this
+// worker again on the same physical message. The server dedups on
+// smtp_message_id, so a random id per attempt is a fresh delivery per attempt.
+
+const sameMessage = {
+ envelopeFrom: '[email protected]',
+ envelopeTo: '[email protected]',
+ date: 'Mon, 08 Sep 2026 09:14:02 +0000',
+ subject: 'disk 91% on db-2',
+ body: 'threshold crossed at 09:14',
+}
+
+test('synthesizeMessageId is stable across a retry of the same message', async () => {
+ // The retry arrives as a new SMTP transaction with its own Received: headers,
+ // so only the parsed fields can be hashed — and they must give the same id.
+ assert.equal(await synthesizeMessageId(sameMessage), await synthesizeMessageId({ ...sameMessage }))
+})
+
+test('synthesizeMessageId separates two genuinely different messages', async () => {
+ const base = await synthesizeMessageId(sameMessage)
+ for (const variant of [
+ { ...sameMessage, envelopeFrom: '[email protected]' },
+ { ...sameMessage, envelopeTo: '[email protected]' },
+ { ...sameMessage, date: 'Mon, 08 Sep 2026 09:15:02 +0000' },
+ { ...sameMessage, subject: 'disk 92% on db-2' },
+ { ...sameMessage, body: 'threshold crossed at 09:15' },
+ ]) {
+ assert.notEqual(await synthesizeMessageId(variant), base)
+ }
+})
+
+test('synthesizeMessageId cannot have a field boundary forged by content', async () => {
+ // Fields are NUL-joined, so moving text across a boundary must change the id.
+ assert.notEqual(
+ await synthesizeMessageId({ ...sameMessage, subject: 'a', body: 'bc' }),
+ await synthesizeMessageId({ ...sameMessage, subject: 'ab', body: 'c' }),
+ )
+})
+
+test('synthesizeMessageId falls back to a coarse bucket when Date is missing', async () => {
+ // A sender that omitted Message-Id may have omitted Date too. Within one
+ // bucket a retry still dedups; that is the original intent of this fallback.
+ const undated = { ...sameMessage, date: undefined }
+ assert.equal(await synthesizeMessageId(undated), await synthesizeMessageId({ ...undated }))
+ assert.ok(SYNTH_ID_BUCKET_MS >= 60 * 60 * 1000, 'the bucket must outlast an MTA first retry')
+})
+
+test('synthesizeMessageId produces a shape the server will accept', async () => {
+ const id = await synthesizeMessageId(sameMessage)
+ assert.match(id, /^synth-[0-9a-f]{64}@cumora-email-gate$/)
+ assert.doesNotMatch(id, /[<>\s]/)
+})
+
+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 the
+ // source so the call site cannot quietly stop using it.
+ const source = await readFile(new URL('./index.ts', import.meta.url), 'utf8')
+ const handler = source.slice(source.indexOf('export default {'))
+
+ assert.match(handler, /synthesizeMessageId\(/, 'the handler no longer derives the fallback id')
+ assert.doesNotMatch(
+ handler, /randomUUID/,
+ 'the fallback Message-Id is random again — every MTA retry of the same message will deliver a duplicate',
+ )
+})
diff --git a/workers/email-gate/src/index.ts b/workers/email-gate/src/index.ts
index d01b6c0..8fd4c1f 100644
--- a/workers/email-gate/src/index.ts
+++ b/workers/email-gate/src/index.ts
@@ -127,6 +127,49 @@ export function getHeader(headers: { key: string; value: string }[] | undefined,
return undefined
}
+/** Fallback time bucket for a message that carries no `Date:` of its own.
+ * Wide enough to cover an MTA's first retries, which is when a tempfail is
+ * most likely to be retried at all. */
+export const SYNTH_ID_BUCKET_MS = 60 * 60 * 1000
+
+/** A Message-Id for a message that arrived without one. The server's dedup
+ * index requires a non-null id.
+ *
+ * It has to be DERIVED, not random. This worker throws on an upstream 5xx or a
+ * network failure precisely so the sending MTA tempfails and retries — and
+ * that retry runs this worker again on the same physical message. The server
+ * dedups on `smtp_message_id`, so a fresh random id per attempt is a fresh
+ * delivery per attempt: the recipient sees the same email once per retry. The
+ * comment here always claimed the id included "the recipient + a coarse
+ * timestamp"; the string it built included neither.
+ *
+ * The raw bytes are not a safe input. A retry is a new SMTP transaction and
+ * arrives with its own `Received:` headers, so identical mail hashes
+ * differently. These five fields survive that, and still tell two genuinely
+ * different messages apart.
+ *
+ * `Date:` is what separates two otherwise identical sends. RFC 5322 requires
+ * it and nearly every MTA adds it, but a sender that omitted Message-Id may
+ * have omitted this too — then fall back to a coarse bucket, which is the
+ * original intent and the best available when the message carries no time of
+ * its own. A retry that straddles a bucket boundary still duplicates. That
+ * residue is deliberate: merging two genuinely distinct alerts would lose
+ * mail, and losing mail is worse than showing it twice. */
+export async function synthesizeMessageId(parts: {
+ envelopeFrom: string
+ envelopeTo: string
+ date: string | undefined
+ subject: string
+ body: string
+}): Promise<string> {
+ const stamp = parts.date?.trim() || `bucket:${Math.floor(Date.now() / SYNTH_ID_BUCKET_MS)}`
+ // NUL-joined so a field boundary cannot be forged by content.
+ const material = [parts.envelopeFrom, parts.envelopeTo, stamp, parts.subject, parts.body].join('\u0000')
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(material))
+ const hex = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')
+ return `synth-${hex}@cumora-email-gate`
+}
+
export default {
async email(message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext): Promise<void> {
if (!recipientAccepted(message.to, env)) {
@@ -206,10 +249,13 @@ export default {
}
if (payload.to.length === 0) payload.to = [message.to]
if (!payload.messageId) {
- // Fabricate one — server's dedup index requires a non-null id.
- // Including the recipient + a coarse timestamp keeps re-deliveries
- // of the same physical message from creating duplicates per agent.
- payload.messageId = `synth-${Date.now().toString(36)}.${crypto.randomUUID()}@cumora-email-gate`
+ payload.messageId = await synthesizeMessageId({
+ envelopeFrom: message.from,
+ envelopeTo: message.to,
+ date: getHeader(parsed.headers, 'Date'),
+ subject: payload.subject,
+ body: payload.text,
+ })
}
const body = JSON.stringify(payload)