/** * COTTON FETCHES, the acts (Post CONTRACT row 13): the person's acts on a mailbox given to Cotton, done in that * mailbox by the object, the way the Mac does them for a mailbox it reads (crates/cotton-mac/src/mail/acts.rs and * trash.rs: the same kinds, the same count-first rule, the same words). * * POST /v1/mail/fetch/act { account, kind, email?, to?, target?, link?, count?, moved?, uid_validity?, uid_below? } * → { ok, error?, count?, moved?, uid_validity?, uid_below?, how?, gone? } * * The phone hands the act to the object directly, rather than as an outbox row: an outbox row's kind, target and * sender are sealed, and the object can never open the email row an act names. Instead the fetcher keeps, for each * message it lands, a clear index of where it is (`mail_fetch_index`: the email row's id, the mailbox, its * UIDVALIDITY, the UID and Gmail's id; numbers only), and an act names the email by its row id. Nothing of an act is * kept: its sender's address lives only inside the request. * * | kind | takes | does | * |---|---|---| * | `mark_read`, `mark_unread` | `email` | set or clear `\Seen` | * | `archive` | `email` | Gmail: the `\Inbox` label off, read back; another server: moved to its `\Archive` | * | `trash` | `email` | moved to the account's Trash | * | `sender_count` | `to`, `target`? | theirs in the mailbox (`target: "inbox"`: in the Inbox), read only: the count and its numbering | * | `sender_trash` | `to`, `uid_validity`, `uid_below`, `count` | the set counted, moved to Trash; with no numbering it counts and asks first | * | `sender_archive` | `to`, the same | the set counted in the Inbox, out of it, read back | * | `unsubscribe` | `to`, `link`? | RFC 8058's one-click POST to `link` when given; else the sender joins this account's own list and what arrives from them goes to Trash | * * Never `\Deleted`, never EXPUNGE: what goes to Trash stays there for the provider's own time. */import * as fetch from"./fetch.ts";importtype { FetcherHost } from"./fetcher.ts";import { connect } from"./fetcher.ts";import { ImapError, typeImap } from"./imap.ts";import { refuse } from"../http.ts";/** UIDs moved or stored per command. */exportconst BATCH = 200;const HEADER_PAGE = 500;exportconst KINDS = ["mark_read", "mark_unread", "archive", "trash", "sender_count", "sender_trash", "sender_archive", "unsubscribe"] asconst;exporttypeKind = (typeof KINDS)[number];/** The Mac's words (trash.rs `TrashError`), for the same failures. */exportconst WORDS = { gone: "This email is no longer in your mail.", noTrash: "This mail account has no Trash to move to.", cannotMove: "This mail server can't move mail without erasing it, so nothing was moved.", renumbered: "The mailbox was renumbered since the count. Count again.", noArchive: "This mail account has no Archive to move to.", moreThanCounted: "Your mail holds more from them than was counted, so nothing was moved. Count again.", keptIt: "Gmail kept it in your Inbox.", notAnAct: "Not something mail can do.", refused: "Your mail server refused the password. Give it again in Post.", unreachable: "Cotton couldn't reach your mail server. Try again.", notAnAddress: (text: string) => `"${text}" is not an email address.`, askTrash: (n: number) => (n === 1 ? "Your mail holds 1 email from them. Try again to move it to Trash." : `Your mail holds ${n} emails from them. Try again to move those ${n} to Trash.`), askArchive: (n: number) => (n === 1 ? "1 email from them is in your Inbox. Try again to archive it." : `${n} emails from them are in your Inbox. Try again to archive those ${n}.`), kept: (n: number) => `Gmail kept ${n} of them in your Inbox.`,};/** What `sent_external_id` says of an unsubscribe, as the Mac writes it. */exportconst ONE_CLICK = "one_click";exportconst TRASH_ON_ARRIVAL = "trash_on_arrival";exportinterfaceActAnswer { ok: boolean; error?: string; count?: number; moved?: number; uid_validity?: number; uid_below?: number; how?: string;/** The email rows (their ids) of the mail a sender's Trash moved, as far as the fetcher's index knows them. */ gone?: string[];}classSaidextendsError {readonly answer: Omit<ActAnswer, "ok">; constructor(words: string, more: Omit<ActAnswer, "ok" | "error"> = {}) {super(words);this.answer = { error: words, ...more }; }}/** An address as it is compared: trimmed and lowercased; refused unless it is one address (trash.rs `address_of`). */exportfunction addressOf(text: string): string {const address = text.trim().toLowerCase();const parts = address.split("@");// eslint-disable-next-line no-control-regexconst ok = address.length <= 320 && parts.length === 2 && parts[0]!.length > 0 && parts[1]!.length > 0 && !/[\s\x00-\x1f"\\<>(),;]/.test(address);if (!ok) thrownewSaid(WORDS.notAnAddress(text.trim()));return address;}/** The address in a From header: inside its angle brackets, else the word with an `@` (trash.rs `from_address`). */exportfunction fromAddress(header: string): string | null {const unfolded = header.replace(/\r?\n[ \t]+/g, " ");const line = /^from:(.*)$/im.exec(unfolded)?.[1] ?? "";const angled = /<([^<>]+)>/.exec(line)?.[1];const word = angled ?? line.split(/[\s,;]+/).find((w) => w.includes("@"));return word ? word.trim().replace(/^"|"$/g, "").toLowerCase() : null;}/** The header block of a raw message (to the first blank line). */exportfunction headerBlock(raw: Uint8Array): string {const text = newTextDecoder().decode(raw.subarray(0, Math.min(raw.length, 65536)));const end = text.search(/\r?\n\r?\n/);return end < 0 ? text : text.slice(0, end);}function quote(text: string): string {return`"${text.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;}/** Where a sender's mail is read from and moved to (trash.rs `place`). */asyncfunction place(imap: Imap): Promise<{ mailbox: string; trash: string; copy: boolean }> {const uses = await imap.uses();const mailbox = imap.gmail ? (uses.all ?? "INBOX") : "INBOX";const trash = uses.trash ?? (imap.gmail ? "[Gmail]/Trash" : null);if (!trash) thrownewSaid(WORDS.noTrash);const copy = imap.capabilities.has("MOVE") ? false : imap.gmail ? true : null;if (copy === null) thrownewSaid(WORDS.cannotMove);return { mailbox, trash, copy };}/** The UIDs below `below` (all, at 0) whose From is exactly `address`, in the mailbox open now (trash.rs `matching`). */asyncfunction matching(imap: Imap, address: string, below: number): Promise<number[]> {const hits = (await imap.search(`FROM ${quote(address)}`)).filter((u) => below === 0 || u < below);const out: number[] = [];for (let i = 0; i < hits.length; i += HEADER_PAGE) {for (const [uid, header] ofawait imap.headers(hits.slice(i, i + HEADER_PAGE), ["FROM"])) if (fromAddress(header) === address) out.push(uid); }return [...newSet(out)].sort((a, b) => a - b);}/** Of `uids` in the Gmail mailbox open now, those that carry the Inbox label, by their labels. */asyncfunction labelledInbox(imap: Imap, uids: number[]): Promise<number[]> {const out: number[] = [];for (let i = 0; i < uids.length; i += BATCH) {for (const f ofawait imap.fetch(uids.slice(i, i + BATCH), false)) if (f.labels.some((l) => l.replace(/^\\/, "").toLowerCase() === "inbox")) out.push(f.uid); }return out.sort((a, b) => a - b);}/** Where a sender's Inbox mail is read and archived: Gmail's All Mail; any other server's INBOX, moved to its \Archive. */asyncfunction inboxSpot(imap: Imap): Promise<{ mailbox: string; archive: string | null }> {const uses = await imap.uses();if (imap.gmail) return { mailbox: uses.all ?? "INBOX", archive: null };if (!uses.archive) thrownewSaid(WORDS.noArchive);if (!imap.capabilities.has("MOVE")) thrownewSaid(WORDS.cannotMove);return { mailbox: "INBOX", archive: uses.archive };}asyncfunction inInbox(imap: Imap, address: string, below: number): Promise<number[]> {const theirs = await matching(imap, address, below);return imap.gmail ? labelledInbox(imap, theirs) : theirs;}interfaceIndexed { box: string; validity: number; uid: number; msgid: string | null;}function indexed(sql: SqlStorage, account: string, email: string): Indexed | null {const r = sql.exec<{ box: string; validity: number; uid: number; msgid: string | null }>("SELECT box, validity, uid, msgid FROM mail_fetch_index WHERE account = ? AND email_id = ?", account, email).toArray()[0];return r ? { box: r.box, validity: Number(r.validity), uid: Number(r.uid), msgid: r.msgid } : null;}/** The UID of the email `email` names, in `mailbox` opened to be written: by Gmail's id, else by its UID while the numbering holds. */asyncfunction locate(imap: Imap, at: Indexed | null, mailbox: string): Promise<number> {const selected = await imap.select(mailbox);if (!at) thrownewSaid(WORDS.gone);let hits: number[] = [];if (imap.gmail && at.msgid && /^\d+$/.test(at.msgid)) hits = await imap.search(`X-GM-MSGID ${at.msgid}`);elseif (at.box === mailbox && at.validity === selected.uidvalidity) hits = (await imap.search(`UID ${at.uid}`)).filter((u) => u === at.uid);const uid = hits.length ? Math.max(...hits) : 0;if (!uid) thrownewSaid(WORDS.gone);return uid;}function whole(v: unknown): number {returntypeof v === "number" && Number.isInteger(v) && v > 0 ? v : 0;}/** RFC 8058's one-click: a POST of `List-Unsubscribe=One-Click` to the https link; only 307 and 308 are followed (they keep the POST), to https, at most five. */exportasyncfunction oneClick(link: string, post: typeof globalThis.fetch = globalThis.fetch): Promise<boolean> {let url: URL;try { url = new URL(link); } catch {returnfalse; }for (let hops = 0; hops <= 5; hops++) {if (url.protocol !== "https:") returnfalse;let r: Response;try { r = await post(url.toString(), { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", "user-agent": "Cotton" }, body: "List-Unsubscribe=One-Click", signal: AbortSignal.timeout(20_000) }); } catch {returnfalse; }if (r.status >= 200 && r.status < 300) returntrue;if (r.status !== 307 && r.status !== 308) returnfalse;const next = r.headers.get("location");if (!next) returnfalse; url = new URL(next, url); }returnfalse;}/** `POST /v1/mail/fetch/act`: one act, done in the mailbox inside the request. */exportasyncfunction act(host: FetcherHost, body: Record<string, unknown>, post?: typeof globalThis.fetch): Promise<ActAnswer> {const account = typeof body.account === "string" ? body.account : refuse(400, "bad_account", "account: the mail account's id");const kind = body.kind asKind;if (!KINDS.includes(kind)) return { ok: false, error: WORDS.notAnAct };const held = fetch.held(host.sql, account) ?? refuse(404, "not_fetched", "Cotton does not fetch this mail account");const email = typeof body.email === "string" ? body.email : "";if (["mark_read", "mark_unread", "archive", "trash"].includes(kind) && !email) refuse(400, "bad_args", "email: the email row's id");let imap: Imap | null = null;try {const to = kind.startsWith("sender_") || (kind === "unsubscribe" && typeof body.to === "string") ? addressOf(String(body.to ?? "")) : "";if (kind === "unsubscribe") {const link = typeof body.link === "string" ? body.link : "";if (link && (await oneClick(link, post))) return { ok: true, how: ONE_CLICK };if (!to) thrownewSaid(WORDS.notAnAddress("")); host.sql.exec("INSERT OR IGNORE INTO mail_fetch_blocked (account, mark, at) VALUES (?, ?, ?)", account, await fetch.senderMark(host.env, host.databaseId, account, to), host.now());return { ok: true, how: TRASH_ON_ARRIVAL }; } imap = await connect(host, held);const at = email ? indexed(host.sql, account, email) : null;switch (kind) {case"trash": {const p = await place(imap);const uid = await locate(imap, at, p.mailbox);await imap.move(uid, p.trash, p.copy);return { ok: true }; }case"archive": {const uses = await imap.uses();if (!imap.gmail) {if (!uses.archive) thrownewSaid(WORDS.noArchive);if (!imap.capabilities.has("MOVE")) thrownewSaid(WORDS.cannotMove);await imap.move(await locate(imap, at, "INBOX"), uses.archive);return { ok: true }; }const uid = await locate(imap, at, uses.all ?? "INBOX");await imap.labels(uid, "-", ["\\Inbox"]);if ((await labelledInbox(imap, [uid])).length) thrownewSaid(WORDS.keptIt);return { ok: true }; }case"mark_read":case"mark_unread": {const mailbox = imap.gmail ? ((await imap.uses()).all ?? "INBOX") : "INBOX";await imap.store(await locate(imap, at, mailbox), kind === "mark_read" ? "+" : "-", ["\\Seen"]);return { ok: true }; }case"sender_count": {if (body.target === "inbox") {const spot = await inboxSpot(imap);const state = await imap.select(spot.mailbox, true);const uids = await inInbox(imap, to, 0);return { ok: true, count: uids.length, uid_validity: state.uidvalidity, uid_below: state.uidnext ?? 0 }; }const p = await place(imap);const state = await imap.select(p.mailbox, true);return { ok: true, count: (await matching(imap, to, 0)).length, uid_validity: state.uidvalidity, uid_below: state.uidnext ?? 0 }; }case"sender_trash": {const p = await place(imap);const validity = whole(body.uid_validity);const below = whole(body.uid_below);if (!validity || !below) {// Counted and said, nothing moved: his Try again moves exactly the set counted (ACTS-CHECK).const state = await imap.select(p.mailbox, true);const n = (await matching(imap, to, 0)).length;const fixed = { count: n, uid_validity: state.uidvalidity, uid_below: state.uidnext ?? 0 };if (!n) return { ok: true, moved: 0, ...fixed };thrownewSaid(WORDS.askTrash(n), fixed); }const state = await imap.select(p.mailbox);if (state.uidvalidity !== validity) thrownewSaid(WORDS.renumbered);const uids = await matching(imap, to, below);const before = whole(body.moved);const counted = whole(body.count);if (counted && uids.length > counted - before) thrownewSaid(WORDS.moreThanCounted);for (let i = 0; i < uids.length; i += BATCH) await imap.move(uids.slice(i, i + BATCH).join(","), p.trash, p.copy);const gone = goneEmails(host.sql, account, p.mailbox, validity, uids);return { ok: true, moved: before + uids.length, gone }; }case"sender_archive": {const spot = await inboxSpot(imap);const validity = whole(body.uid_validity);const below = whole(body.uid_below);if (!validity || !below) {const state = await imap.select(spot.mailbox, true);const n = (await inInbox(imap, to, 0)).length;const fixed = { count: n, uid_validity: state.uidvalidity, uid_below: state.uidnext ?? 0 };if (!n) return { ok: true, moved: 0, ...fixed };thrownewSaid(WORDS.askArchive(n), fixed); }const state = await imap.select(spot.mailbox);if (state.uidvalidity !== validity) thrownewSaid(WORDS.renumbered);const uids = await inInbox(imap, to, below);const counted = whole(body.count);if (counted && uids.length > counted) thrownewSaid(WORDS.moreThanCounted);for (let i = 0; i < uids.length; i += BATCH) {constset = uids.slice(i, i + BATCH).join(",");if (spot.archive) await imap.move(set, spot.archive);elseawait imap.labels(set, "-", ["\\Inbox"]); }// What the server holds now, not what it answered (SENDERS TRUE).const kept = (await inInbox(imap, to, below)).filter((u) => uids.includes(u)).length;return kept ? { ok: false, error: WORDS.kept(kept), moved: uids.length - kept } : { ok: true, moved: uids.length }; } }return { ok: false, error: WORDS.notAnAct }; } catch (e) {if (e instanceofSaid) return { ok: false, ...e.answer };if (e instanceofImapError) return { ok: false, error: e.kind === "no" && /AUTHENTICATIONFAILED|LOGIN/i.test(e.said) ? WORDS.refused : WORDS.unreachable };throw e; } finally {if (imap) await imap.logout(); }}/** The email rows of the UIDs moved, as the fetcher's index knows them (same mailbox and numbering). */function goneEmails(sql: SqlStorage, account: string, box: string, validity: number, uids: number[]): string[] {if (!uids.length) return [];return sql .exec<{ email_id: string }>("SELECT email_id FROM mail_fetch_index WHERE account = ? AND box = ? AND validity = ? AND uid IN (SELECT value FROM json_each(?))", account, box, validity, JSON.stringify(uids)) .toArray() .map((r) => r.email_id);}