/** * Cotton fetches, the password's half (src/mail/fetch.ts; Post CONTRACT "The Worker", row 13): a mailbox's password * given from the owner's phone is kept encrypted under MAIL_FETCH_KEY, answered by no route, written to no log, and * gone at once when removed. Invented mailbox and password only. */ import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; import type { Business } from "../src/business.ts"; import { openPassword } from "../src/mail/fetch.ts"; import { dial } from "../src/mail/imap.ts"; import { bodyAad } from "../src/seal.ts"; import { Store, type StoredRow } from "../src/store.ts"; import { openArrivalRow } from "./arrival_keys.ts"; import { holdsWord } from "./clear-word.ts"; import { FakeImap } from "./fake-imap.ts"; import { FakeSmtp } from "./fake-smtp.ts"; import { DATABASE_ID, http, mint, personalObject } from "./personal.ts"; const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug)); const PASSWORD = "invented-app-password-quill-7731"; describe("a mailbox given to Cotton", () => { it("keeps its password encrypted, never answers or logs it, and drops it at once on removal", async () => { const slug = "mail-fetch-hold"; const { credential } = await personalObject(slug); const phone = { authorization: `Bearer ${credential}` }; const account = "acct-invented-1"; const given = await http(slug, "POST", "/v1/mail/fetch", { account, address: "Mira@Example.test", host: "imap.example.test", port: 993, password: PASSWORD }, phone); expect(given.status, JSON.stringify(given.body)).toBe(200); expect(given.body).toEqual({ account, state: "idle" }); // Stored only sealed, bound to this database and account; the key opens it, nothing else holds it. const stored = await runInDurableObject(stub(slug), (_i, state) => ({ row: state.storage.sql.exec>("SELECT * FROM mail_fetch_account").one(), everything: JSON.stringify(state.storage.sql.exec("SELECT * FROM mail_fetch_account").toArray()) + JSON.stringify(state.storage.sql.exec("SELECT * FROM mail_fetch_log").toArray()), })); expect(stored.row).toMatchObject({ account, address: "mira@example.test", host: "imap.example.test", port: 993, state: "idle" }); expect(String(stored.row.password_enc)).toMatch(/^f1:/); expect(stored.everything).not.toContain(PASSWORD); expect(await openPassword(env, DATABASE_ID, account, String(stored.row.password_enc))).toBe(PASSWORD); await expect(openPassword(env, DATABASE_ID, "acct-other", String(stored.row.password_enc))).rejects.toThrow(); // What the phone reads: the state and the log, never the password nor the address. const st = await http<{ state: string; since: string | null; last_at: string | null }>(slug, "GET", `/v1/mail/fetch/state?account=${account}`, undefined, phone); expect(st.body).toMatchObject({ state: "idle", last_at: null }); expect(Date.parse(st.body.since!)).toBeGreaterThan(Date.now() - 600_000); for (const path of [`/v1/mail/fetch/state?account=${account}`, `/v1/mail/fetch/log?account=${account}`, "/v1/mail/settings"]) { const r = await http(slug, "GET", path, undefined, phone); expect(JSON.stringify(r.body), path).not.toContain(PASSWORD); } // Only the owner's own signed-in phone gives one: an owner token is refused, and so is a malformed one. const token = await mint(slug, credential, "invented lane", ["owner"]); expect((await http(slug, "POST", "/v1/mail/fetch", { account, address: "a@example.test", host: "imap.example.test", password: "x" }, { authorization: `Bearer ${token}` })).status).toBe(403); expect((await http(slug, "POST", "/v1/mail/fetch", { account, address: "a@example.test", host: "not a host", password: "x" }, phone)).body).toMatchObject({ code: "bad_host" }); expect((await http(slug, "POST", "/v1/mail/fetch", { account, address: "a@example.test", host: "127.0.0.1", port: 1143, password: "x" }, phone)).status).toBe(200); expect((await http(slug, "POST", "/v1/mail/fetch", { account: "bad account!", address: "a@example.test", host: "imap.example.test", password: "x" }, phone)).body).toMatchObject({ code: "bad_account" }); expect((await http(slug, "POST", "/v1/mail/fetch", { account, address: "a@example.test", host: "imap.example.test", password: "" }, phone)).body).toMatchObject({ code: "bad_password" }); // Removed: the row is gone at once and the log says stopped, with no address and no password. const removed = await http<{ removed_at: string }>(slug, "DELETE", "/v1/mail/fetch", { account }, phone); expect(removed.status, JSON.stringify(removed.body)).toBe(200); expect(Date.parse(removed.body.removed_at)).toBeGreaterThan(Date.now() - 600_000); expect(await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec("SELECT count(*) AS n FROM mail_fetch_account").one().n)).toBe(0); expect((await http(slug, "GET", `/v1/mail/fetch/state?account=${account}`, undefined, phone)).body).toEqual({ state: "stopped", since: null, last_at: null }); const log = await http<{ log: { kind: string; account: string; code: string | null }[] }>(slug, "GET", `/v1/mail/fetch/log?account=${account}&limit=5`, undefined, phone); expect(log.body.log[0]).toMatchObject({ kind: "stopped", account, code: "removed" }); expect(JSON.stringify(log.body)).not.toContain("example.test"); }); }); // ── the reading half (src/mail/imap.ts, src/mail/fetcher.ts), against an in-memory server ── function message(o: { from: string; to: string; id: string; subject: string; body: string; date?: string }): string { return [`From: ${o.from}`, `To: ${o.to}`, `Subject: ${o.subject}`, `Date: ${o.date ?? "Mon, 5 Oct 2026 09:30:00 +0000"}`, `Message-ID: <${o.id}>`, "MIME-Version: 1.0", "Content-Type: text/plain; charset=utf-8", "", o.body, ""].join("\r\n"); } async function rows(slug: string, table: string): Promise { 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(slug: string): Promise[]> { return Promise.all((await rows(slug, "email")).map((r) => openArrivalRow(r.data, bodyAad(DATABASE_ID, "email", r.id), "email", r.id))); } const passOf = (slug: string, fake: FakeImap) => runInDurableObject(stub(slug), (instance: Business) => instance.fetchMailPass(fake.dial)); const dueNow = (slug: string) => runInDurableObject(stub(slug), (_i, state) => void state.storage.sql.exec("UPDATE mail_fetch_account SET last_at = NULL")); async function given(slug: string, address: string, password = PASSWORD): Promise> { const { credential } = await personalObject(slug, { arrival: true }); const phone = { authorization: `Bearer ${credential}` }; const r = await http(slug, "POST", "/v1/mail/fetch", { account: "acct-fetch", address, host: "imap.example.test", port: 993, password }, phone); expect(r.status, JSON.stringify(r.body)).toBe(200); return phone; } describe("Cotton reading a mailbox given to it", () => { it("reads Gmail's All Mail into sealed rows its labels describe, new mail after history, never marking anything read", async () => { const slug = "mail-fetch-gmail"; const phone = await given(slug, "mira@example.test"); const me = "Mira Example "; const fake = new FakeImap({ gmail: true, user: "mira@example.test", password: PASSWORD }) .box("INBOX", { validity: 7, messages: [] }) .box("[Gmail]/All Mail", { validity: 9, flags: ["\\HasNoChildren", "\\All"], messages: [ { uid: 11, msgid: "1790000000000000011", labels: ["\\Inbox"], flags: ["\\Seen"], raw: message({ from: "Orrin ", to: me, id: "lantern.1@example.org", subject: "Lantern walk", body: "Meet at the copper gate." }) }, { uid: 12, msgid: "1790000000000000012", labels: ["\\Sent"], flags: ["\\Seen"], raw: message({ from: me, to: "Orrin ", id: "lantern.2@example.test", subject: "Re: Lantern walk", body: "Bringing the saffron cake." }) }, { uid: 14, msgid: "1790000000000000014", labels: ["\\Inbox", "Receipts"], flags: [], raw: message({ from: "Shop ", to: me, id: "receipt.9@example.net", subject: "Your marigold order", body: "Order 4410 is on its way." }) }, ], }); const first = await passOf(slug, fake); expect(first.results).toEqual([{ account: "acct-fetch", count: 3, more: false, state: "idle" }]); const mails = await opened(slug); expect(mails.length).toBe(3); const by = (subject: string) => mails.find((m) => String(m.body).includes(subject))!; expect(by("copper gate")).toMatchObject({ account: "mira@example.test", direction: "in", unread: false, in_inbox: true }); expect(by("saffron")).toMatchObject({ direction: "out", unread: false, in_inbox: false }); expect(by("marigold") ?? by("4410")).toMatchObject({ direction: "in", unread: true, in_inbox: true }); // Read with EXAMINE and BODY.PEEK[]: nothing changed on the server, nothing stored, no password said. expect(fake.said).toContain("EXAMINE [Gmail]/All Mail"); expect(fake.said.some((c) => /STORE|EXPUNGE|DELETED/i.test(c))).toBe(false); expect(fake.said.join("\n")).not.toContain(PASSWORD); expect(fake.closed).toBe(fake.opened); // Nothing the object keeps in the clear holds a word of the mail; the log says how many, never what. 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 mail_arrival").toArray(), state.storage.sql.exec("SELECT * FROM mail_fetch_log").toArray()])); for (const w of ["Lantern", "copper", "saffron", "marigold", "Orrin"]) expect(holdsWord(kept, w), w).toBe(false); const log = await http<{ log: { kind: string; count: number; code: string | null }[] }>(slug, "GET", "/v1/mail/fetch/log?account=acct-fetch", undefined, phone); expect(log.body.log[0]).toMatchObject({ kind: "fetched", count: 3, code: null }); expect((await http<{ state: string; last_at: string | null }>(slug, "GET", "/v1/mail/fetch/state?account=acct-fetch", undefined, phone)).body).toMatchObject({ state: "idle" }); // Not due again for five minutes; then new mail alone is read. expect((await passOf(slug, fake)).results).toEqual([]); fake.boxes.get("[Gmail]/All Mail")!.messages.push({ uid: 15, msgid: "1790000000000000015", labels: ["\\Inbox"], flags: ["\\Flagged"], raw: message({ from: "Orrin ", to: me, id: "lantern.3@example.org", subject: "Re: Lantern walk", body: "Gate moved to the mill." }) }); await dueNow(slug); expect((await passOf(slug, fake)).results[0]).toMatchObject({ count: 1 }); expect([...fake.bodies.entries()].sort()).toEqual([[11, 1], [12, 1], [14, 1], [15, 1]]); expect((await opened(slug)).find((m) => String(m.body).includes("mill"))).toMatchObject({ starred: true, unread: true }); // A new UIDVALIDITY reads the mailbox again from the top: every message already kept is one row still, and keeps no second raw copy. fake.boxes.get("[Gmail]/All Mail")!.validity = 10; await dueNow(slug); expect((await passOf(slug, fake)).results[0]).toMatchObject({ count: 4 }); expect((await rows(slug, "email")).length).toBe(4); const dups = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ kept: string; raw_key: string | null }>("SELECT kept, raw_key FROM mail_arrival WHERE kept = 'duplicate'").toArray()); expect(dups.length).toBe(4); expect(dups.every((d) => d.raw_key === null)).toBe(true); }, 300_000); it("stops an account whose password the server refuses, says refused, and reads nothing until it is given again", async () => { const slug = "mail-fetch-refused"; const phone = await given(slug, "mira@example.test", "an-old-invented-password"); const fake = new FakeImap({ gmail: false, user: "mira@example.test", password: PASSWORD }).box("INBOX", { validity: 1, messages: [{ uid: 1, raw: message({ from: "a@example.org", to: "mira@example.test", id: "x.1@example.org", subject: "Kestrel", body: "Kestrel nest." }) }] }); expect((await passOf(slug, fake)).results).toEqual([{ account: "acct-fetch", count: 0, more: false, state: "refused" }]); expect((await http(slug, "GET", "/v1/mail/fetch/state?account=acct-fetch", undefined, phone)).body).toMatchObject({ state: "refused" }); expect((await http<{ log: { kind: string; code: string }[] }>(slug, "GET", "/v1/mail/fetch/log?account=acct-fetch", undefined, phone)).body.log[0]).toMatchObject({ kind: "failed", code: "refused" }); await dueNow(slug); const dials = fake.dials; expect((await passOf(slug, fake)).results).toEqual([]); expect(fake.dials).toBe(dials); // Given again with the right one: read at once. expect((await http(slug, "POST", "/v1/mail/fetch", { account: "acct-fetch", address: "mira@example.test", host: "imap.example.test", password: PASSWORD }, phone)).body).toEqual({ account: "acct-fetch", state: "idle" }); expect((await passOf(slug, fake)).results[0]).toMatchObject({ count: 1, state: "idle" }); expect((await rows(slug, "email")).length).toBe(1); }, 300_000); it("reads a plain server's INBOX, its flags saying read and starred, and takes a password a quoted string cannot carry", async () => { const slug = "mail-fetch-plain"; const odd = 'invented "pass" \\ wörd'; await given(slug, "tam@example.test", odd); const fake = new FakeImap({ gmail: false, user: "tam@example.test", password: odd }).box("INBOX", { validity: 3, messages: [ { uid: 2, flags: ["\\Seen", "\\Flagged"], raw: message({ from: "Ivo ", to: "tam@example.test", id: "q.2@example.org", subject: "Quarry", body: "Quarry rope at noon." }) }, { uid: 5, flags: [], raw: message({ from: "Ivo ", to: "tam@example.test", id: "q.5@example.org", subject: "Quarry again", body: "Bring the brass lamp." }) }, ], }); expect((await passOf(slug, fake)).results[0]).toMatchObject({ count: 2, state: "idle" }); const mails = await opened(slug); expect(mails.find((m) => String(m.body).includes("rope"))).toMatchObject({ unread: false, starred: true, in_inbox: true, direction: "in", account: "tam@example.test" }); expect(mails.find((m) => String(m.body).includes("lamp"))).toMatchObject({ unread: true, starred: false, in_inbox: true }); expect(fake.said).toContain("EXAMINE INBOX"); }, 300_000); }); // ── the acts (src/mail/acts.ts): done in the mailbox inside the request, named by the email row ── const actOf = (slug: string, fake: FakeImap, body: Record, post?: typeof globalThis.fetch) => runInDurableObject(stub(slug), (instance: Business) => instance.fetchMailAct({ account: "acct-fetch", ...body }, fake.dial, post)); const emailOf = (slug: string, uid: number) => runInDurableObject(stub(slug), (_i, state) => String(state.storage.sql.exec("SELECT email_id FROM mail_fetch_index WHERE uid = ?", uid).one().email_id)); describe("the person's acts on a mailbox Cotton reads", () => { it("on Gmail: read and unread, archive read back, Trash, a sender's mail counted first and then exactly that set, and an unsubscribe", async () => { const slug = "mail-fetch-acts-gmail"; const phone = await given(slug, "mira@example.test"); const me = "Mira Example "; const shop = (uid: number, inbox = true) => ({ uid, msgid: `17900000000000001${uid}`, labels: inbox ? ["\\Inbox"] : [], flags: [], raw: message({ from: "Shop ", to: me, id: `bill.${uid}@example.net`, subject: `Bill ${uid}`, body: `Invoice ${uid}.` }) }); const fake = new FakeImap({ gmail: true, user: "mira@example.test", password: PASSWORD }) .box("INBOX", { validity: 7, messages: [] }) .box("[Gmail]/Trash", { validity: 8, flags: ["\\Trash"], messages: [] }) .box("[Gmail]/All Mail", { validity: 9, flags: ["\\All"], messages: [{ uid: 21, msgid: "1790000000000000121", labels: ["\\Inbox"], flags: [], raw: message({ from: "Orrin ", to: me, id: "heron.1@example.org", subject: "Heron", body: "Heron at the weir." }) }, shop(22), shop(23), shop(24, false)], }); expect((await passOf(slug, fake)).results[0]).toMatchObject({ count: 4 }); const all = () => fake.boxes.get("[Gmail]/All Mail")!.messages; const heron = await emailOf(slug, 21); expect(await actOf(slug, fake, { kind: "mark_read", email: heron })).toEqual({ ok: true }); expect(all().find((m) => m.uid === 21)!.flags).toContain("\\Seen"); expect(await actOf(slug, fake, { kind: "mark_unread", email: heron })).toEqual({ ok: true }); expect(all().find((m) => m.uid === 21)!.flags).not.toContain("\\Seen"); expect(await actOf(slug, fake, { kind: "archive", email: heron })).toEqual({ ok: true }); expect(all().find((m) => m.uid === 21)!.labels).not.toContain("\\Inbox"); // Read back: a label Gmail keeps is said, not taken for done. fake.sticky = "\\Inbox"; expect(await actOf(slug, fake, { kind: "archive", email: await emailOf(slug, 22) })).toEqual({ ok: false, error: "Gmail kept it in your Inbox." }); fake.sticky = null; expect(await actOf(slug, fake, { kind: "trash", email: heron })).toEqual({ ok: true }); expect(all().some((m) => m.uid === 21)).toBe(false); expect(fake.boxes.get("[Gmail]/Trash")!.messages.length).toBe(1); expect(await actOf(slug, fake, { kind: "trash", email: heron })).toEqual({ ok: false, error: "This email is no longer in your mail." }); // A sender's Trash: counted and asked first, then exactly the set counted (one arriving since stays). expect(await actOf(slug, fake, { kind: "sender_count", to: "Bills@Example.net" })).toEqual({ ok: true, count: 3, uid_validity: 9, uid_below: 25 }); expect(await actOf(slug, fake, { kind: "sender_count", to: "bills@example.net", target: "inbox" })).toMatchObject({ ok: true, count: 2 }); const asked = await actOf(slug, fake, { kind: "sender_trash", to: "bills@example.net" }); expect(asked).toEqual({ ok: false, error: "Your mail holds 3 emails from them. Try again to move those 3 to Trash.", count: 3, uid_validity: 9, uid_below: 25 }); all().push(shop(25)); expect(await actOf(slug, fake, { kind: "sender_trash", to: "bills@example.net", count: 2, uid_validity: 9, uid_below: 25 })).toEqual({ ok: false, error: "Your mail holds more from them than was counted, so nothing was moved. Count again." }); const moved = await actOf(slug, fake, { kind: "sender_trash", to: "bills@example.net", count: 3, uid_validity: 9, uid_below: 25 }); expect(moved).toMatchObject({ ok: true, moved: 3 }); expect([...moved.gone!].sort()).toEqual([await emailOf(slug, 22), await emailOf(slug, 23), await emailOf(slug, 24)].sort()); expect(all().map((m) => m.uid)).toEqual([25]); expect(await actOf(slug, fake, { kind: "sender_trash", to: "bills@example.net", count: 3, uid_validity: 4, uid_below: 25 })).toMatchObject({ ok: false, error: "The mailbox was renumbered since the count. Count again." }); expect(fake.said.some((c) => /EXPUNGE|DELETED/i.test(c))).toBe(false); // Unsubscribe: RFC 8058's one-click POST when offered; a redirect to a page is not a click, and the sender joins this account's list instead. const posts: { url: string; body: string }[] = []; const web = (status: number) => (async (url: string | URL | Request, init?: RequestInit) => { posts.push({ url: String(url), body: String(init?.body) }); return new Response(null, { status, headers: status === 302 ? { location: "https://shop.example.net/sorry" } : {} }); }) as typeof globalThis.fetch; expect(await actOf(slug, fake, { kind: "unsubscribe", to: "bills@example.net", link: "https://shop.example.net/u/1" }, web(200))).toEqual({ ok: true, how: "one_click" }); expect(posts[0]).toEqual({ url: "https://shop.example.net/u/1", body: "List-Unsubscribe=One-Click" }); expect(await actOf(slug, fake, { kind: "unsubscribe", to: "bills@example.net", link: "https://shop.example.net/u/1" }, web(302))).toEqual({ ok: true, how: "trash_on_arrival" }); const blockedRows = await runInDurableObject(stub(slug), (_i, state) => JSON.stringify(state.storage.sql.exec("SELECT * FROM mail_fetch_blocked").toArray())); expect(blockedRows).not.toContain("example.net"); // What arrives from them now goes to Trash, unkept. all().push(shop(26)); await dueNow(slug); const before = (await rows(slug, "email")).length; await passOf(slug, fake); expect((await rows(slug, "email")).length).toBe(before); expect(all().some((m) => m.uid === 26)).toBe(false); expect(fake.boxes.get("[Gmail]/Trash")!.messages.some((m) => m.raw.includes("bill.26@"))).toBe(true); // The route: the owner's own phone alone, and only for an account Cotton fetches. expect((await http(slug, "POST", "/v1/mail/fetch/act", { account: "acct-other", kind: "trash", email: heron }, phone)).body).toMatchObject({ code: "not_fetched" }); expect((await http(slug, "POST", "/v1/mail/fetch/act", { account: "acct-fetch", kind: "page" }, phone)).body).toEqual({ ok: false, error: "Not something mail can do." }); }, 300_000); it("on a plain server: archive moves to its Archive, a sender's Inbox archived after its count, and a server that cannot move moves nothing", async () => { const slug = "mail-fetch-acts-plain"; await given(slug, "tam@example.test"); const ivo = (uid: number) => ({ uid, flags: [], raw: message({ from: "Ivo ", to: "tam@example.test", id: `q.${uid}@example.org`, subject: `Quarry ${uid}`, body: `Rope ${uid}.` }) }); const fake = new FakeImap({ gmail: false, user: "tam@example.test", password: PASSWORD }) .box("INBOX", { validity: 3, messages: [ivo(1), ivo(2), ivo(3)] }) .box("Archive", { validity: 4, flags: ["\\Archive"], messages: [] }) .box("Trash", { validity: 5, flags: ["\\Trash"], messages: [] }); await passOf(slug, fake); expect(await actOf(slug, fake, { kind: "archive", email: await emailOf(slug, 1) })).toEqual({ ok: true }); expect(fake.boxes.get("Archive")!.messages.length).toBe(1); const counted = await actOf(slug, fake, { kind: "sender_archive", to: "ivo@example.org" }); expect(counted).toEqual({ ok: false, error: "2 emails from them are in your Inbox. Try again to archive those 2.", count: 2, uid_validity: 3, uid_below: 4 }); expect(await actOf(slug, fake, { kind: "sender_archive", to: "ivo@example.org", count: 2, uid_validity: 3, uid_below: 4 })).toEqual({ ok: true, moved: 2 }); expect(fake.boxes.get("INBOX")!.messages.length).toBe(0); fake.canMove = false; expect(await actOf(slug, fake, { kind: "sender_trash", to: "ivo@example.org" })).toEqual({ ok: false, error: "This mail server can't move mail without erasing it, so nothing was moved." }); expect(await actOf(slug, fake, { kind: "sender_count", to: "not an address" })).toEqual({ ok: false, error: '"not an address" is not an email address.' }); }, 300_000); }); // ── sending from a mailbox given to Cotton (route "smtp", src/mail/smtp.ts) ── describe("sending from a mailbox Cotton reads", () => { const sendOf = (slug: string, dial: Parameters[1], body: Record) => runInDurableObject(stub(slug), (instance: Business) => instance.mailSendAsk(body, dial)); const both = (imap: FakeImap, smtp: FakeSmtp) => (async (host: string, port: number, tls: boolean) => (host.startsWith("smtp.") ? smtp.session(host) : imap.dial(host, port, tls))) as Parameters[1]; const draft = (id: string, from: string) => ({ draft: id, route: "smtp", from, to: ["ivo@example.org"], cc: [], bcc: ["quiet@example.org"], subject: "Ropes for the quarry", text: "Bring two coils.\n.\nAnd the lamp.", attachments: [{ name: "map.txt", mime: "text/plain", content: btoa("COPPER MAP") }] }); it("goes over the mailbox's own SMTP server with its held password, Bcc only on the envelope, a file attached, once per draft, its copy in Sent", async () => { const slug = "mail-fetch-send-plain"; const phone = await given(slug, "tam@example.test"); const imap = new FakeImap({ gmail: false, user: "tam@example.test", password: PASSWORD }).box("INBOX", { validity: 3, messages: [] }).box("Sent", { validity: 6, flags: ["\\Sent"], messages: [] }); const smtp = new FakeSmtp({ user: "tam@example.test", password: PASSWORD }); const sent = await sendOf(slug, both(imap, smtp), draft("d-1", "tam@example.test")); expect(sent).toMatchObject({ draft: "d-1", state: "sent" }); expect(sent.messageId).toMatch(/^<[0-9a-f-]+@example\.test>$/); expect(smtp.hosts).toEqual(["smtp.example.test"]); expect(smtp.taken.length).toBe(1); const taken = smtp.taken[0]!; expect(taken).toMatchObject({ user: "tam@example.test", from: "tam@example.test" }); expect(taken.recipients.sort()).toEqual(["ivo@example.org", "quiet@example.org"]); expect(taken.message).not.toContain("quiet@"); expect(taken.message).toContain('Content-Disposition: attachment; filename="map.txt"'); expect(taken.message).toContain(btoa("COPPER MAP")); expect(taken.message).toContain(`Message-ID: ${sent.messageId}`); // Its copy in the mailbox's Sent, read; and the sealed Sent row. const copy = imap.boxes.get("Sent")!.messages; expect(copy.length).toBe(1); expect(copy[0]!.flags).toEqual(["\\Seen"]); expect(copy[0]!.raw).toContain(String(sent.messageId)); const mine = (await opened(slug)).find((m) => m.direction === "out"); expect(mine).toMatchObject({ account: "tam@example.test", unread: false, in_inbox: false }); expect(String(mine!.body)).toContain("Bring two coils."); // The same draft again is answered by the ledger: nothing goes twice. expect(await sendOf(slug, both(imap, smtp), draft("d-1", "tam@example.test"))).toMatchObject({ state: "sent", messageId: sent.messageId }); expect(smtp.taken.length).toBe(1); // Only from an address Cotton reads. expect((await http(slug, "POST", "/v1/mail/send", draft("d-2", "other@example.test"), phone)).body).toMatchObject({ code: "not_fetched" }); }, 300_000); it("on Gmail keeps no second copy in Sent; a refused password or recipient fails in words, and Retry sends", async () => { const slug = "mail-fetch-send-gmail"; await given(slug, "mira@example.test"); const imap = new FakeImap({ gmail: true, user: "mira@example.test", password: PASSWORD }).box("[Gmail]/All Mail", { validity: 9, flags: ["\\All"], messages: [] }).box("[Gmail]/Sent Mail", { validity: 10, flags: ["\\Sent"], messages: [] }); const wrong = new FakeSmtp({ user: "mira@example.test", password: "a-different-invented-password" }); expect(await sendOf(slug, both(imap, wrong), draft("g-1", "mira@example.test"))).toEqual({ draft: "g-1", state: "failed", code: "smtp_refused", said: "Your mail server refused the password. Give it again in Post." }); const smtp = new FakeSmtp({ user: "mira@example.test", password: PASSWORD }); smtp.refuse = "ivo@example.org"; expect(await sendOf(slug, both(imap, smtp), draft("g-1", "mira@example.test"))).toMatchObject({ state: "failed", code: "smtp_recipient" }); smtp.refuse = null; expect(await sendOf(slug, both(imap, smtp), draft("g-1", "mira@example.test"))).toMatchObject({ state: "sent" }); expect(smtp.taken.length).toBe(1); expect(imap.boxes.get("[Gmail]/Sent Mail")!.messages.length).toBe(0); }, 300_000); }); // ── new mail in seconds: IDLE held after a pass (src/mail/fetcher.ts `watch`) ── describe("new mail in seconds on a mailbox Cotton reads", () => { const watchOf = (slug: string, fake: FakeImap, ms: number) => runInDurableObject(stub(slug), (instance: Business) => instance.fetchMailWatch(fake.dial, ms)); const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); const note = (uid: number, words: string) => ({ uid, msgid: `179000000000000${1000 + uid}`, labels: ["\\Inbox"], flags: [], raw: message({ from: "Orrin ", to: "mira@example.test", id: `note.${uid}@example.org`, subject: `Note ${uid}`, body: words }) }); it("holds IDLE once read up to date, reads new mail the moment the server says it, and stops at once when the password is removed", async () => { const slug = "mail-fetch-idle"; const phone = await given(slug, "mira@example.test"); const fake = new FakeImap({ gmail: true, user: "mira@example.test", password: PASSWORD }).box("[Gmail]/All Mail", { validity: 9, flags: ["\\All"], messages: [note(1, "Older note.")] }); await passOf(slug, fake); expect((await rows(slug, "email")).length).toBe(1); const started = Date.now(); const watching = watchOf(slug, fake, 20_000); await wait(1500); // Delivered from inside the object: the fake's socket lives there, as a real one would. await runInDurableObject(stub(slug), () => fake.deliver("[Gmail]/All Mail", note(2, "The heron is back."))); // Read within seconds of arriving, long before the window's end. let landed = 0; for (let i = 0; i < 40 && landed < 2; i++) { await wait(250); landed = (await rows(slug, "email")).length; } expect(landed).toBe(2); expect(Date.now() - started).toBeLessThan(15_000); expect(fake.said).toContain("IDLE"); // Removing the password closes the IDLE connection: the watch ends now, not at its window's end. expect((await http(slug, "DELETE", "/v1/mail/fetch", { account: "acct-fetch" }, phone)).status).toBe(200); expect(await watching).toBe(1); expect(Date.now() - started).toBeLessThan(18_000); expect(fake.closed).toBe(fake.opened); }, 300_000); it("asks a server without IDLE again each minute or at the window's end", async () => { const slug = "mail-fetch-noidle"; await given(slug, "mira@example.test"); const fake = new FakeImap({ gmail: true, user: "mira@example.test", password: PASSWORD }).box("[Gmail]/All Mail", { validity: 9, flags: ["\\All"], messages: [note(1, "Older note.")] }); fake.canIdle = false; await passOf(slug, fake); fake.deliver("[Gmail]/All Mail", note(2, "Second note.")); expect(await watchOf(slug, fake, 1500)).toBe(1); expect(fake.said).not.toContain("IDLE"); }, 300_000); }); describe("a mail server Cotton cannot reach", () => { it("logs unreachable, never the host, when the connection never opens", async () => { const slug = "mail-fetch-unreachable"; const phone = await given(slug, "mira@example.test"); // The real socket, to a name that never resolves (RFC 6761 .invalid). await runInDurableObject(stub(slug), (instance: Business) => instance.fetchMailPass((_host, port, tls) => dial("imap.nowhere.invalid", port, tls))); const log = await http<{ log: { kind: string; code: string | null }[] }>(slug, "GET", "/v1/mail/fetch/log?account=acct-fetch", undefined, phone); expect(log.body.log[0]).toMatchObject({ kind: "failed", code: "unreachable" }); expect(JSON.stringify(log.body)).not.toContain("nowhere"); }, 300_000); });