415 lines · 26.7 KB · TypeScriptRaw
/** * Mail on the person's own domain (22 Nov 2026; * assets/design/chat/OWN-MAIL.md): the Worker's email handler finds the * person by the domain, sends the stage-1 copy first, and the object keeps * the message sealed at arrival in the very rows the Mac would write, with * its attachments and raw message sealed in the person's media. Sending goes * once per draft through the ledger. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { afterEach, describe, expect, it } from "vitest";import worker from "../src/index.ts";import { resolverForTests, type Resolve } from "../src/mail/dns.ts";import { NO_SUCH_MAILBOX } from "../src/mail/receive.ts";import { senderForTests, WORDS, type MailSender } from "../src/mail/send.ts";import { bodyAad } from "../src/seal.ts";import { Store, type StoredRow } from "../src/store.ts";import { openArrivalFile, openArrivalRow } from "./arrival_keys.ts";import { DATABASE_ID, http, personalObject } from "./personal.ts";import { holdsWord } from "./clear-word.ts";const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const utf8 = new TextEncoder();afterEach(() => { resolverForTests(null); senderForTests(undefined);});/** DNS as Cloudflare writes it for a domain on routing and sending, with the person's proof record. */function dnsFor(domain: string, code: string | null, extra: Record<string, string[]> = {}): Resolve { const table: Record<string, string[]> = { [`MX ${domain}`]: ["13 route1.mx.cloudflare.net", "86 route2.mx.cloudflare.net", "24 route3.mx.cloudflare.net"], [`TXT ${domain}`]: ["v=spf1 include:_spf.mx.cloudflare.net ~all"], [`TXT cf2024-1._domainkey.${domain}`]: ["v=DKIM1; h=sha256; k=rsa; p=MIIB"], [`TXT cf-bounce._domainkey.${domain}`]: ["v=DKIM1; h=sha256; k=rsa; p=MIIC"], [`TXT _dmarc.${domain}`]: ["v=DMARC1; p=none"], ...(code ? { [`TXT _cotton.${domain}`]: [`cotton-verify=${code}`] } : {}), ...extra, }; return async (name, type) => table[`${type} ${name}`] ?? [];}/** A person with a proved domain, one address, and (optionally) its stage-1 copy. */async function person(slug: string, domain: string, o: { forwardTo?: string; arrival?: boolean; catchAll?: boolean } = {}): Promise<{ credential: string; auth: Record<string, string> }> { const { credential } = await personalObject(slug, { arrival: o.arrival ?? true }); const auth = { authorization: `Bearer ${credential}` }; const added = await http<{ proof: { name: string; value: string } }>(slug, "POST", "/v1/mail/domains", { domain }, auth); expect(added.status, JSON.stringify(added.body)).toBe(200); const code = added.body.proof.value.slice("cotton-verify=".length); resolverForTests(dnsFor(domain, code)); const checked = await http<{ proved: boolean; receiving: boolean; sending: boolean }>(slug, "POST", "/v1/mail/domains/check", { domain }, auth); expect(checked.body, JSON.stringify(checked.body)).toMatchObject({ proved: true, receiving: true, sending: true }); const address = await http(slug, "POST", "/v1/mail/addresses", { address: `me@${domain}`, forwardTo: o.forwardTo ?? null, isDefault: true }, auth); expect(address.status, JSON.stringify(address.body)).toBe(200); if (o.catchAll) await http(slug, "POST", "/v1/mail/domains/catch-all", { domain, on: true }, auth); return { credential, auth };}/** Cloudflare's ForwardableEmailMessage, as Email Routing hands it to the Worker. */function incoming(to: string, raw: string | Uint8Array, o: { forwardFails?: boolean } = {}) { const bytes = typeof raw === "string" ? utf8.encode(raw) : raw; const seen = { rejected: null as string | null, forwardedTo: [] as string[] }; const message = { from: "ada@example.org", to, headers: new Headers(), rawSize: bytes.byteLength, raw: new Response(bytes).body!, setReject(reason: string) { seen.rejected = reason; }, async forward(rcptTo: string) { if (o.forwardFails) throw Object.assign(new Error("not verified"), { code: "E_RECIPIENT_NOT_ALLOWED" }); seen.forwardedTo.push(rcptTo); return { messageId: "fwd" }; }, async reply() { return { messageId: "reply" }; }, }; return { message: message as unknown as ForwardableEmailMessage, seen };}const mail = (to: string, o: { id?: string; subject?: string; body?: string; refs?: string; attach?: boolean } = {}) => [ "Authentication-Results: mx.cloudflare.net; dkim=pass header.d=example.org; spf=pass smtp.mailfrom=example.org; dmarc=pass header.from=example.org", "From: Ada Example <ada@example.org>", `To: ${to}`, `Subject: ${o.subject ?? "Quillon parade"}`, "Date: Mon, 5 Oct 2026 09:30:00 +0000", `Message-ID: <${o.id ?? "parade.1@example.org"}>`, ...(o.refs ? [`In-Reply-To: <${o.refs}>`, `References: <${o.refs}>`] : []), "MIME-Version: 1.0", ...(o.attach ? [ 'Content-Type: multipart/mixed; boundary="b"', "", "--b", "Content-Type: text/plain; charset=utf-8", "", o.body ?? "Bring the brass drum to Ferrous lane.", "--b", 'Content-Type: application/pdf; name="route.pdf"', 'Content-Disposition: attachment; filename="route.pdf"', "Content-Transfer-Encoding: base64", "", btoa("COBALT ROUTE MAP"), "--b--", ] : ["Content-Type: text/plain; charset=utf-8", "", o.body ?? "Bring the brass drum to Ferrous lane."]), "", ].join("\r\n");async function rows(slug: string, table: string): Promise<StoredRow[]> { return runInDurableObject(stub(slug), (_i, state) => { const store = new Store(state.storage.sql, () => new Date()); return state.storage.sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = ?", table).toArray().map((r) => store.get(table, r.id)!).filter(Boolean); });}async function opened(table: string, row: StoredRow): Promise<Record<string, unknown>> { return openArrivalRow(row.data, bodyAad(DATABASE_ID, table, row.id), table, row.id);}describe("mail arriving on the person's own domain", () => { it("is copied to the present mailbox first, then kept sealed in the rows the Mac writes, with its attachment sealed", async () => { const slug = "ownmail-arrive"; await person(slug, "quillon.example", { forwardTo: "present@mailbox.example" }); const { message, seen } = incoming("Me+Parade@Quillon.example", mail("me@quillon.example", { attach: true })); await worker.email!(message, env); expect(seen.rejected).toBeNull(); expect(seen.forwardedTo).toEqual(["present@mailbox.example"]); const [email] = await rows(slug, "email"); expect(email, "one email row").toBeDefined(); expect(String(email!.data.dek_enc)).toMatch(/^a1:/); expect(email!.data).toMatchObject({ sent_at: "2026-10-05T09:30:00.000Z" }); const open = await opened("email", email!); expect(open).toMatchObject({ account: "me@quillon.example", direction: "in", unread: true, from_email: "ada@example.org", subject: "Quillon parade", body: "Bring the brass drum to Ferrous lane." }); const attachment = (open.attachments as { name: string; key: string }[])[0]!; expect(attachment).toMatchObject({ name: "route.pdf", mime: "application/pdf", key: `${DATABASE_ID}/mail/${email!.id}/0` }); const stored = await env.MEDIA.get(`${slug}/mail/${email!.id}/0`); const bytes = new Uint8Array(await stored!.arrayBuffer()); expect(new TextDecoder().decode(await openArrivalFile(bytes, attachment.key))).toBe("COBALT ROUTE MAP"); const [thread] = await rows(slug, "email_thread"); expect(thread!.id).toBe(email!.data.thread_id); expect(await opened("email_thread", thread!)).toMatchObject({ external_key: "imap:parade.1@example.org", subject: "Quillon parade", email_count: 1 }); const people = await rows(slug, "email_participant"); expect(people.length).toBe(2); // Nothing the object keeps in the clear holds a word of the mail. const kept = await runInDurableObject(stub(slug), (_i, state) => JSON.stringify([state.storage.sql.exec("SELECT data FROM rows WHERE table_id LIKE 'email%'").toArray(), state.storage.sql.exec("SELECT * FROM change").toArray(), state.storage.sql.exec("SELECT * FROM mail_arrival").toArray()])); for (const w of ["Quillon parade", "brass", "Ferrous", "COBALT", "Ada Example"]) expect(holdsWord(kept, w), w).toBe(false); const raw = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ raw_key: string; kept: string; forwarded: string; dmarc: string }>("SELECT raw_key, kept, forwarded, dmarc FROM mail_arrival").toArray()[0]!); expect(raw).toMatchObject({ kept: "rows", forwarded: "ok", dmarc: "pass" }); const rawBytes = new Uint8Array(await (await env.MEDIA.get(raw.raw_key.replace(`${DATABASE_ID}/`, `${slug}/`)))!.arrayBuffer()); expect(new TextDecoder().decode(await openArrivalFile(rawBytes, raw.raw_key))).toContain("Bring the brass drum"); }); it("joins a reply to its conversation, and the same message twice is one row", async () => { const slug = "ownmail-thread"; const { auth } = await person(slug, "cobalt.example"); for (const m of [mail("me@cobalt.example"), mail("me@cobalt.example", { id: "parade.2@example.org", subject: "Re: Quillon parade", refs: "parade.1@example.org" }), mail("me@cobalt.example")]) { const { message, seen } = incoming("me@cobalt.example", m); await worker.email!(message, env); expect(seen.rejected).toBeNull(); } const emails = await rows(slug, "email"); expect(emails.length).toBe(2); expect(new Set(emails.map((e) => e.data.thread_id)).size).toBe(1); expect((await rows(slug, "email_thread")).length).toBe(1); const tally = await http<{ days: { came: number; rows: number; duplicate: number }[] }>(slug, "GET", "/v1/mail/tally?days=3650", undefined, auth); expect(tally.body.days.reduce((n, d) => n + d.came, 0)).toBe(3); expect(tally.body.days.reduce((n, d) => n + d.duplicate, 0)).toBe(1); const cross = await http<{ arrived: string[] }>(slug, "POST", "/v1/mail/arrived", { ids: [emails[0]!.id, "not-one"] }, auth); expect(cross.body.arrived).toEqual([emails[0]!.id]); // RULE (incident, 23 Nov 2026: the Mac's mail stood at "the object refused (500 internal_error)"): the Mac asks // about a page's ids up to 1,000 at once, and a Durable Object's SQLite binds at most 100 parameters. const many = Array.from({ length: 999 }, (_, i) => `not-${i}`); many.splice(500, 0, emails[0]!.id); const page = await http<{ arrived: string[] }>(slug, "POST", "/v1/mail/arrived", { ids: many }, auth); expect(page.status).toBe(200); expect(page.body.arrived).toEqual([emails[0]!.id]); }); it("refuses an address that is not the person's, a domain nobody holds, and one not yet proved", async () => { const slug = "ownmail-refuse"; await person(slug, "ferrous.example"); for (const to of ["stranger@ferrous.example", "me@nobody.example"]) { const { message, seen } = incoming(to, mail(to)); await worker.email!(message, env); expect(seen.rejected, to).toBe(NO_SUCH_MAILBOX); } expect(await rows(slug, "email")).toEqual([]); }); it("takes any address at a catch-all domain", async () => { const slug = "ownmail-catchall"; await person(slug, "brass.example", { catchAll: true }); const { message, seen } = incoming("shop@brass.example", mail("shop@brass.example")); await worker.email!(message, env); expect(seen.rejected).toBeNull(); expect((await opened("email", (await rows(slug, "email"))[0]!)).account).toBe("shop@brass.example"); }); it("with no arrival key keeps nothing readable: let go when its copy went, refused when it did not", async () => { const slug = "ownmail-nokey"; await person(slug, "drum.example", { arrival: false, forwardTo: "present@mailbox.example" }); const copied = incoming("me@drum.example", mail("me@drum.example")); await worker.email!(copied.message, env); expect(copied.seen.forwardedTo).toEqual(["present@mailbox.example"]); expect(await rows(slug, "email")).toEqual([]); const failing = incoming("me@drum.example", mail("me@drum.example", { id: "two@example.org" }), { forwardFails: true }); await expect(worker.email!(failing.message, env)).rejects.toThrow(/arrival key/); const tally = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ kept: string; forwarded: string }>("SELECT kept, forwarded FROM mail_arrival").toArray()); expect(tally).toEqual([{ kept: "no_key", forwarded: "ok" }]); }); it("keeps what it cannot read as rows raw and sealed, for the phone", async () => { const slug = "ownmail-raw"; const { auth } = await person(slug, "lane.example"); const { message, seen } = incoming("me@lane.example", "Subject: no sender here\r\nDate: Mon, 5 Oct 2026 09:30:00 +0000\r\n\r\nhello\r\n"); await worker.email!(message, env); expect(seen.rejected).toBeNull(); const raw = await http<{ raw: { id: string; key: string; words: string }[] }>(slug, "GET", "/v1/mail/raw", undefined, auth); expect(raw.body.raw).toHaveLength(1); expect(raw.body.raw[0]!.words).toContain("no_sender"); });});describe("the dev door for the proof at size", () => { it("takes the owner's raw message as Email Routing would, to their own address only", async () => { const slug = "ownmail-devdoor"; const { auth } = await person(slug, "devdoor.example"); const post = (to: string, body: string, headers: Record<string, string> = auth) => SELF.fetch(`https://example.test/b/${slug}/v1/mail/arrive-raw`, { method: "POST", headers: { ...headers, "x-mail-to": to, "content-type": "message/rfc822" }, body }); const took = await post("me@devdoor.example", mail("me@devdoor.example")); expect(took.status).toBe(200); expect(await took.json()).toMatchObject({ kept: "rows" }); expect((await rows(slug, "email")).length).toBe(1); expect((await post("stranger@devdoor.example", mail("stranger@devdoor.example"))).status).toBe(404); expect((await post("me@devdoor.example", mail("me@devdoor.example"), {})).status).toBe(403); // An invented domain held as proved without DNS, and never told to the Directory: no real mail reaches it. await http(slug, "POST", "/v1/mail/domains", { domain: "invented-proof.example" }, auth); expect((await http(slug, "POST", "/v1/mail/domains/prove-dev", { domain: "invented-proof.example" }, auth)).body).toEqual({ domain: "invented-proof.example", proved: true }); expect(await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).mailDomainOf("invented-proof.example")).toBeNull(); });});describe("the person's domain", () => { it("is proved only by its TXT record, and its DNS is said line by line", async () => { const slug = "ownmail-dns"; const { credential } = await personalObject(slug, { arrival: true }); const auth = { authorization: `Bearer ${credential}` }; await http(slug, "POST", "/v1/mail/domains", { domain: "parade.example" }, auth); resolverForTests(dnsFor("parade.example", null, { "MX parade.example": ["10 aspmx.l.google.com"], "TXT parade.example": ["v=spf1 include:_spf.google.com ~all", "v=spf1 -all"] })); const check = await http<{ proved: boolean; receiving: boolean; lines: { id: string; ok: boolean; said: string }[] }>(slug, "POST", "/v1/mail/domains/check", { domain: "parade.example" }, auth); expect(check.body.proved).toBe(false); expect(check.body.receiving).toBe(false); const said = Object.fromEntries(check.body.lines.map((l) => [l.id, l.said])); expect(said.proof).toMatch(/^Add a TXT record at _cotton\.parade\.example with cotton-verify=/); expect(said.mx).toContain("aspmx.l.google.com"); expect(said.spf).toBe("parade.example has 2 SPF records; keep one."); expect(await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).mailDomainOf("parade.example")).toBeNull(); }); it("held by one person cannot be taken by another", async () => { await person("ownmail-first", "taken.example"); const { credential } = await personalObject("ownmail-second", { arrival: true }); const auth = { authorization: `Bearer ${credential}` }; const added = await http<{ proof: { value: string } }>("ownmail-second", "POST", "/v1/mail/domains", { domain: "taken.example" }, auth); resolverForTests(dnsFor("taken.example", added.body.proof.value.slice("cotton-verify=".length))); const check = await http<{ code: string }>("ownmail-second", "POST", "/v1/mail/domains/check", { domain: "taken.example" }, auth); expect(check.status).toBe(409); expect(check.body.code).toBe("domain_taken"); });});describe("sending from the person's own address", () => { class FakeSender implements MailSender { sent: Parameters<MailSender["send"]>[0][] = []; fail: string | null = null; async send(builder: Parameters<MailSender["send"]>[0]): Promise<{ messageId: string }> { if (this.fail) throw Object.assign(new Error(this.fail), { code: this.fail }); this.sent.push(builder); return { messageId: `<cf-${this.sent.length}@quillon.example>` }; } } const ask = (draft: string, extra: Record<string, unknown> = {}, domain = "send.example") => ({ draft, from: `me@${domain}`, to: ["ada@example.org"], cc: [], subject: "Re: Quillon parade", text: "Noon works.", inReplyTo: "<parade.2@example.org>", references: ["<parade.1@example.org>"], ...extra }); it("sends a draft once, threaded, however often it is asked", async () => { const slug = "ownmail-send"; const { auth } = await person(slug, "send.example"); const sender = new FakeSender(); senderForTests(sender); const first = await http<{ state: string; messageId: string }>(slug, "POST", "/v1/mail/send", ask("draft-1"), auth); expect(first.body).toMatchObject({ state: "sent", messageId: "<cf-1@quillon.example>" }); const again = await http<{ state: string }>(slug, "POST", "/v1/mail/send", ask("draft-1"), auth); expect(again.body.state).toBe("sent"); expect(sender.sent).toHaveLength(1); // The Sent copy: kept sealed, the person's own, read, threaded by what it answered. const [copy] = await rows(slug, "email"); expect(copy!.id).toBe((first.body as { email?: string }).email); expect(await opened("email", copy!)).toMatchObject({ direction: "out", unread: false, in_inbox: false, account: "me@send.example", from_email: "me@send.example", subject: "Re: Quillon parade", body: "Noon works.", message_id: "<cf-1@quillon.example>", message_refs: "<parade.1@example.org> <parade.2@example.org>" }); const [thread] = await rows(slug, "email_thread"); expect(await opened("email_thread", thread!)).toMatchObject({ external_key: "imap:parade.1@example.org" }); expect(sender.sent[0]).toMatchObject({ from: "me@send.example", to: ["ada@example.org"], subject: "Re: Quillon parade", headers: { "In-Reply-To": "<parade.2@example.org>", References: "<parade.1@example.org> <parade.2@example.org>" } }); expect(await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).mailSentOf("<cf-1@quillon.example>")).toBe(slug); // Cloudflare's later word on it lands beside the draft. expect(await stub(slug).mailDelivered("<cf-1@quillon.example>", "bounced", "550 5.1.1 User unknown")).toBe(true); const ledger = await http<{ sends: { state: string; delivery: string; deliveryWords: string }[] }>(slug, "GET", "/v1/mail/sends?draft=draft-1", undefined, auth); expect(ledger.body.sends[0]).toMatchObject({ state: "sent", delivery: "bounced", deliveryWords: "550 5.1.1 User unknown" }); // Bcc and files go to Cloudflare as its builder takes them (route "domain", the default). const withFiles = await http(slug, "POST", "/v1/mail/send", ask("draft-2", { route: "domain", bcc: ["quiet@example.org"], attachments: [{ name: "route.pdf", mime: "application/pdf", content: btoa("COBALT") }] }), auth); expect(withFiles.body).toMatchObject({ state: "sent" }); expect(sender.sent[1]).toMatchObject({ bcc: ["quiet@example.org"], attachments: [{ disposition: "attachment", filename: "route.pdf", type: "application/pdf" }] }); expect(new TextDecoder().decode(sender.sent[1]!.attachments![0]!.content)).toBe("COBALT"); expect((await http(slug, "POST", "/v1/mail/send", ask("draft-3", { route: "fax" }), auth)).status).toBe(400); }); it("says why it did not send, and sends on the person's Retry", async () => { const slug = "ownmail-fail"; const { auth } = await person(slug, "fail.example"); const sender = new FakeSender(); senderForTests(sender); sender.fail = "E_DAILY_LIMIT_EXCEEDED"; const failed = await http<{ state: string; said: string }>(slug, "POST", "/v1/mail/send", ask("draft-2", {}, "fail.example"), auth); expect(failed.body).toMatchObject({ state: "failed", said: WORDS.limit }); sender.fail = null; const retried = await http<{ state: string }>(slug, "POST", "/v1/mail/send", ask("draft-2", {}, "fail.example"), auth); expect(retried.body.state).toBe("sent"); expect(sender.sent).toHaveLength(1); }); it("refuses before sending: not your address, no one to send to, too many, and no sender set up", async () => { const slug = "ownmail-refuse-send"; const { auth } = await person(slug, "refuse.example"); senderForTests(new FakeSender()); const notMine = await http<{ code: string }>(slug, "POST", "/v1/mail/send", ask("d", { from: "someone@elsewhere.example" }, "refuse.example"), auth); expect(notMine.body.code).toBe("not_your_address"); const nobody = await http<{ code: string }>(slug, "POST", "/v1/mail/send", ask("d", { to: [] }, "refuse.example"), auth); expect(nobody.body.code).toBe("no_recipient"); const many = await http<{ code: string }>(slug, "POST", "/v1/mail/send", ask("d", { to: Array.from({ length: 51 }, (_, i) => `p${i}@example.org`) }, "refuse.example"), auth); expect(many.body.code).toBe("too_many_recipients"); const bad = await http<{ code: string }>(slug, "POST", "/v1/mail/send", ask("d", { to: ["not an address"] }, "refuse.example"), auth); expect(bad.body.code).toBe("bad_address"); senderForTests(null); const none = await http<{ state: string; said: string }>(slug, "POST", "/v1/mail/send", ask("d", {}, "refuse.example"), auth); expect(none.body).toMatchObject({ state: "failed", said: WORDS.notSetUp }); }); it("a send that never heard back is said unknown, and Retry is the person's", async () => { const slug = "ownmail-unknown"; const { auth } = await person(slug, "unknown.example"); await runInDurableObject(stub(slug), (_i, state) => { state.storage.sql.exec("INSERT INTO mail_send (draft, state, from_address, started_at) VALUES ('d3', 'sending', 'me@unknown.example', ?)", Date.now() - 3 * 60_000); }); const sender = new FakeSender(); senderForTests(sender); const ledger = await http<{ sends: { state: string; said: string }[] }>(slug, "GET", "/v1/mail/sends?draft=d3", undefined, auth); expect(ledger.body.sends[0]).toMatchObject({ state: "unknown", said: WORDS.unknown }); expect(sender.sent).toHaveLength(0); const retried = await http<{ state: string }>(slug, "POST", "/v1/mail/send", ask("d3", {}, "unknown.example"), auth); expect(retried.body.state).toBe("sent"); });});describe("aliases, plus-addressing and a deleted address (Post CONTRACT row 14)", () => { type Plan = { accept: boolean; mailbox: string; forwardTo: string | null }; const planOf = (slug: string, to: string) => (stub(slug) as unknown as { mailPlan(to: string): Promise<Plan> }).mailPlan(to); it("delivers an alias into the mailbox it lands on, a +part into its own, and refuses a deleted address even at a catch-all domain", async () => { const slug = "ownmail-alias"; const domain = "lantern-alias.example"; const { auth } = await person(slug, domain, { forwardTo: "present@elsewhere.example", catchAll: true }); // An alias of me@: delivered into me@'s mailbox, with me@'s copy. const alias = await http<{ lands: string | null }>(slug, "POST", "/v1/mail/addresses", { address: `hello@${domain}`, lands: `me@${domain}` }, auth); expect(alias.status, JSON.stringify(alias.body)).toBe(200); expect(alias.body.lands).toBe(`me@${domain}`); expect(await planOf(slug, `hello@${domain}`)).toEqual({ accept: true, mailbox: `me@${domain}`, forwardTo: "present@elsewhere.example" }); expect(await planOf(slug, `hello+parade@${domain}`)).toEqual({ accept: true, mailbox: `me@${domain}`, forwardTo: "present@elsewhere.example" }); // Plus-addressing is on: any +part reaches its address. expect(await planOf(slug, `me+receipts@${domain}`)).toMatchObject({ accept: true, mailbox: `me@${domain}` }); // The shapes an alias may not take, each by name. expect((await http(slug, "POST", "/v1/mail/addresses", { address: `loop@${domain}`, lands: `loop@${domain}` }, auth)).body).toMatchObject({ code: "alias_loop" }); expect((await http(slug, "POST", "/v1/mail/addresses", { address: `twice@${domain}`, lands: `hello@${domain}` }, auth)).body).toMatchObject({ code: "alias_loop" }); expect((await http(slug, "POST", "/v1/mail/addresses", { address: `stray@${domain}`, lands: `nobody@${domain}` }, auth)).body).toMatchObject({ code: "unknown_address" }); expect((await http(slug, "POST", "/v1/mail/addresses", { address: `me@${domain}`, lands: `hello@${domain}` }, auth)).body).toMatchObject({ code: "alias_loop" }); // Deleted (the address in the body): me@ goes with the alias landing on it; mail to either is refused from now on, // though the domain still takes any other address. const gone = await http<{ removed: string[]; addresses: { address: string }[] }>(slug, "DELETE", "/v1/mail/addresses", { address: `me@${domain}` }, auth); expect(gone.status, JSON.stringify(gone.body)).toBe(200); expect(gone.body.removed.sort()).toEqual([`hello@${domain}`, `me@${domain}`]); expect(gone.body.addresses).toEqual([]); expect((await planOf(slug, `me@${domain}`)).accept).toBe(false); expect((await planOf(slug, `me+receipts@${domain}`)).accept).toBe(false); expect((await planOf(slug, `hello@${domain}`)).accept).toBe(false); expect((await planOf(slug, `anyone@${domain}`)).accept).toBe(true); // The Worker's email handler answers the sender "No such mailbox here": refused, never dropped. const { message, seen } = incoming(`me@${domain}`, mail(`me@${domain}`, { id: "gone.1@example.org" })); await worker.email!(message, env); expect(seen.rejected).toBe(NO_SUCH_MAILBOX); // Added again: it is the person's again. And a delete by the query, as earlier builds send it. expect((await http(slug, "POST", "/v1/mail/addresses", { address: `me@${domain}` }, auth)).status).toBe(200); expect((await planOf(slug, `me@${domain}`)).accept).toBe(true); const byQuery = await http<{ removed: string[] }>(slug, "DELETE", `/v1/mail/addresses?address=${encodeURIComponent(`me@${domain}`)}`, undefined, auth); expect(byQuery.body.removed).toEqual([`me@${domain}`]); expect((await planOf(slug, `me@${domain}`)).accept).toBe(false); });});