Email for professionals and teams
feat(jmap): Email/import for MIME-composing clients, and the header query filter (#46)
egamer24c1441cedd5dc
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7e05a23..2006a99 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -20,7 +20,7 @@ npm run preview # local OpenNext previewnpm run cf-typegen # regenerate cloudflare-env.d.ts from wrangler.jsonc```-There is no test suite and no test runner configured.+There is no test script in `package.json`; the checks under `tests/` are `node:test` files run with `node --test tests/*.test.mjs` (pass the glob — on Node 24 a bare `tests/` is read as a module path). They must not need Workers bindings, so anything that reaches D1 or R2 belongs in a script under `scripts/` run against `npm run dev` instead.`next.config.ts` sets `typescript.ignoreBuildErrors: true` and `tsconfig.json` sets `noImplicitAny: false`, so the build will not catch type errors. Run `npx tsc --noEmit` if you want real type checking.@@ -87,6 +87,10 @@ The app reaches every platform service through `getEnv()` (`src/lib/cloudflare.t`handleJmapRequest` (`src/lib/jmap/handler.ts`) owns `/jmap/*` and `/.well-known/jmap`; the Next routes under `src/app/jmap/[[...segments]]` and `src/app/.well-known/jmap` only delegate to it, and it is framework-free so it could be mounted from `worker.ts` too. Auth is an API key with the `jmap` scope via `authenticateApiRequest` (`src/lib/api/key-auth.ts`, the Next-free core that `src/lib/api/auth.ts` now wraps). JMAP Mailbox ids encode `mailboxId`, `mailboxId~role` or `mailboxId~f~folderId` (`ids.ts`); `email-query.ts` maps filters onto `messages` columns, `email-objects.ts` builds Email objects from stored rows (no MIME parsing), and states are digests of counts (`state.ts`), which is why every `/changes` method answers `cannotCalculateChanges`.+`Email/set` create and `Email/import` share one insert (`insertDraft` in `emails.ts`) and one target rule (`resolveDraftsMailbox` in `email-import-utils.ts`): a new message goes into exactly one Drafts mailbox, never Inbox or a folder, because delivered mail is the inbound pipeline's job. `Email/import` parses the uploaded blob with `parseRawMime`, stores the `Message-ID` in `providerMessageId` with its angle brackets (as inbound rows do) and keeps the uploaded bytes at `drafts/<messageId>.eml` in `rawR2Key`, so `readBlob` serves the client's own MIME back instead of the rebuilt minimal message; the `jmap-uploads/` object is deleted once claimed. `Email/copy` and `Email/parse` are still `emailUnsupported`.++`email-query.ts` answers the `header` filter from columns — `Message-ID` from `providerMessageId` (compared with and without angle brackets, since inbound rows store them and outbound rows do not), `In-Reply-To` from `inReplyTo`, `References` by a padded `LIKE` on the space-joined chain. Any other header name throws `unsupportedFilter` (RFC 8620 §5.5). Filter conditions must never be silently dropped: a client that de-duplicates with `header` would otherwise match every message in the mailbox.+### Password reset and MFA`reset_email` on `users` is the destination for reset links (`src/lib/auth/password-reset.ts`); links are hashed, single-use, 30 minutes, and redeeming one revokes every session. Reset mail is sent by `sendSystemEmail` (`src/lib/email/system-mail.ts`), which writes straight to the send binding from the first admin mailbox on a sending-enabled domain, so nothing lands in Sent and no webhooks fire. If no domain can send, the request still returns 200 and a warning is logged. TOTP lives in `src/lib/auth/totp.ts` (RFC 6238 over Web Crypto, no dependency); the secret is stored on `users` at enrolment but only counts once `totp_enabled` is set by a verified code. A login with MFA returns `{ mfaRequired, challengeToken }` (`login_challenges`, 5 minutes) instead of a session, and `/api/auth/mfa/verify` finishes it with a TOTP or recovery code. Password changes and admin resets call `deleteUserSessions`.diff --git a/docs/api.md b/docs/api.mdindex de71a19..dd33093 100644--- a/docs/api.md+++ b/docs/api.md@@ -61,7 +61,11 @@ The dashboard composer accepts up to 10 attachments, with a 10 MB limit per fileMailflare serves [JMAP](https://jmap.io) (RFC 8620 core and RFC 8621 mail, plus submission) so external mail apps can read and send mail. Discovery is at `/.well-known/jmap`, which redirects to `/jmap/session`. Authenticate with an API key that has the `jmap` scope, either as `Authorization: Bearer <key>` or as the password of HTTP Basic auth (the username is ignored). Settings > Account > Email apps mints such a key.-The account id is the user id. Each Mailflare mailbox appears as a top-level JMAP Mailbox with system children (`inbox`, `drafts`, `sent`, `archive`, `junk`, `trash`) and one child per user folder; a message belongs to exactly one of them. Supported methods: `Mailbox/get|query|set` (folders only), `Thread/get`, `Email/get|query|set`, `SearchSnippet/get`, `Identity/get`, `EmailSubmission/set`, and `Core/echo`. `*/changes` return `cannotCalculateChanges`, so clients re-query on a state change; `/jmap/eventsource` pushes state changes by polling. `Email/set` creates drafts, updates `$seen` and `$flagged`, moves between mailboxes, and destroys (to Trash first, then permanently). `EmailSubmission/set` sends a draft and reports it destroyed, since the sent copy is a new message. Blob download and upload follow the Session's `downloadUrl` and `uploadUrl`.+The account id is the user id. Each Mailflare mailbox appears as a top-level JMAP Mailbox with system children (`inbox`, `drafts`, `sent`, `archive`, `junk`, `trash`) and one child per user folder; a message belongs to exactly one of them. Supported methods: `Mailbox/get|query|set` (folders only), `Thread/get`, `Email/get|query|set|import`, `SearchSnippet/get`, `Identity/get`, `EmailSubmission/set`, and `Core/echo`. `Email/copy` and `Email/parse` are not implemented. `*/changes` return `cannotCalculateChanges`, so clients re-query on a state change; `/jmap/eventsource` pushes state changes by polling. `Email/set` creates drafts, updates `$seen` and `$flagged`, moves between mailboxes, and destroys (to Trash first, then permanently). `EmailSubmission/set` sends a draft and reports it destroyed, since the sent copy is a new message. Blob download and upload follow the Session's `downloadUrl` and `uploadUrl`.++`Email/import` takes a `message/rfc822` blob that was uploaded first and stores it as a draft, which is how clients that compose MIME themselves send: upload, import, then `EmailSubmission/set`. Each entry takes `blobId`, `mailboxIds`, and optionally `keywords` and `receivedAt`. **The target must be exactly one Drafts mailbox** — importing into Inbox or a folder is rejected with `invalidProperties` on `mailboxIds`, because delivered mail belongs to the inbound pipeline that does threading and spam scoring. `$seen` and `$flagged` are stored, `$draft` is implied, and other keywords are ignored. `receivedAt` sets the message date, falling back to the `Date` header and then to now. The uploaded bytes are kept verbatim, so downloading the new message's `blobId` returns exactly what was uploaded rather than a reconstruction, and the `Message-ID` header is stored so the client can find its own draft again. Per-message failures come back in `notCreated` as `blobNotFound`, `invalidEmail`, `invalidProperties`, `forbidden` (the `From` address is not one the key may send from) or `tooLarge`.++`Email/query` supports the `header` filter: `["Message-ID", "<[email protected]>"]` matches messages with that value, and `["Message-ID"]` matches any message that has the header. `Message-ID`, `In-Reply-To` and `References` are answered from stored columns; Message-IDs compare with or without angle brackets, and header names are case-insensitive. Any other header name returns an `unsupportedFilter` error rather than silently matching everything.## Password reset and two-factor authenticationdiff --git a/scripts/jmap-import-check.mjs b/scripts/jmap-import-check.mjsnew file mode 100644index 0000000..cf97925--- /dev/null+++ b/scripts/jmap-import-check.mjs@@ -0,0 +1,300 @@+/**+ * End-to-end check of JMAP Email/import and the `header` query filter against a+ * running dev server, in the shape a MIME-composing client sends: upload raw+ * message/rfc822, import it into Drafts, find it again by Message-ID, submit it.+ *+ * npm run dev && npm run db:seed # in another shell+ * node scripts/jmap-import-check.mjs+ *+ * Pass a key with the `jmap` scope in JMAP_KEY, or let the script sign in with+ * the seeded demo account and mint one. BASE_URL overrides http://localhost:3000.+ */++const BASE = (process.env.BASE_URL ?? "http://localhost:3000").replace(/\/$/, "");+const DEMO = { email: "[email protected]", password: "demo-password-change-me" };++let passed = 0;+let failed = 0;++function check(name, ok, detail) {+ if (ok) {+ passed += 1;+ console.log(` ok ${name}`);+ } else {+ failed += 1;+ console.log(` FAIL ${name}${detail === undefined ? "" : ` — ${typeof detail === "string" ? detail : JSON.stringify(detail)}`}`);+ }+}++function section(title) {+ console.log(`\n${title}`);+}++async function mintKey() {+ if (process.env.JMAP_KEY) return process.env.JMAP_KEY;+ const login = await fetch(`${BASE}/api/auth/login`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(DEMO),+ });+ if (!login.ok) throw new Error(`login failed (${login.status}); run npm run db:seed first`);+ const cookie = (login.headers.getSetCookie?.() ?? []).map((value) => value.split(";")[0]).join("; ");+ const created = await fetch(`${BASE}/api/api-keys`, {+ method: "POST",+ headers: { "Content-Type": "application/json", Cookie: cookie },+ body: JSON.stringify({ name: `import-check ${Date.now()}`, scopes: ["jmap"] }),+ });+ if (!created.ok) throw new Error(`could not mint an API key (${created.status})`);+ return (await created.json()).key;+}++/** One JMAP request; returns the method responses. */+async function jmap(key, methodCalls, using = ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail", "urn:ietf:params:jmap:submission"]) {+ const response = await fetch(`${BASE}/jmap/api`, {+ method: "POST",+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },+ body: JSON.stringify({ using, methodCalls }),+ });+ const body = await response.json();+ if (!response.ok) throw new Error(`JMAP ${response.status}: ${JSON.stringify(body)}`);+ return body.methodResponses;+}++async function callOne(key, name, args) {+ const [[, result]] = await jmap(key, [[name, args, "c0"]]);+ return result;+}++/** A multipart/mixed message with one text part and one attachment. */+function buildMime({ from, to, subject, messageId, text, attachmentName, attachmentBody }) {+ const boundary = "mailflare-import-check-boundary";+ return [+ `From: ${from}`,+ `To: ${to}`,+ `Subject: ${subject}`,+ `Message-ID: ${messageId}`,+ "Date: Tue, 16 Sep 2026 09:00:00 +0000",+ "MIME-Version: 1.0",+ `Content-Type: multipart/mixed; boundary="${boundary}"`,+ "",+ `--${boundary}`,+ "Content-Type: text/plain; charset=utf-8",+ "Content-Transfer-Encoding: 7bit",+ "",+ text,+ `--${boundary}`,+ `Content-Type: text/plain; charset=utf-8; name="${attachmentName}"`,+ `Content-Disposition: attachment; filename="${attachmentName}"`,+ "Content-Transfer-Encoding: 7bit",+ "",+ attachmentBody,+ `--${boundary}--`,+ "",+ ].join("\r\n");+}++async function upload(key, accountId, bytes) {+ const response = await fetch(`${BASE}/jmap/upload/${encodeURIComponent(accountId)}`, {+ method: "POST",+ headers: { "Content-Type": "message/rfc822", Authorization: `Bearer ${key}` },+ body: bytes,+ });+ if (!response.ok) throw new Error(`upload failed (${response.status})`);+ return response.json();+}++async function main() {+ const key = await mintKey();++ section("Session");+ const session = await (await fetch(`${BASE}/jmap/session`, { headers: { Authorization: `Bearer ${key}` } })).json();+ const accountId = session.primaryAccounts["urn:ietf:params:jmap:mail"];+ check("session advertises a mail account", !!accountId, session.primaryAccounts);+ check("session advertises the submission capability", !!session.capabilities["urn:ietf:params:jmap:submission"]);++ const mailboxes = await callOne(key, "Mailbox/get", { accountId, ids: null });+ const drafts = mailboxes.list.find((box) => box.role === "drafts");+ const inbox = mailboxes.list.find((box) => box.role === "inbox");+ check("a Drafts mailbox exists", !!drafts, mailboxes.list.map((box) => box.role));+ check("an Inbox mailbox exists", !!inbox);++ const identities = await callOne(key, "Identity/get", { accountId, ids: null });+ const identity = identities.list[0];+ check("at least one Identity to send from", !!identity, identities.list);++ section("Upload");+ const messageId = `<import-check-${Date.now()}@example.com>`;+ const otherMessageId = `<import-check-absent-${Date.now()}@example.com>`;+ const raw = buildMime({+ from: identity.email,+ to: "[email protected]",+ subject: "Import check",+ messageId,+ text: "Composed locally and imported over JMAP.\r\n",+ attachmentName: "note.txt",+ attachmentBody: "attachment body\r\n",+ });+ const rawBytes = new TextEncoder().encode(raw);+ const uploaded = await upload(key, accountId, rawBytes);+ check("upload returns a blobId", typeof uploaded.blobId === "string", uploaded);+ check("upload reports the exact size", uploaded.size === rawBytes.byteLength, { got: uploaded.size, want: rawBytes.byteLength });++ section("Email/import");+ const stale = await callOne(key, "Email/import", {+ accountId,+ ifInState: "not-the-current-state",+ emails: { s1: { blobId: uploaded.blobId, mailboxIds: { [drafts.id]: true }, keywords: { $draft: true, $seen: true } } },+ });+ check("a stale ifInState is a stateMismatch", stale.type === "stateMismatch", stale);++ const imported = await callOne(key, "Email/import", {+ accountId,+ emails: {+ d1: {+ blobId: uploaded.blobId,+ mailboxIds: { [drafts.id]: true },+ keywords: { $draft: true, $seen: true },+ receivedAt: "2026-09-16T09:00:00Z",+ },+ },+ });+ const created = imported.created?.d1;+ check("the message is created", !!created, imported);+ check("created carries an id", typeof created?.id === "string", created);+ check("created carries a blobId", typeof created?.blobId === "string", created);+ check("created carries a threadId", typeof created?.threadId === "string", created);+ check("created carries a size", typeof created?.size === "number" && created.size > 0, created);+ check("the state moves", imported.oldState !== imported.newState, { old: imported.oldState, new: imported.newState });+ check("nothing is reported as notCreated", Object.keys(imported.notCreated ?? {}).length === 0, imported.notCreated);++ section("Email/get on the imported draft");+ const fetched = await callOne(key, "Email/get", {+ accountId,+ ids: [created.id],+ properties: ["subject", "from", "to", "keywords", "mailboxIds", "attachments", "messageId", "threadId", "blobId", "size", "receivedAt", "header:Message-ID"],+ });+ const email = fetched.list[0];+ check("Email/get finds it", !!email, fetched);+ check("subject round-trips", email?.subject === "Import check", email?.subject);+ check("from round-trips", email?.from?.[0]?.email === identity.email, email?.from);+ check("to round-trips", email?.to?.[0]?.email === "[email protected]", email?.to);+ check("the attachment is stored", email?.attachments?.length === 1, email?.attachments);+ check("the attachment keeps its filename", email?.attachments?.[0]?.name === "note.txt", email?.attachments?.[0]);+ check("$draft is set", email?.keywords?.$draft === true, email?.keywords);+ check("$seen is set", email?.keywords?.$seen === true, email?.keywords);+ check("it lands in Drafts", email?.mailboxIds?.[drafts.id] === true, email?.mailboxIds);+ check("the Message-ID is stored", email?.messageId?.[0] === messageId.replace(/^<|>$/g, ""), email?.messageId);+ check("header:Message-ID answers it", typeof email?.["header:Message-ID"] === "string" && email["header:Message-ID"].includes(messageId), email?.["header:Message-ID"]);+ check("receivedAt honours the argument", email?.receivedAt?.startsWith("2026-09-16T09:00:00"), email?.receivedAt);+ check("the blobId matches the import response", email?.blobId === created.blobId, { get: email?.blobId, import: created.blobId });+ check("the threadId matches the import response", email?.threadId === created.threadId, { get: email?.threadId, import: created.threadId });+ check("the size matches the import response", email?.size === created.size, { get: email?.size, import: created.size });++ section("Blob download");+ const download = await fetch(`${BASE}/jmap/download/${encodeURIComponent(accountId)}/${encodeURIComponent(email.blobId)}/message.eml`, {+ headers: { Authorization: `Bearer ${key}` },+ });+ const downloaded = new Uint8Array(await download.arrayBuffer());+ check("the blob downloads", download.ok, download.status);+ check("the download is served as message/rfc822", (download.headers.get("content-type") ?? "").startsWith("message/rfc822"), download.headers.get("content-type"));+ check("the raw bytes are byte-identical to the upload", downloaded.length === rawBytes.length && downloaded.every((byte, index) => byte === rawBytes[index]), { got: downloaded.length, want: rawBytes.length });++ section("Email/query with a header filter");+ const byMessageId = await callOne(key, "Email/query", { accountId, filter: { inMailbox: drafts.id, header: ["Message-ID", messageId] } });+ check("the Message-ID filter returns exactly the imported draft", byMessageId.ids?.length === 1 && byMessageId.ids[0] === created.id, byMessageId.ids);++ const withoutBrackets = await callOne(key, "Email/query", { accountId, filter: { inMailbox: drafts.id, header: ["Message-ID", messageId.replace(/^<|>$/g, "")] } });+ check("the same id without angle brackets matches too", withoutBrackets.ids?.length === 1 && withoutBrackets.ids[0] === created.id, withoutBrackets.ids);++ const lowerCaseName = await callOne(key, "Email/query", { accountId, filter: { inMailbox: drafts.id, header: ["message-id", messageId] } });+ check("the header name is matched case-insensitively", lowerCaseName.ids?.length === 1 && lowerCaseName.ids[0] === created.id, lowerCaseName.ids);++ const otherId = await callOne(key, "Email/query", { accountId, filter: { inMailbox: drafts.id, header: ["Message-ID", otherMessageId] } });+ check("a different Message-ID matches nothing", otherId.ids?.length === 0, otherId.ids);++ const present = await callOne(key, "Email/query", { accountId, filter: { inMailbox: drafts.id, header: ["Message-ID"] } });+ check("the one-element form matches drafts that carry the header", present.ids?.includes(created.id), present.ids);++ const unfiltered = await callOne(key, "Email/query", { accountId, filter: { inMailbox: drafts.id } });+ check("the filter actually narrows the mailbox", unfiltered.ids?.length >= byMessageId.ids?.length, { all: unfiltered.ids?.length, filtered: byMessageId.ids?.length });++ const unknownHeader = await callOne(key, "Email/query", { accountId, filter: { inMailbox: drafts.id, header: ["X-Unknown"] } });+ check("an unsupported header is an unsupportedFilter error", unknownHeader.type === "unsupportedFilter", unknownHeader);++ const unknownInTree = await callOne(key, "Email/query", {+ accountId,+ filter: { operator: "AND", conditions: [{ inMailbox: drafts.id }, { header: ["X-Mailer", "anything"] }] },+ });+ check("an unsupported header inside an operator tree errors too", unknownInTree.type === "unsupportedFilter", unknownInTree);++ section("Rejections");+ const wrongMailbox = await callOne(key, "Email/import", {+ accountId,+ emails: { bad: { blobId: uploaded.blobId, mailboxIds: { [inbox.id]: true } } },+ });+ check("importing into Inbox is invalidProperties", wrongMailbox.notCreated?.bad?.type === "invalidProperties", wrongMailbox.notCreated);+ check("the rejection names mailboxIds", wrongMailbox.notCreated?.bad?.properties?.[0] === "mailboxIds", wrongMailbox.notCreated?.bad);++ const twoMailboxes = await callOne(key, "Email/import", {+ accountId,+ emails: { bad: { blobId: uploaded.blobId, mailboxIds: { [drafts.id]: true, [inbox.id]: true } } },+ });+ check("importing into two mailboxes is invalidProperties", twoMailboxes.notCreated?.bad?.type === "invalidProperties", twoMailboxes.notCreated);++ const missingBlob = await callOne(key, "Email/import", {+ accountId,+ emails: { bad: { blobId: "up~does-not-exist", mailboxIds: { [drafts.id]: true } } },+ });+ check("an unknown blobId is blobNotFound", missingBlob.notCreated?.bad?.type === "blobNotFound", missingBlob.notCreated);++ const nonUploadBlob = await callOne(key, "Email/import", {+ accountId,+ emails: { bad: { blobId: `msg~${created.id}`, mailboxIds: { [drafts.id]: true } } },+ });+ check("a non-upload blobId is blobNotFound", nonUploadBlob.notCreated?.bad?.type === "blobNotFound", nonUploadBlob.notCreated);++ check("the upload is released once claimed", missingBlob.notCreated?.bad?.type === "blobNotFound" && (await callOne(key, "Email/import", { accountId, emails: { again: { blobId: uploaded.blobId, mailboxIds: { [drafts.id]: true } } } })).notCreated?.again?.type === "blobNotFound", "re-importing the claimed upload should fail");++ section("Import and submit in one request");+ const secondMessageId = `<import-check-submit-${Date.now()}@example.com>`;+ const secondRaw = new TextEncoder().encode(buildMime({+ from: identity.email,+ to: "[email protected]",+ subject: "Import and submit",+ messageId: secondMessageId,+ text: "Sent straight after import.\r\n",+ attachmentName: "second.txt",+ attachmentBody: "second attachment\r\n",+ }));+ const secondUpload = await upload(key, accountId, secondRaw);+ const responses = await jmap(key, [+ ["Email/import", { accountId, emails: { d2: { blobId: secondUpload.blobId, mailboxIds: { [drafts.id]: true }, keywords: { $draft: true, $seen: true } } } }, "i1"],+ ["EmailSubmission/set", { accountId, create: { s1: { emailId: "#d2", identityId: identity.id } } }, "i2"],+ ]);+ const importResponse = responses.find(([name, , id]) => name === "Email/import" && id === "i1")?.[1];+ const submission = responses.find(([name, , id]) => name === "EmailSubmission/set" && id === "i2")?.[1];+ const implicitSet = responses.find(([name, , id]) => name === "Email/set" && id === "i2")?.[1];+ const importedId = importResponse?.created?.d2?.id;+ check("the second import succeeds", !!importedId, importResponse);+ check("#creationId resolves in the same request", !!submission?.created?.s1, submission);+ check("the submission is final", submission?.created?.s1?.undoStatus === "final", submission?.created?.s1);+ check("the implicit Email/set reports the draft destroyed", implicitSet?.destroyed?.includes(importedId), implicitSet);++ const gone = await callOne(key, "Email/get", { accountId, ids: [importedId] });+ check("the draft is gone after sending", gone.notFound?.includes(importedId), gone);++ const sent = await callOne(key, "Email/query", { accountId, filter: { inMailbox: `${drafts.id.split("~")[0]}~sent` }, limit: 5 });+ check("a sent copy exists", (sent.ids?.length ?? 0) > 0, sent.ids);++ section("Cleanup");+ const destroyed = await callOne(key, "Email/set", { accountId, destroy: [created.id] });+ check("the first imported draft can be destroyed", destroyed.destroyed?.includes(created.id), destroyed);++ console.log(`\n${passed} passed, ${failed} failed`);+ process.exit(failed === 0 ? 0 : 1);+}++main().catch((error) => {+ console.error(`\nAborted: ${error.message}`);+ process.exit(1);+});diff --git a/src/app/api/drafts/[id]/route.ts b/src/app/api/drafts/[id]/route.tsindex 38cf592..8e0f0e0 100644--- a/src/app/api/drafts/[id]/route.ts+++ b/src/app/api/drafts/[id]/route.ts@@ -10,7 +10,8 @@ import { selectDraftWithBody } from "./utils";import { readJsonBody } from "@/lib/http/request";import { RequestBodyTooLargeError } from "@/lib/http/errors";import { getDraftSender, userOwnsDraft } from "../utils";-import { deleteMessageAttachmentObjects, listMessageAttachments } from "@/lib/email/attachments";+import { listMessageAttachments } from "@/lib/email/attachments";+import { deleteMessageWithObjects } from "@/lib/email/message-cleanup";export async function GET(request: Request, { params }: DraftRouteParams) {const { id } = await params;@@ -80,8 +81,6 @@ export async function DELETE(request: Request, { params }: DraftRouteParams) {return NextResponse.json({ error: "Draft not found" }, { status: 404 });}- // Rows cascade with the draft; the R2 objects do not.- await deleteMessageAttachmentObjects(env, id);- await db.delete(messages).where(eq(messages.id, id));+ await deleteMessageWithObjects(env, db, id, draft.rawR2Key);return NextResponse.json({ ok: true });}diff --git a/src/lib/email/message-cleanup.ts b/src/lib/email/message-cleanup.tsnew file mode 100644index 0000000..4ee6223--- /dev/null+++ b/src/lib/email/message-cleanup.ts@@ -0,0 +1,16 @@+import { eq } from "drizzle-orm";+import type { AppDatabase } from "@/db";+import { messages } from "@/db/schema";+import { deleteMessageAttachmentObjects } from "@/lib/email/attachments";++/** Remove every external object owned by a message before deleting its row. */+export async function deleteMessageWithObjects(+ env: CloudflareEnv,+ db: AppDatabase,+ id: string,+ rawR2Key: string | null,+): Promise<void> {+ await deleteMessageAttachmentObjects(env, id);+ if (rawR2Key) await env.BUCKET.delete(rawR2Key);+ await db.delete(messages).where(eq(messages.id, id));+}diff --git a/src/lib/email/parse.ts b/src/lib/email/parse.tsindex faa3acb..ba3a25e 100644--- a/src/lib/email/parse.ts+++ b/src/lib/email/parse.ts@@ -15,6 +15,8 @@ export type ParsedEmail = {toAddr: string | null;/** Full Cc header, comma-joined. */ccAddr: string | null;+ /** Full Bcc header, comma-joined. Only present on mail composed locally, never on delivered mail. */+ bccAddr: string | null;inReplyTo: string | null;references: string[];date: Date | null;@@ -32,6 +34,7 @@ export async function parseRawMime(raw: ArrayBuffer): Promise<ParsedEmail> {fromAddr: formatPostalAddress(email.from, null),toAddr: formatPostalAddressList(email.to, null),ccAddr: formatPostalAddressList(email.cc, null),+ bccAddr: formatPostalAddressList(email.bcc, null),inReplyTo: normalizeMessageId(email.inReplyTo),references: parseMessageIdList(email.references),date: date && !Number.isNaN(date.getTime()) ? date : null,diff --git a/src/lib/jmap/blobs.ts b/src/lib/jmap/blobs.tsindex 05da51c..be06af1 100644--- a/src/lib/jmap/blobs.ts+++ b/src/lib/jmap/blobs.ts@@ -8,11 +8,16 @@ import type { JmapContext } from "./types";const UPLOAD_PREFIX = "jmap-uploads";+/** Uploads are namespaced by user, so only the account that stored one can read it. */+function uploadKey(ctx: JmapContext, uploadId: string): string {+ return `${UPLOAD_PREFIX}/${ctx.auth.userId}/${uploadId}`;+}+/** Client uploads live in R2 under the user until a draft claims them. */export async function storeUpload(ctx: JmapContext, body: ArrayBuffer, type: string, name: string | null) {if (body.byteLength > LIMITS.maxSizeUpload) return null;const id = newId("upl");- await ctx.env.BUCKET.put(`${UPLOAD_PREFIX}/${ctx.auth.userId}/${id}`, body, {+ await ctx.env.BUCKET.put(uploadKey(ctx, id), body, {httpMetadata: { contentType: type },customMetadata: { userId: ctx.auth.userId, ...(name ? { name } : {}) },});@@ -20,11 +25,30 @@ export async function storeUpload(ctx: JmapContext, body: ArrayBuffer, type: str}export async function readUpload(ctx: JmapContext, uploadId: string) {- const object = await ctx.env.BUCKET.get(`${UPLOAD_PREFIX}/${ctx.auth.userId}/${uploadId}`);+ const object = await ctx.env.BUCKET.get(uploadKey(ctx, uploadId));if (!object) return null;return { content: await object.arrayBuffer(), type: object.httpMetadata?.contentType ?? "application/octet-stream", name: object.customMetadata?.name ?? null };}+/** Drop an upload once a message owns its bytes. */+export async function deleteUpload(ctx: JmapContext, uploadId: string): Promise<void> {+ await ctx.env.BUCKET.delete(uploadKey(ctx, uploadId));+}++/**+ * Keep the exact MIME an imported message arrived as, mirroring the `inbound/`+ * copy the mail pipeline stores, so `readBlob` serves the client its own bytes+ * back instead of the rebuilt minimal message.+ */+export async function storeRawDraftMime(ctx: JmapContext, messageId: string, raw: ArrayBuffer): Promise<string> {+ const key = `drafts/${messageId}.eml`;+ await ctx.env.BUCKET.put(key, raw, {+ httpMetadata: { contentType: "message/rfc822" },+ customMetadata: { userId: ctx.auth.userId, messageId },+ });+ return key;+}+/*** Resolve a blob id to bytes the account may read: an attachment on one of* its messages, the raw MIME of one of its messages, or its own upload.diff --git a/src/lib/jmap/email-import-utils.ts b/src/lib/jmap/email-import-utils.tsnew file mode 100644index 0000000..bad3b54--- /dev/null+++ b/src/lib/jmap/email-import-utils.ts@@ -0,0 +1,51 @@+import { KEYWORD_FLAGGED, KEYWORD_SEEN } from "./constants";+import { decodeMailboxRef } from "./ids";+import type { JmapSetError } from "./types";++/**+ * A JMAP Id[Boolean] set, as `mailboxIds` and `keywords` are defined. Clients+ * built on libraries that model these as lists send a plain array instead, so+ * both shapes are read; only entries set to true count.+ */+export function idSetToList(value: unknown): string[] {+ if (Array.isArray(value)) return value.filter((item): item is string => typeof item === "string");+ if (!value || typeof value !== "object") return [];+ return Object.entries(value as Record<string, unknown>).filter(([, on]) => !!on).map(([id]) => id);+}++/** The keywords Mailflare stores as columns. `$draft` is implied by the Drafts-only rule, and unknown keywords are ignored. */+export function importFlags(keywords: unknown): { read: boolean; starred: boolean } {+ const set = new Set(idSetToList(keywords));+ return { read: set.has(KEYWORD_SEEN), starred: set.has(KEYWORD_FLAGGED) };+}++/**+ * `receivedAt` is a UTCDate in RFC 8621, but client libraries also send epoch+ * seconds or milliseconds. Anything unusable falls back to the caller's default.+ */+export function parseReceivedAt(value: unknown): Date | null {+ if (typeof value === "number" && Number.isFinite(value)) {+ // Seconds until the value is too large to be one: 1e12 is the year 33658 in seconds.+ const date = new Date(value < 1e12 ? value * 1000 : value);+ return Number.isNaN(date.getTime()) ? null : date;+ }+ if (typeof value !== "string" || !value.trim()) return null;+ const date = new Date(value.trim());+ return Number.isNaN(date.getTime()) ? null : date;+}++/**+ * Where a new message may be created: exactly one JMAP Mailbox, and it must be+ * a Drafts role mailbox the key can write to. Importing into arbitrary mailboxes+ * would have to answer for threading, spam scoring and inbound state, so v1+ * takes the same target `Email/set` create does.+ */+export function resolveDraftsMailbox(mailboxIds: unknown, writable: Set<string>): { mailboxId: string } | { error: JmapSetError } {+ const ids = idSetToList(mailboxIds);+ const invalid = (description: string) => ({ error: { type: "invalidProperties", properties: ["mailboxIds"], description } });+ if (ids.length !== 1) return invalid("A message belongs to exactly one mailbox");+ const ref = decodeMailboxRef(ids[0]);+ if (!ref || !writable.has(ref.mailboxId)) return invalid("Unknown mailbox");+ if (ref.kind !== "role" || ref.role !== "drafts") return invalid("New messages can only be created in a Drafts mailbox");+ return { mailboxId: ref.mailboxId };+}diff --git a/src/lib/jmap/email-query.ts b/src/lib/jmap/email-query.tsindex 450790a..dab0f7f 100644--- a/src/lib/jmap/email-query.ts+++ b/src/lib/jmap/email-query.ts@@ -1,8 +1,9 @@-import { and, asc, desc, eq, exists, gt, gte, inArray, isNull, like, lt, ne, not, or, sql } from "drizzle-orm";+import { and, asc, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, like, lt, ne, not, or, sql } from "drizzle-orm";import type { SQL } from "drizzle-orm";import { messageAttachments, messages } from "@/db/schema";import { KEYWORD_DRAFT, KEYWORD_FLAGGED, KEYWORD_SEEN } from "./constants";-import { invalidArguments } from "./errors";+import { invalidArguments, unsupportedFilter } from "./errors";+import { normalizeMessageId } from "@/lib/email/threading";import { decodeMailboxRef, roleToStatus } from "./ids";import type { Comparator, Filter, FilterCondition, MailboxRef } from "./types";@@ -31,8 +32,40 @@ function keywordCondition(keyword: string, present: boolean): SQL {}}+function likeEscape(value: string): string {+ return value.replace(/[%_\\]/g, (char) => `\\${char}`);+}+function likePattern(value: string): string {- return `%${value.replace(/[%_\\]/g, (char) => `\\${char}`)}%`;+ return `%${likeEscape(value)}%`;+}++/**+ * RFC 8621 §4.4.1 `header`: `[name]` means the header is present, `[name, value]`+ * that its value equals that string. Only the headers Mailflare keeps as columns+ * can be matched, and Message-IDs compare without their angle brackets because+ * inbound rows store them with and outbound rows without.+ */+function headerCondition(header: string[]): SQL {+ if (!Array.isArray(header) || header.length < 1 || header.length > 2 || typeof header[0] !== "string") {+ throw invalidArguments("header must be [name] or [name, value]");+ }+ const name = header[0].trim().toLowerCase();+ const value = header.length === 2 ? normalizeMessageId(String(header[1])) : null;+ switch (name) {+ case "message-id":+ if (header.length === 1) return isNotNull(messages.providerMessageId);+ return value ? inArray(messages.providerMessageId, [value, `<${value}>`]) : sql`0`;+ case "in-reply-to":+ if (header.length === 1) return isNotNull(messages.inReplyTo);+ return value ? inArray(messages.inReplyTo, [value, `<${value}>`]) : sql`0`;+ case "references":+ if (header.length === 1) return isNotNull(messages.references);+ // The column is the space-joined chain, so pad both sides to match whole ids only.+ return value ? like(sql`' ' || coalesce(${messages.references}, '') || ' '`, `% ${likeEscape(value)} %`) : sql`0`;+ default:+ throw unsupportedFilter(`Cannot filter on the ${header[0]} header`);+ }}function conditionToSql(condition: FilterCondition, accessible: Set<string>): SQL[] {@@ -74,6 +107,7 @@ function conditionToSql(condition: FilterCondition, accessible: Set<string>): SQ)!,);}+ if (condition.header) parts.push(headerCondition(condition.header));if (condition.hasAttachment !== undefined) {const hasOne = exists(sql`(SELECT 1 FROM ${messageAttachments} WHERE ${messageAttachments.messageId} = ${messages.id} AND ${messageAttachments.disposition} = 'attachment')`,diff --git a/src/lib/jmap/emails.ts b/src/lib/jmap/emails.tsindex cbca613..7b29beb 100644--- a/src/lib/jmap/emails.ts+++ b/src/lib/jmap/emails.ts@@ -1,23 +1,75 @@import { and, asc, count, desc, eq, inArray, sql } from "drizzle-orm";import { messages } from "@/db/schema";import { newId } from "@/lib/ids";-import { buildSnippet } from "@/lib/email/parse";+import { buildSnippet, parseRawMime } from "@/lib/email/parse";import { getAuthorizedSenderAddress } from "@/lib/email/sender";import { joinEmailAddressList } from "@/lib/email/address";+import { resolveThreadId } from "@/lib/email/threading";import { storeMessageAttachments } from "@/lib/email/attachments";+import { deleteMessageWithObjects } from "@/lib/email/message-cleanup";import { LIMITS, KEYWORD_FLAGGED, KEYWORD_SEEN } from "./constants";import { JmapError, invalidArguments } from "./errors";import { decodeBlobId, decodeMailboxRef, roleToStatus } from "./ids";import { buildEmailObject, loadAttachmentsByMessage, resolveHeaderProperty } from "./email-objects";+import { importFlags, parseReceivedAt, resolveDraftsMailbox } from "./email-import-utils";import { filterToSql, mailboxRefCondition, sortToSql } from "./email-query";import { getEmailState } from "./state";import { listAccessibleMailboxIdSet, listJmapMailboxes } from "./access";-import { readUpload } from "./blobs";-import type { Comparator, EmailAddressObject, Filter, JmapContext, JmapMethodHandler, MailboxRef } from "./types";+import { deleteUpload, readUpload, storeRawDraftMime } from "./blobs";+import type { Comparator, EmailAddressObject, Filter, JmapContext, JmapMethodHandler, JmapSetError, MailboxRef } from "./types";import type { AttachmentContent } from "@/lib/email/attachment-types";type MessageRow = typeof messages.$inferSelect;+/** The columns a draft row is made of, shared by `Email/set` create and `Email/import`. */+type DraftRow = {+ mailboxId: string;+ fromAddr: string;+ toAddr: string;+ ccAddr: string | null;+ bccAddr: string | null;+ subject: string | null;+ textBody: string | null;+ htmlBody: string | null;+ inReplyTo: string | null;+ references: string | null;+ read?: boolean;+ starred?: boolean;+ threadId?: string | null;+ providerMessageId?: string | null;+ rawR2Key?: string | null;+ createdAt?: Date;+};++/** Insert a draft and return its id. Drafts are outbound mail that has not been sent. */+async function insertDraft(ctx: JmapContext, row: DraftRow): Promise<string> {+ const id = newId("msg");+ await ctx.db.insert(messages).values({+ id,+ userId: ctx.auth.userId,+ mailboxId: row.mailboxId,+ direction: "outbound",+ fromAddr: row.fromAddr,+ toAddr: row.toAddr,+ ccAddr: row.ccAddr,+ bccAddr: row.bccAddr,+ subject: row.subject,+ snippet: buildSnippet(row.textBody, row.htmlBody),+ textBody: row.textBody,+ htmlBody: row.htmlBody,+ status: "draft",+ read: row.read ?? true,+ starred: row.starred ?? false,+ inReplyTo: row.inReplyTo,+ references: row.references,+ threadId: row.threadId ?? null,+ providerMessageId: row.providerMessageId ?? null,+ rawR2Key: row.rawR2Key ?? null,+ ...(row.createdAt ? { createdAt: row.createdAt } : {}),+ });+ return id;+}+async function scope(ctx: JmapContext) {const ids = Array.from(await listAccessibleMailboxIdSet(ctx));return { ids, condition: ids.length ? inArray(messages.mailboxId, ids) : eq(messages.userId, ctx.auth.userId) };@@ -150,16 +202,13 @@ function keywordsFromPatch(patch: Record<string, unknown>): { read?: boolean; st/** Drafts are the only thing a client creates; everything else is a flag or a move. */async function createDraft(ctx: JmapContext, value: Record<string, unknown>, accessible: Set<string>) {- const mailboxIds = Object.keys((value.mailboxIds as Record<string, boolean>) ?? {}).filter((id) => (value.mailboxIds as Record<string, boolean>)[id]);- const ref = mailboxIds.length === 1 ? decodeMailboxRef(mailboxIds[0]) : null;- if (!ref || !accessible.has(ref.mailboxId) || ref.kind !== "role" || ref.role !== "drafts") {- return { error: { type: "invalidProperties", properties: ["mailboxIds"], description: "New messages can only be created in a Drafts mailbox" } };- }+ const target = resolveDraftsMailbox(value.mailboxIds, accessible);+ if ("error" in target) return target;const from = (value.from as EmailAddressObject[] | undefined)?.[0]?.email;if (!from) return { error: { type: "invalidProperties", properties: ["from"] } };let sender: { fromAddr: string; mailboxId: string };try {- sender = await getAuthorizedSenderAddress(ctx.env, { userId: ctx.auth.userId, from, mailboxId: ref.mailboxId });+ sender = await getAuthorizedSenderAddress(ctx.env, { userId: ctx.auth.userId, from, mailboxId: target.mailboxId });} catch (error) {return { error: { type: "forbidden", description: error instanceof Error ? error.message : "Cannot send from that address" } };}@@ -171,25 +220,17 @@ async function createDraft(ctx: JmapContext, value: Record<string, unknown>, accconst html = partText(value.htmlBody);const references = Array.isArray(value.references) ? (value.references as string[]).join(" ") : null;- const id = newId("msg");- await ctx.db.insert(messages).values({- id,- userId: ctx.auth.userId,+ const id = await insertDraft(ctx, {mailboxId: sender.mailboxId,- direction: "outbound",fromAddr: sender.fromAddr,toAddr: addressList(value.to),ccAddr: addressList(value.cc) || null,bccAddr: addressList(value.bcc) || null,subject: typeof value.subject === "string" ? value.subject : null,- snippet: buildSnippet(text || null, html || null),textBody: text || null,htmlBody: html || null,- status: "draft",- read: true,inReplyTo: Array.isArray(value.inReplyTo) ? (value.inReplyTo as string[])[0] ?? null : null,references,- threadId: null,});const uploads: AttachmentContent[] = [];@@ -279,7 +320,7 @@ export const emailSet: JmapMethodHandler = async (ctx, args) => {notDestroyed[id] = { type: "forbidden" };continue;}- if (row.status === "trash" || row.status === "draft") await ctx.db.delete(messages).where(eq(messages.id, id));+ if (row.status === "trash" || row.status === "draft") await deleteMessageWithObjects(ctx.env, ctx.db, row.id, row.rawR2Key);else await ctx.db.update(messages).set({ status: "trash", folderId: null }).where(eq(messages.id, id));destroyed.push(id);}@@ -287,6 +328,119 @@ export const emailSet: JmapMethodHandler = async (ctx, args) => {return { accountId: ctx.accountId, oldState, newState: await getEmailState(ctx), created, updated, destroyed, notCreated, notUpdated, notDestroyed };};+/**+ * Import one uploaded `message/rfc822` blob as a draft (RFC 8621 §4.8). Clients+ * that compose MIME locally send by uploading it, importing it into Drafts and+ * then submitting it, so this is the first half of their send path. The raw+ * bytes are kept verbatim under `drafts/` and the parsed headers fill the+ * columns the rest of Mailflare reads, including `providerMessageId`, which is+ * what lets a client find its own draft again with a Message-ID header filter.+ */+async function importEmail(ctx: JmapContext, value: Record<string, unknown>, writable: Set<string>): Promise<{ id: string } | { error: JmapSetError }> {+ const target = resolveDraftsMailbox(value.mailboxIds, writable);+ if ("error" in target) return target;++ const blob = typeof value.blobId === "string" ? decodeBlobId(value.blobId) : null;+ if (!blob || blob.kind !== "up") return { error: { type: "blobNotFound", description: "blobId must name an upload from this account" } };+ const upload = await readUpload(ctx, blob.id);+ if (!upload) return { error: { type: "blobNotFound", description: "No such upload" } };+ if (upload.content.byteLength === 0) return { error: { type: "invalidEmail", description: "The blob is empty" } };+ if (upload.content.byteLength > LIMITS.maxSizeUpload) return { error: { type: "tooLarge", description: "The message exceeds maxSizeUpload" } };++ let parsed: Awaited<ReturnType<typeof parseRawMime>>;+ try {+ parsed = await parseRawMime(upload.content);+ } catch (error) {+ return { error: { type: "invalidEmail", description: error instanceof Error ? error.message : "The blob is not a MIME message" } };+ }+ if (!parsed.fromAddr) return { error: { type: "invalidEmail", description: "The message has no From header" } };++ let sender: { fromAddr: string; mailboxId: string };+ try {+ sender = await getAuthorizedSenderAddress(ctx.env, { userId: ctx.auth.userId, from: parsed.fromAddr, mailboxId: target.mailboxId });+ } catch (error) {+ return { error: { type: "forbidden", description: error instanceof Error ? error.message : "Cannot send from that address" } };+ }++ const flags = importFlags(value.keywords);+ const id = await insertDraft(ctx, {+ mailboxId: sender.mailboxId,+ fromAddr: sender.fromAddr,+ toAddr: parsed.toAddr ?? "",+ ccAddr: parsed.ccAddr,+ bccAddr: parsed.bccAddr,+ subject: parsed.subject,+ textBody: parsed.text,+ htmlBody: parsed.html,+ inReplyTo: parsed.inReplyTo,+ references: parsed.references.length ? parsed.references.join(" ") : null,+ read: flags.read,+ starred: flags.starred,+ // Angle brackets are kept, as inbound rows store them.+ providerMessageId: parsed.messageId,+ threadId: await resolveThreadId(ctx.db, {+ mailboxId: sender.mailboxId,+ messageId: parsed.messageId,+ inReplyTo: parsed.inReplyTo,+ references: parsed.references,+ }),+ createdAt: parseReceivedAt(value.receivedAt) ?? parsed.date ?? new Date(),+ });++ // Nothing may be left half-imported, so the row and the bytes go together.+ let rawR2Key: string | null = null;+ try {+ rawR2Key = await storeRawDraftMime(ctx, id, upload.content);+ await ctx.db.update(messages).set({ rawR2Key }).where(eq(messages.id, id));+ if (parsed.attachments.length) await storeMessageAttachments(ctx.env, id, parsed.attachments);+ } catch (error) {+ try {+ await deleteMessageWithObjects(ctx.env, ctx.db, id, rawR2Key);+ } catch (cleanupError) {+ console.error(`Failed to clean up rejected Email/import draft ${id}`, cleanupError);+ }+ return { error: { type: "tooLarge", description: error instanceof Error ? error.message : "Attachments rejected" } };+ }+ // The bytes belong to the message now, so release the upload.+ try {+ await deleteUpload(ctx, blob.id);+ } catch (error) {+ // The import is already complete. Failing it here would make a client retry+ // and create a duplicate draft merely because temporary cleanup failed.+ console.warn(`Failed to delete claimed JMAP upload ${blob.id}`, error);+ }+ return { id };+}++export const emailImport: JmapMethodHandler = async (ctx, args) => {+ const oldState = await getEmailState(ctx);+ if (args.ifInState && args.ifInState !== oldState) return { type: "stateMismatch" };+ const emails = (args.emails ?? {}) as Record<string, Record<string, unknown>>;+ if (Object.keys(emails).length > LIMITS.maxObjectsInSet) throw new JmapError("requestTooLarge");+ const writable = new Set((await listJmapMailboxes(ctx)).filter((row) => row.permission !== "read_only").map((row) => row.id));+ const created: Record<string, unknown> = {};+ const notCreated: Record<string, unknown> = {};++ for (const [creationId, value] of Object.entries(emails)) {+ const result = await importEmail(ctx, value ?? {}, writable);+ if ("error" in result) {+ notCreated[creationId] = result.error;+ continue;+ }+ ctx.createdIds[creationId] = result.id;+ const [row] = await loadMessages(ctx, [result.id]);+ if (!row) {+ notCreated[creationId] = { type: "serverFail", description: "The imported message could not be read back" };+ continue;+ }+ // The same values Email/get would answer, so the client can act on them straight away.+ const object = buildEmailObject(row, (await loadAttachmentsByMessage(ctx, [row.id])).get(row.id) ?? [], { fetchBodies: false, maxBodyValueBytes: 0 });+ created[creationId] = { id: object.id, blobId: object.blobId, threadId: object.threadId, size: object.size };+ }++ return { accountId: ctx.accountId, oldState, newState: await getEmailState(ctx), created, notCreated };+};+export const emailUnsupported = (method: string): JmapMethodHandler => async () => ({ type: "unknownMethod", description: `${method} is not supported` });/** Thread/get: every message sharing a thread key, oldest first. */diff --git a/src/lib/jmap/errors.ts b/src/lib/jmap/errors.tsindex 3ef5a2f..0b1f906 100644--- a/src/lib/jmap/errors.ts+++ b/src/lib/jmap/errors.ts@@ -18,6 +18,11 @@ export function invalidArguments(description: string): JmapError {return new JmapError("invalidArguments", description);}+/** RFC 8620 §5.5: a filter the server cannot apply is an error, never a silent match-all. */+export function unsupportedFilter(description: string): JmapError {+ return new JmapError("unsupportedFilter", description);+}+/** RFC 7807 problem document for request-level failures. */export function problemResponse(type: string, status: number, detail: string, extra: Record<string, unknown> = {}): Response {return new Response(JSON.stringify({ type: `urn:ietf:params:jmap:error:${type}`, status, detail, ...extra }), {diff --git a/src/lib/jmap/identities.ts b/src/lib/jmap/identities.tsindex 48ac97b..c470de6 100644--- a/src/lib/jmap/identities.ts+++ b/src/lib/jmap/identities.ts@@ -2,6 +2,7 @@ import { and, eq } from "drizzle-orm";import { messages } from "@/db/schema";import { sendEmail } from "@/lib/email/send";import { loadMessageAttachmentContents } from "@/lib/email/attachments";+import { deleteMessageWithObjects } from "@/lib/email/message-cleanup";import { decodeIdentityId, identityId } from "./ids";import { listJmapMailboxes, listSendableAddresses } from "./access";import { getEmailState } from "./state";@@ -91,7 +92,13 @@ export const emailSubmissionSet: JmapMethodHandler = async (ctx, args) => {mailboxId: identity.mailboxId,attachments,});- await ctx.db.delete(messages).where(eq(messages.id, draft.id));+ try {+ await deleteMessageWithObjects(ctx.env, ctx.db, draft.id, draft.rawR2Key);+ } catch (error) {+ // Sending is irreversible, so cleanup failure must not invite a retry+ // that could deliver the same message twice.+ console.error(`Failed to clean up submitted draft ${draft.id}`, error);+ }destroyedEmails.push(draft.id);ctx.createdIds[creationId] = result.messageId;created[creationId] = {diff --git a/src/lib/jmap/processor.ts b/src/lib/jmap/processor.tsindex c4b7292..42bd848 100644--- a/src/lib/jmap/processor.ts+++ b/src/lib/jmap/processor.ts@@ -1,7 +1,7 @@import { CAPABILITY_CORE, CAPABILITY_MAIL, CAPABILITY_SUBMISSION, LIMITS } from "./constants";import { JmapError } from "./errors";import { mailboxChanges, mailboxGet, mailboxQuery, mailboxSet } from "./mailboxes";-import { emailChanges, emailGet, emailQuery, emailQueryChanges, emailSet, emailUnsupported, searchSnippetGet, threadChanges, threadGet } from "./emails";+import { emailChanges, emailGet, emailImport, emailQuery, emailQueryChanges, emailSet, emailUnsupported, searchSnippetGet, threadChanges, threadGet } from "./emails";import { emailSubmissionChanges, emailSubmissionGet, emailSubmissionQuery, emailSubmissionSet, identityChanges, identityGet, identitySet } from "./identities";import { getEmailState, getMailboxState } from "./state";import type { JmapContext, JmapInvocation, JmapMethodHandler, JmapRequest, JmapResponse } from "./types";@@ -21,7 +21,7 @@ const METHODS: Record<string, JmapMethodHandler> = {"Email/queryChanges": emailQueryChanges,"Email/set": emailSet,"Email/copy": emailUnsupported("Email/copy"),- "Email/import": emailUnsupported("Email/import"),+ "Email/import": emailImport,"Email/parse": emailUnsupported("Email/parse"),"SearchSnippet/get": searchSnippetGet,"Identity/get": identityGet,diff --git a/src/lib/jmap/types.d.ts b/src/lib/jmap/types.d.tsindex 4254724..70e596c 100644--- a/src/lib/jmap/types.d.ts+++ b/src/lib/jmap/types.d.ts@@ -20,6 +20,9 @@ export type JmapResponse = {export type JmapMethodError = { type: string; description?: string; [key: string]: unknown };+/** RFC 8620 §5.3 SetError: why one object in a /set or /import call was rejected. */+export type JmapSetError = { type: string; properties?: string[]; description?: string };+export type JmapContext = {env: CloudflareEnv;db: AppDatabase;@@ -88,6 +91,8 @@ export type FilterCondition = {subject?: string;body?: string;hasAttachment?: boolean;+ /** `[name]` matches messages carrying the header; `[name, value]` those whose value equals it. */+ header?: string[];};export type FilterOperator = { operator: "AND" | "OR" | "NOT"; conditions: Filter[] };diff --git a/src/lib/spam/feedback.ts b/src/lib/spam/feedback.tsindex 29b660e..c139d69 100644--- a/src/lib/spam/feedback.ts+++ b/src/lib/spam/feedback.ts@@ -25,7 +25,7 @@ export async function applySpamFeedback(env: CloudflareEnv, user: SessionUser, mconst parsed = {subject: message.subject, text: message.textBody, html: message.htmlBody,messageId: message.providerMessageId, fromAddr: message.fromAddr, toAddr: message.toAddr,- ccAddr: message.ccAddr, inReplyTo: message.inReplyTo,+ ccAddr: message.ccAddr, bccAddr: message.bccAddr, inReplyTo: message.inReplyTo,references: message.references?.split(/\s+/).filter(Boolean) ?? [], date: message.createdAt,attachments: [],};diff --git a/tests/jmap-email-import.test.mjs b/tests/jmap-email-import.test.mjsnew file mode 100644index 0000000..c5cb6e9--- /dev/null+++ b/tests/jmap-email-import.test.mjs@@ -0,0 +1,170 @@+import assert from "node:assert/strict";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import test, { after } from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";++import { build } from "esbuild";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");++/**+ * The modules under test import through the `@/*` alias and are TypeScript, so+ * they are bundled with the esbuild already used by `scripts/build-server.mjs`+ * rather than loaded directly. Nothing here touches a Workers binding: the+ * import helpers are pure and the query layer only builds SQL.+ */+const outDir = mkdtempSync(join(tmpdir(), "mailflare-jmap-test-"));+after(() => rmSync(outDir, { recursive: true, force: true }));++await build({+ stdin: {+ contents: `+ export { idSetToList, importFlags, parseReceivedAt, resolveDraftsMailbox } from "./src/lib/jmap/email-import-utils.ts";+ export { filterToSql } from "./src/lib/jmap/email-query.ts";+ export { encodeMailboxRef } from "./src/lib/jmap/ids.ts";+ import { SQLiteSyncDialect } from "drizzle-orm/sqlite-core";+ const dialect = new SQLiteSyncDialect();+ export const render = (fragment) => dialect.sqlToQuery(fragment);+ `,+ resolveDir: root,+ sourcefile: "jmap-test-entry.js",+ },+ outfile: join(outDir, "entry.mjs"),+ bundle: true,+ platform: "node",+ format: "esm",+ target: "node22",+ tsconfig: join(root, "tsconfig.json"),+ logLevel: "silent",+});++const { idSetToList, importFlags, parseReceivedAt, resolveDraftsMailbox, filterToSql, encodeMailboxRef, render } = await import(+ pathToFileURL(join(outDir, "entry.mjs")).href+);++const DRAFTS = encodeMailboxRef({ kind: "role", mailboxId: "mbx1", role: "drafts" });+const INBOX = encodeMailboxRef({ kind: "role", mailboxId: "mbx1", role: "inbox" });+const FOLDER = encodeMailboxRef({ kind: "folder", mailboxId: "mbx1", folderId: "fld1" });+const writable = new Set(["mbx1"]);++const renderFilter = (filter) => render(filterToSql(filter, writable));++test("JMAP Id[Boolean] sets are read as maps and as plain lists", () => {+ assert.deepEqual(idSetToList({ a: true, b: true }), ["a", "b"]);+ assert.deepEqual(idSetToList({ a: true, b: false }), ["a"]);+ assert.deepEqual(idSetToList(["a", "b"]), ["a", "b"]);+ assert.deepEqual(idSetToList(undefined), []);+ assert.deepEqual(idSetToList("nonsense"), []);+ assert.deepEqual(idSetToList([1, "a"]), ["a"]);+});++test("only the keywords Mailflare stores as columns are mapped", () => {+ assert.deepEqual(importFlags({ $seen: true, $draft: true }), { read: true, starred: false });+ assert.deepEqual(importFlags({ $flagged: true }), { read: false, starred: true });+ assert.deepEqual(importFlags(["$draft", "$seen", "$flagged"]), { read: true, starred: true });+ // $draft is implied by the Drafts-only rule and unknown keywords are ignored.+ assert.deepEqual(importFlags({ $draft: true, $answered: true, "custom-tag": true }), { read: false, starred: false });+ assert.deepEqual(importFlags(undefined), { read: false, starred: false });+});++test("receivedAt accepts a UTCDate, epoch seconds and epoch milliseconds", () => {+ assert.equal(parseReceivedAt("2026-09-16T09:00:00Z").toISOString(), "2026-09-16T09:00:00.000Z");+ assert.equal(parseReceivedAt(1789549200).toISOString(), "2026-09-16T09:00:00.000Z");+ assert.equal(parseReceivedAt(1789549200000).toISOString(), "2026-09-16T09:00:00.000Z");+ assert.equal(parseReceivedAt("not a date"), null);+ assert.equal(parseReceivedAt(""), null);+ assert.equal(parseReceivedAt(undefined), null);+ assert.equal(parseReceivedAt(Number.NaN), null);+});++test("an import targets exactly one writable Drafts mailbox", () => {+ assert.deepEqual(resolveDraftsMailbox({ [DRAFTS]: true }, writable), { mailboxId: "mbx1" });+ assert.deepEqual(resolveDraftsMailbox([DRAFTS], writable), { mailboxId: "mbx1" });+});++test("anything but a Drafts mailbox is rejected as invalidProperties on mailboxIds", () => {+ for (const [name, mailboxIds] of [+ ["no mailbox", {}],+ ["two mailboxes", { [DRAFTS]: true, [INBOX]: true }],+ ["the inbox", { [INBOX]: true }],+ ["a user folder", { [FOLDER]: true }],+ ["the account mailbox", { mbx1: true }],+ ["an unknown mailbox", { "mbx9~drafts": true }],+ ["a read-only mailbox", { "mbx2~drafts": true }],+ ["a malformed id", { "~~": true }],+ ]) {+ const result = resolveDraftsMailbox(mailboxIds, writable);+ assert.ok("error" in result, `${name} should be rejected`);+ assert.equal(result.error.type, "invalidProperties", name);+ assert.deepEqual(result.error.properties, ["mailboxIds"], name);+ }+});++test("a Message-ID header filter compares without angle brackets", () => {+ const withBrackets = renderFilter({ header: ["Message-ID", "<[email protected]>"] });+ const without = renderFilter({ header: ["Message-ID", "[email protected]"] });+ const padded = renderFilter({ header: ["Message-ID", " <[email protected]> "] });+ assert.deepEqual(withBrackets.params, ["[email protected]", "<[email protected]>"]);+ assert.deepEqual(without.params, withBrackets.params);+ assert.deepEqual(padded.params, withBrackets.params);+ assert.match(withBrackets.sql, /provider_message_id/);+});++test("the header name is matched case-insensitively", () => {+ const upper = renderFilter({ header: ["MESSAGE-ID", "<[email protected]>"] });+ const lower = renderFilter({ header: ["message-id", "<[email protected]>"] });+ assert.equal(upper.sql, lower.sql);+ assert.deepEqual(upper.params, lower.params);+});++test("In-Reply-To and References map onto their own columns", () => {+ const inReplyTo = renderFilter({ header: ["In-Reply-To", "<[email protected]>"] });+ assert.match(inReplyTo.sql, /in_reply_to/);+ assert.deepEqual(inReplyTo.params, ["[email protected]", "<[email protected]>"]);++ // The column is the space-joined chain, so the pattern is padded and matches whole ids only.+ const references = renderFilter({ header: ["References", "<[email protected]>"] });+ assert.match(references.sql, /references_header/);+ assert.deepEqual(references.params, ["% [email protected] %"]);+});++test("the one-element form asks whether the header is present at all", () => {+ assert.match(renderFilter({ header: ["Message-ID"] }).sql, /provider_message_id" is not null/);+ assert.match(renderFilter({ header: ["In-Reply-To"] }).sql, /in_reply_to" is not null/);+ assert.match(renderFilter({ header: ["References"] }).sql, /references_header" is not null/);+ assert.deepEqual(renderFilter({ header: ["Message-ID"] }).params, []);+});++test("a header Mailflare cannot answer is an unsupportedFilter error, not a match-all (RFC 8620 §5.5)", () => {+ for (const header of [["X-Unknown"], ["X-Mailer", "Flectar"], ["Reply-To", "[email protected]"]]) {+ assert.throws(() => filterToSql({ header }, writable), (error) => error.type === "unsupportedFilter", JSON.stringify(header));+ }+ // Nested in an operator tree it must still surface rather than drop the condition.+ assert.throws(+ () => filterToSql({ operator: "AND", conditions: [{ inMailbox: DRAFTS }, { header: ["X-Unknown"] }] }, writable),+ (error) => error.type === "unsupportedFilter",+ );+});++test("a malformed header condition is invalidArguments", () => {+ for (const header of [[], ["Message-ID", "a", "b"], [42]]) {+ assert.throws(() => filterToSql({ header }, writable), (error) => error.type === "invalidArguments", JSON.stringify(header));+ }+});++test("the de-duplication query a client sends narrows the mailbox instead of matching every draft", () => {+ // Flectar's query_draft_by_message_id: { inMailbox: drafts, header: ["Message-ID", id] }.+ const query = renderFilter({ inMailbox: DRAFTS, header: ["Message-ID", "<[email protected]>"] });+ assert.match(query.sql, /mailbox_id/);+ assert.match(query.sql, /provider_message_id/);+ assert.ok(query.params.includes("[email protected]"), query.params);+ assert.ok(query.params.includes("mbx1"), query.params);++ // Without the Message-ID the same query is only the mailbox predicate, which is+ // what every draft used to match.+ const unfiltered = renderFilter({ inMailbox: DRAFTS });+ assert.doesNotMatch(unfiltered.sql, /provider_message_id/);+ assert.ok(query.sql.length > unfiltered.sql.length);+});