/** * COTTON FETCHES (Post CONTRACT "The Worker", build step 7b, row 13): a mailbox the person gives to Cotton rather * than to their Mac. The object holds the mailbox's password, reads it over IMAP, keeps each message sealed at * arrival exactly as own-domain mail is (src/mail/mail.ts `arrive`), carries out the person's acts on it and sends * from it over SMTP. * * THE PASSWORD. Kept encrypted under MAIL_FETCH_KEY, a Worker secret used for nothing else (AES-GCM, bound to the * database and the account), in `mail_fetch_account`. It is never written to a log, never answered by any route and * never told to the Directory. Removing it deletes the row at once and closes the socket. * * THE LOG (`mail_fetch_log`) holds when, which account, what (fetched, failed, stopped), how many and a code: never * an address, a subject, a word or a password. * * POST /v1/mail/fetch { account, address, host, port, password } → { account, state } (owner) * DELETE /v1/mail/fetch { account } → { removed_at } * GET /v1/mail/fetch/state?account= → { state, since, last_at } * GET /v1/mail/fetch/log?account=&limit= → { log: [{ at, account, kind, count, code, ref }] } * * `ref` (JOBS OUT 3): which message a `failed / too_large` entry skipped, its UID and message id sealed at arrival to * the owner's arrival key (`a2:`, src/arrival.ts sealValueAtArrival, bound to `mail_fetch_log:`), so the phone * can name it and the object cannot; null on every other entry. A failure the same as the account's newest entry * (no_arrival_key every five minutes) updates that entry's time instead of pushing the log out. * * Times are ISO strings. `state`: live (reading), idle (held, waiting for its next read), stopped (removed or * never given), refused (the server refused the password: given again, it reads again). */ import { devWorker, type Env } from "../env.ts"; import { refuse } from "../http.ts"; export const SCHEMA = ` CREATE TABLE IF NOT EXISTS mail_fetch_account (account TEXT PRIMARY KEY, address TEXT NOT NULL, host TEXT NOT NULL, port INTEGER NOT NULL, password_enc TEXT NOT NULL, since INTEGER NOT NULL, state TEXT NOT NULL, last_at INTEGER, cursor TEXT); CREATE TABLE IF NOT EXISTS mail_fetch_log (seq INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, account TEXT NOT NULL, kind TEXT NOT NULL, count INTEGER NOT NULL DEFAULT 0, code TEXT); CREATE INDEX IF NOT EXISTS mail_fetch_log_by_account ON mail_fetch_log (account, seq); CREATE TABLE IF NOT EXISTS mail_fetch_trash (account TEXT NOT NULL, validity INTEGER NOT NULL, uid INTEGER NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (account, validity, uid)); CREATE TABLE IF NOT EXISTS mail_fetch_index (account TEXT NOT NULL, email_id TEXT NOT NULL, box TEXT NOT NULL, validity INTEGER NOT NULL, uid INTEGER NOT NULL, msgid TEXT, PRIMARY KEY (account, email_id)); CREATE TABLE IF NOT EXISTS mail_fetch_blocked (account TEXT NOT NULL, mark TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (account, mark)); `; export type FetchState = "live" | "idle" | "stopped" | "refused"; export type LogKind = "fetched" | "failed" | "stopped"; /** The log keeps this many lines an account; older ones go. */ export const LOG_KEEP = 1000; const ACCOUNT = /^[A-Za-z0-9._:@+-]{1,128}$/; const HOST = /^(?=.{1,253}$)([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}$/; const LOOPBACK = "127.0.0.1"; export interface FetchHost { sql: SqlStorage; env: Env; databaseId: string; now(): number; /** Close any socket this account holds open (the fetcher's). */ close(account: string): void; } export interface Held { account: string; address: string; host: string; port: number; since: number; state: FetchState; last_at: number | null; cursor: string | null; } function key(env: Env): Promise { const raw = env.MAIL_FETCH_KEY; if (!raw) refuse(503, "fetch_unavailable", "this Cotton server holds no key for mailbox passwords yet: Cotton cannot fetch mail here"); let bytes: Uint8Array; try { bytes = Uint8Array.from(atob(raw.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0)); } catch { refuse(503, "fetch_unavailable", "this Cotton server's key for mailbox passwords is not a key"); } if (bytes.length !== 32) refuse(503, "fetch_unavailable", "this Cotton server's key for mailbox passwords is not 32 bytes"); return crypto.subtle.importKey("raw", bytes, "AES-GCM", false, ["encrypt", "decrypt"]); } const aad = (databaseId: string, account: string) => new TextEncoder().encode(`cotton-mail-fetch-v1\n${databaseId}\n${account}`); const b64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); const unb64 = (text: string) => Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0)); /** The password sealed for one account: `f1:` the nonce and the body. */ export async function sealPassword(env: Env, databaseId: string, account: string, password: string): Promise { const nonce = crypto.getRandomValues(new Uint8Array(12)); const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: aad(databaseId, account) }, await key(env), new TextEncoder().encode(password))); const out = new Uint8Array(12 + body.length); out.set(nonce); out.set(body, 12); return `f1:${b64(out)}`; } /** * A sender on this account's own list (an unsubscribe without RFC 8058's one-click), kept as an HMAC under * MAIL_FETCH_KEY so the object holds no sender's address: what arrives from them goes to Trash. */ export async function senderMark(env: Env, databaseId: string, account: string, address: string): Promise { const raw = env.MAIL_FETCH_KEY; if (!raw) refuse(503, "fetch_unavailable", "this Cotton server holds no key for mailbox passwords yet: Cotton cannot fetch mail here"); // Its own key, derived from MAIL_FETCH_KEY: the password key is never used for anything else. const ikm = await crypto.subtle.importKey("raw", unb64(raw), "HKDF", false, ["deriveKey"]); const k = await crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(32), info: new TextEncoder().encode("cotton-mail-sender-v1") }, ikm, { name: "HMAC", hash: "SHA-256", length: 256 }, false, ["sign"]); const sig = new Uint8Array(await crypto.subtle.sign("HMAC", k, new TextEncoder().encode(`${databaseId}\n${account}\n${address.trim().toLowerCase()}`))); return b64(sig); } /** The password opened, for the fetcher alone; never answered, never logged. */ export async function openPassword(env: Env, databaseId: string, account: string, sealed: string): Promise { if (!sealed.startsWith("f1:")) throw new Error("not a mailbox password"); const bytes = unb64(sealed.slice(3)); const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12), additionalData: aad(databaseId, account) }, await key(env), bytes.slice(12)); return new TextDecoder().decode(plain); } function accountOf(raw: unknown): string { return typeof raw === "string" && ACCOUNT.test(raw) ? raw : refuse(400, "bad_account", "account: the mail account's id"); } /** A mail server's host: a name, or (on the dev and test Workers alone) this machine's loopback for a fake server. */ function hostOf(env: Env, raw: unknown): string { const host = typeof raw === "string" ? raw.trim().toLowerCase() : ""; if (HOST.test(host)) return host; if (host === LOOPBACK && devWorker(env)) return host; refuse(400, "bad_host", "host: the mail server's name, such as imap.gmail.com"); } /** `POST /v1/mail/fetch`: the password held (encrypted), the account live from the next alarm. */ export async function give(host: FetchHost, body: Record): Promise<{ account: string; state: FetchState }> { const account = accountOf(body.account); const address = typeof body.address === "string" && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(body.address.trim()) ? body.address.trim().toLowerCase() : refuse(400, "bad_address", "address: the mailbox's address"); const server = hostOf(host.env, body.host); const port = body.port === undefined ? 993 : Number.isInteger(body.port) && (body.port as number) >= 1 && (body.port as number) <= 65535 ? (body.port as number) : refuse(400, "bad_port", "port: 1 to 65535 (993 for IMAP over TLS)"); const password = typeof body.password === "string" && body.password.length > 0 && body.password.length <= 1024 ? body.password : refuse(400, "bad_password", "password: the mailbox's password or app password"); const sealed = await sealPassword(host.env, host.databaseId, account, password); const now = host.now(); host.sql.exec( "INSERT INTO mail_fetch_account (account, address, host, port, password_enc, since, state, last_at, cursor) VALUES (?, ?, ?, ?, ?, ?, 'idle', NULL, NULL) ON CONFLICT (account) DO UPDATE SET address = excluded.address, host = excluded.host, port = excluded.port, password_enc = excluded.password_enc, state = 'idle'", account, address, server, port, sealed, now, ); return { account, state: "idle" }; } /** `DELETE /v1/mail/fetch`: the row gone at once, the socket closed. */ export function remove(host: FetchHost, body: Record): { removed_at: string } { const account = accountOf(body.account); host.close(account); host.sql.exec("DELETE FROM mail_fetch_account WHERE account = ?", account); host.sql.exec("DELETE FROM mail_fetch_index WHERE account = ?", account); host.sql.exec("DELETE FROM mail_fetch_blocked WHERE account = ?", account); host.sql.exec("DELETE FROM mail_fetch_trash WHERE account = ?", account); log(host, account, "stopped", 0, "removed"); return { removed_at: new Date(host.now()).toISOString() }; } export function held(sql: SqlStorage, account: string): Held | null { const r = sql.exec<{ account: string; address: string; host: string; port: number; since: number; state: string; last_at: number | null; cursor: string | null }>("SELECT account, address, host, port, since, state, last_at, cursor FROM mail_fetch_account WHERE account = ?", account).toArray()[0]; return r ? { account: r.account, address: r.address, host: r.host, port: Number(r.port), since: Number(r.since), state: r.state as FetchState, last_at: r.last_at === null ? null : Number(r.last_at), cursor: r.cursor } : null; } export function accounts(sql: SqlStorage): Held[] { return sql.exec<{ account: string }>("SELECT account FROM mail_fetch_account ORDER BY account").toArray().map((r) => held(sql, r.account)!); } /** The sealed password, for the fetcher alone. */ export function passwordEnc(sql: SqlStorage, account: string): string | null { return sql.exec<{ password_enc: string }>("SELECT password_enc FROM mail_fetch_account WHERE account = ?", account).toArray()[0]?.password_enc ?? null; } /** `GET /v1/mail/fetch/state`. */ export function state(sql: SqlStorage, raw: unknown): { state: FetchState; since: string | null; last_at: string | null } { const h = held(sql, accountOf(raw)); if (!h) return { state: "stopped", since: null, last_at: null }; return { state: h.state, since: new Date(h.since).toISOString(), last_at: h.last_at === null ? null : new Date(h.last_at).toISOString() }; } export function setState(host: Pick, account: string, next: FetchState, touched = false): void { host.sql.exec(`UPDATE mail_fetch_account SET state = ?${touched ? ", last_at = ?" : ""} WHERE account = ?`, ...(touched ? [next, host.now(), account] : [next, account])); } export function setCursor(sql: SqlStorage, account: string, cursor: string | null): void { sql.exec("UPDATE mail_fetch_account SET cursor = ? WHERE account = ?", cursor, account); } /** The log's later columns, added the additive way to a table an earlier build made (JOBS OUT 3, L-a). */ export function ensureColumns(sql: SqlStorage): void { const have = new Set(sql.exec<{ name: string }>("PRAGMA table_info(mail_fetch_log)").toArray().map((c) => c.name)); if (!have.has("ref_id")) sql.exec("ALTER TABLE mail_fetch_log ADD COLUMN ref_id TEXT"); if (!have.has("ref")) sql.exec("ALTER TABLE mail_fetch_log ADD COLUMN ref TEXT"); } /** One line: never an address, a subject, a word or a password; `ref` only sealed (see above). */ export function log(host: Pick, account: string, kind: LogKind, count: number, code: string | null, ref: { id: string; sealed: string } | null = null): void { if (kind === "failed" && code !== null && ref === null) { // The same failure again: its entry's time moves, and the log keeps its history. const newest = host.sql.exec<{ seq: number; kind: string; code: string | null; ref: string | null }>("SELECT seq, kind, code, ref FROM mail_fetch_log WHERE account = ? ORDER BY seq DESC LIMIT 1", account).toArray()[0]; if (newest && newest.kind === "failed" && newest.code === code && newest.ref === null) { host.sql.exec("UPDATE mail_fetch_log SET at = ?, count = ? WHERE seq = ?", host.now(), count, newest.seq); return; } } host.sql.exec("INSERT INTO mail_fetch_log (at, account, kind, count, code, ref_id, ref) VALUES (?, ?, ?, ?, ?, ?, ?)", host.now(), account, kind, count, code, ref?.id ?? null, ref?.sealed ?? null); host.sql.exec("DELETE FROM mail_fetch_log WHERE account = ? AND seq <= (SELECT seq FROM mail_fetch_log WHERE account = ? ORDER BY seq DESC LIMIT 1 OFFSET ?)", account, account, LOG_KEEP); } /** `GET /v1/mail/fetch/log`: newest first. */ export function readLog(sql: SqlStorage, rawAccount: unknown, rawLimit: unknown): { log: { at: string; account: string; kind: LogKind; count: number; code: string | null; ref: { id: string; sealed: string } | null }[] } { const account = accountOf(rawAccount); const n = Number(rawLimit ?? 50); const limit = Number.isInteger(n) && n >= 1 ? Math.min(n, 500) : 50; return { log: sql .exec<{ at: number; account: string; kind: string; count: number; code: string | null; ref_id: string | null; ref: string | null }>("SELECT at, account, kind, count, code, ref_id, ref FROM mail_fetch_log WHERE account = ? ORDER BY seq DESC LIMIT ?", account, limit) .toArray() .map((r) => ({ at: new Date(Number(r.at)).toISOString(), account: r.account, kind: r.kind as LogKind, count: Number(r.count), code: r.code, ref: r.ref_id && r.ref ? { id: r.ref_id, sealed: r.ref } : null })), }; }