/** * SENDING FROM THE PERSON'S OWN ADDRESS (OWN-MAIL.md "Sending"). The phone * opens the draft the person tapped Send on and hands that one mail here, * over TLS; the object passes it to Cloudflare's Email Sending (the * `send_email` binding EMAIL), which signs it with the domain's DKIM key, * and keeps nothing it can read: only the ledger. * * THE LEDGER (`mail_send`, one row per draft) makes a tap send once: * * sending started; a second call answers it and sends nothing * sent Cloudflare took it: its message id * failed refused before or by Cloudflare: its code and words; Retry is the person's tap * unknown started more than two minutes ago and never heard back from: the person checks and may Retry * * Cloudflare's own answer after sending (bounced, complained, failed) comes * by its event queue (src/mail/events.ts) and is kept beside the row as * `delivery`. */ import { directory } from "../directory.ts"; import type { Env } from "../env.ts"; import { refuse } from "../http.ts"; import { addressOf, domainOf, keepSent, MAX_RECIPIENTS, MAX_SEND_BYTES, SEND_UNKNOWN_MS, sentMessage, type MailHost } from "./mail.ts"; import * as fetch from "./fetch.ts"; import type { FetcherHost } from "./fetcher.ts"; import { connect } from "./fetcher.ts"; import { compose, sendOver, SMTP_PORT, smtpHost, SmtpError, type Attachment } from "./smtp.ts"; type Row = Record; /** The few things Cotton asks of a sender: Cloudflare's binding, or a test's stand-in. */ export interface MailSender { send(builder: { from: string; to: string[]; cc?: string[]; bcc?: string[]; subject: string; text: string; headers?: Record; attachments?: { disposition: "attachment"; filename: string; type: string; content: Uint8Array }[] }): Promise<{ messageId: string }>; } let standIn: MailSender | null | undefined; /** Tests only: put a sender in the binding's place (null: none at all). */ export function senderForTests(sender: MailSender | null | undefined): void { standIn = sender; } function sender(env: Env): MailSender | null { if (standIn !== undefined) return standIn; return (env.EMAIL as unknown as MailSender | undefined) ?? null; } /** What one send asks: the draft it is, and the mail the phone formed from it. */ export interface SendAsk { draft: string; from: string; to: string[]; cc: string[]; subject: string; text: string; inReplyTo: string | null; references: string[]; /** The conversation the draft was written in: the Sent copy joins it. */ thread: string | null; /** `domain`: from the person's own domain, by Cloudflare. `smtp`: from a mailbox given to Cotton, over its own SMTP server (Post CONTRACT row 13). */ route: "domain" | "smtp"; bcc: string[]; attachments: Attachment[]; } export interface SendAnswer { draft: string; state: "sending" | "sent" | "failed" | "unknown"; messageId?: string; /** The Sent copy's email row. */ email?: string; code?: string; said?: string; delivery?: string; deliveryWords?: string; } const MESSAGE_ID = /^<[^<>\s]+@[^<>\s]+>$/; function list(value: unknown, field: string): string[] { const items = value === undefined || value === null ? [] : Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : refuse(400, "bad_request", `${field} is an array of addresses`); return items .map((v) => (typeof v === "string" ? v.trim() : v)) .filter((v) => v !== "") .map((v) => addressOf(v) ?? refuse(400, "bad_address", `${String(v)} is not an email address`)); } /** The ask, read and checked: every refusal before a byte goes to Cloudflare, in words. */ export function readAsk(host: MailHost, body: Record): SendAsk { const draft = typeof body.draft === "string" && body.draft.length > 0 && body.draft.length <= 100 ? body.draft : refuse(400, "bad_request", "draft is the id of the draft being sent"); const from = addressOf(body.from) ?? refuse(400, "bad_address", "from is one of your own addresses"); const route = body.route === "smtp" ? "smtp" : body.route === undefined || body.route === null || body.route === "domain" ? "domain" : refuse(400, "bad_request", 'route is "domain" or "smtp"'); if (route === "domain") { const held = host.sql.exec("SELECT a.address FROM mail_address a JOIN mail_domain d ON d.domain = ? WHERE a.address = ? AND d.proved_at IS NOT NULL", domainOf(from), from).toArray()[0]; if (!held) refuse(403, "not_your_address", `${from} is not one of your own addresses here, so nothing can be sent from it`); } else if (!host.sql.exec("SELECT 1 FROM mail_fetch_account WHERE address = ?", from).toArray().length) { refuse(403, "not_fetched", `Cotton does not hold ${from}'s password, so it cannot send from it`); } const to = list(body.to, "to"); const cc = list(body.cc, "cc"); const bcc = list(body.bcc, "bcc"); if (to.length + cc.length + bcc.length === 0) refuse(400, "no_recipient", "a mail needs someone to go to"); if (to.length + cc.length + bcc.length > MAX_RECIPIENTS) refuse(400, "too_many_recipients", `a mail goes to at most ${MAX_RECIPIENTS} people at once`); const attachments = attachmentsOf(body.attachments); const subject = typeof body.subject === "string" ? body.subject.replace(/[\r\n]+/g, " ").slice(0, 998) : ""; const text = typeof body.text === "string" ? body.text : ""; if (new TextEncoder().encode(text).byteLength + attachments.reduce((n, a) => n + a.bytes.byteLength, 0) > MAX_SEND_BYTES) refuse(413, "too_large", "a mail is at most 25 MiB"); const inReplyTo = typeof body.inReplyTo === "string" && MESSAGE_ID.test(body.inReplyTo) ? body.inReplyTo : null; const references = Array.isArray(body.references) ? body.references.filter((r): r is string => typeof r === "string" && MESSAGE_ID.test(r)).slice(-30) : []; const thread = typeof body.thread === "string" && body.thread.length <= 100 ? body.thread : null; return { draft, from, to, cc, subject, text, inReplyTo, references, thread, route, bcc, attachments }; } /** `attachments: [{ name, mime, content: base64 }]`, decoded. */ function attachmentsOf(value: unknown): Attachment[] { if (value === undefined || value === null) return []; if (!Array.isArray(value) || value.length > 100) refuse(400, "bad_request", "attachments is a list of { name, mime, content } (content in base64)"); return value.map((a: unknown) => { const o = (a ?? {}) as Record; const name = typeof o.name === "string" && o.name.trim() ? o.name.trim().slice(0, 200) : refuse(400, "bad_request", "an attachment needs its name"); const mime = typeof o.mime === "string" && /^[\w.+-]+\/[\w.+-]+$/.test(o.mime) ? o.mime : "application/octet-stream"; if (typeof o.content !== "string") refuse(400, "bad_request", `${name}: content is the file in base64`); let bytes: Uint8Array; try { bytes = Uint8Array.from(atob(o.content.replace(/\s+/g, "")), (c) => c.charCodeAt(0)); } catch { refuse(400, "bad_request", `${name}: content is not base64`); } return { name, mime, bytes }; }); } function answerOf(r: Row): SendAnswer { return { draft: String(r.draft), state: r.state as SendAnswer["state"], ...(r.message_id ? { messageId: String(r.message_id) } : {}), ...(r.email_id ? { email: String(r.email_id) } : {}), ...(r.code ? { code: String(r.code) } : {}), ...(r.words ? { said: String(r.words) } : {}), ...(r.delivery ? { delivery: String(r.delivery) } : {}), ...(r.delivery_words ? { deliveryWords: String(r.delivery_words) } : {}), }; } /** The ledger's word on a draft, `sending` past its time said `unknown`. */ export function ledger(host: MailHost, draft: string): SendAnswer | null { const r = host.sql.exec("SELECT * FROM mail_send WHERE draft = ?", draft).toArray()[0]; if (!r) return null; if (r.state === "sending" && host.now() - Number(r.started_at) > SEND_UNKNOWN_MS) { host.sql.exec("UPDATE mail_send SET state = 'unknown', words = ? WHERE draft = ? AND state = 'sending'", WORDS.unknown, draft); return answerOf({ ...r, state: "unknown", words: WORDS.unknown }); } return answerOf(r); } export const WORDS = { unknown: "Cotton could not tell whether this went. Check Sent, then Try again if it did not.", notSetUp: "Sending from Comms is not set up on this server yet.", suppressed: "One of these addresses has refused mail from this domain before, so it was not sent.", limit: "Too much mail has gone from here today. Try again later.", domain: (domain: string) => `Sending from ${domain} is not set up yet.`, tooLarge: "This mail is too large to send.", refused: "The other side's mail server refused it.", other: (code: string) => `Cloudflare did not send it (${code}).`, notFetched: "Cotton does not hold this mailbox's password, so it cannot send from it.", smtpRefused: "Your mail server refused the password. Give it again in Post.", smtpRecipient: "Your mail server refused one of these addresses, so it was not sent.", smtpFailed: "Your mail server did not send it. Try again.", smtpUnreachable: "Cotton couldn't reach your mail server. Try again.", }; function wordsFor(code: string, from: string): string { switch (code) { case "E_RECIPIENT_SUPPRESSED": return WORDS.suppressed; case "E_RATE_LIMIT_EXCEEDED": case "E_DAILY_LIMIT_EXCEEDED": return WORDS.limit; case "E_SENDER_DOMAIN_NOT_AVAILABLE": case "E_SENDER_DOMAIN_NOT_CONFIGURED": case "E_EMAIL_SENDING_NOT_READY": case "E_SENDER_NOT_VERIFIED": return WORDS.domain(domainOf(from)); case "E_CONTENT_TOO_LARGE": return WORDS.tooLarge; case "E_DELIVERY_FAILED": return WORDS.refused; default: return WORDS.other(code); } } /** * Send one draft, once. A draft already `sending` or `sent` is answered from * the ledger and nothing goes; `failed` or `unknown` is tried again, which * only the person's own Retry asks for. */ export async function send(host: MailHost, ask: SendAsk, slug: string, fetcher?: FetcherHost): Promise { const held = ledger(host, ask.draft); if (held && (held.state === "sending" || held.state === "sent")) return held; const out = ask.route === "domain" ? sender(host.env) : null; const now = host.now(); // Taken before the first await: a second call while this one waits finds it `sending`. host.sql.exec( "INSERT INTO mail_send (draft, state, from_address, started_at) VALUES (?, 'sending', ?, ?) ON CONFLICT (draft) DO UPDATE SET state = 'sending', from_address = excluded.from_address, message_id = NULL, code = NULL, words = NULL, started_at = excluded.started_at, ended_at = NULL", ask.draft, ask.from, now, ); const fail = (code: string, words: string): SendAnswer => { host.sql.exec("UPDATE mail_send SET state = 'failed', code = ?, words = ?, ended_at = ? WHERE draft = ?", code, words, host.now(), ask.draft); return { draft: ask.draft, state: "failed", code, said: words }; }; const references = [...ask.references.filter((r) => r !== ask.inReplyTo), ...(ask.inReplyTo ? [ask.inReplyTo] : [])]; if (ask.route === "smtp") { if (!fetcher) return fail("not_set_up", WORDS.notSetUp); return sendSmtp(host, fetcher, ask, references, fail); } if (!out) return fail("not_set_up", WORDS.notSetUp); const headers: Record = {}; if (ask.inReplyTo) headers["In-Reply-To"] = ask.inReplyTo; if (references.length) headers.References = references.join(" "); let messageId: string; try { const result = await out.send({ from: ask.from, to: ask.to, ...(ask.cc.length ? { cc: ask.cc } : {}), ...(ask.bcc.length ? { bcc: ask.bcc } : {}), subject: ask.subject, text: ask.text, ...(Object.keys(headers).length ? { headers } : {}), ...(ask.attachments.length ? { attachments: ask.attachments.map((a) => ({ disposition: "attachment" as const, filename: a.name, type: a.mime, content: a.bytes })) } : {}), }); messageId = String(result.messageId); } catch (error) { const code = typeof (error as { code?: unknown }).code === "string" ? String((error as { code: string }).code) : error instanceof TypeError ? "E_VALIDATION_ERROR" : "E_UNKNOWN"; return fail(code, wordsFor(code, ask.from)); } host.sql.exec("UPDATE mail_send SET state = 'sent', message_id = ?, ended_at = ? WHERE draft = ?", messageId, host.now(), ask.draft); // Cloudflare's later word on it (a bounce) names the message id alone: the Directory says whose it was. await directory(host.env).mailSent(messageId, slug); // The Sent copy, from what passed through, sealed; it never stops the answer that it went. const headerId = MESSAGE_ID.test(messageId) ? messageId : `<${messageId.replace(/[<>\s]/g, "")}@${domainOf(ask.from)}>`; let email: string | null = null; try { email = await keepSent(host, sentMessage({ ...ask, messageId: headerId, references, at: host.now() }), ask.from, ask.thread); } catch (error) { console.error("mail: sent, but its Sent copy was not kept", String(error)); } if (email) host.sql.exec("UPDATE mail_send SET email_id = ? WHERE draft = ?", email, ask.draft); return { draft: ask.draft, state: "sent", messageId, ...(email ? { email } : {}) }; } /** * `route: "smtp"`: from a mailbox given to Cotton, over its own SMTP server with the password the object holds; * then a copy appended to its Sent where the server does not keep one itself (Gmail does), and the Sent row kept * sealed as for any send. */ async function sendSmtp(host: MailHost, fetcher: FetcherHost, ask: SendAsk, references: string[], fail: (code: string, words: string) => SendAnswer): Promise { const account = fetcher.sql.exec<{ account: string }>("SELECT account FROM mail_fetch_account WHERE address = ? ORDER BY account LIMIT 1", ask.from).toArray()[0]?.account; const held = account ? fetch.held(fetcher.sql, account) : null; const sealed = account ? fetch.passwordEnc(fetcher.sql, account) : null; if (!held || !sealed) return fail("not_fetched", WORDS.notFetched); const at = host.now(); const messageId = `<${crypto.randomUUID()}@${domainOf(ask.from)}>`; const raw = compose({ ...ask, messageId, references, at }); try { const password = await fetch.openPassword(fetcher.env, fetcher.databaseId, held.account, sealed); const wire = await fetcher.dial(smtpHost(held.host), held.host === "127.0.0.1" ? held.port : SMTP_PORT, held.host !== "127.0.0.1"); await sendOver(wire, held.address, password, { from: ask.from, recipients: [...new Set([...ask.to, ...ask.cc, ...ask.bcc])], message: raw }); } catch (error) { if (error instanceof SmtpError && error.stage === "auth") return fail("smtp_refused", WORDS.smtpRefused); if (error instanceof SmtpError && error.stage === "rcpt") return fail("smtp_recipient", WORDS.smtpRecipient); return fail(error instanceof SmtpError ? `smtp_${error.stage}` : "smtp_unreachable", error instanceof SmtpError ? WORDS.smtpFailed : WORDS.smtpUnreachable); } host.sql.exec("UPDATE mail_send SET state = 'sent', message_id = ?, ended_at = ? WHERE draft = ?", messageId, host.now(), ask.draft); // The copy in the mailbox's own Sent, where the server keeps none (Gmail keeps its own): it never stops the answer that it went. try { const imap = await connect(fetcher, held); try { if (!imap.gmail) { const sent = (await imap.uses()).sent; if (sent) await imap.append(sent, ["\\Seen"], raw); } } finally { await imap.logout(); } } catch (error) { console.error("mail: sent over SMTP, but its copy in the mailbox's Sent was not appended", error instanceof Error ? error.name : "error"); } let email: string | null = null; try { email = await keepSent(host, raw, ask.from, ask.thread); } catch (error) { console.error("mail: sent, but its Sent copy was not kept", String(error)); } if (email) host.sql.exec("UPDATE mail_send SET email_id = ? WHERE draft = ?", email, ask.draft); return { draft: ask.draft, state: "sent", messageId, ...(email ? { email } : {}) }; } /** Cloudflare's word after sending, kept beside the draft's row. */ export function delivered(host: MailHost, messageId: string, delivery: "bounced" | "complained" | "failed" | "delivered", words: string | null): boolean { const r = host.sql.exec("SELECT draft FROM mail_send WHERE message_id = ?", messageId).toArray()[0]; if (!r) return false; host.sql.exec("UPDATE mail_send SET delivery = ?, delivery_words = ? WHERE message_id = ?", delivery, words, messageId); return true; }