Skip to content

Email for professionals and teams

feat(jmap): JMAP server for external mail clients

Oday Bakkour3655f616bec8
diff --git a/CLAUDE.md b/CLAUDE.md
index 5a1b6e7..82f51a2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -79,6 +79,10 @@ Schema lives in one file: `src/db/schema/index.ts` (21 tables). Migrations are g
The setup path only ever initializes an empty database — it refuses to touch one that already has tables.
+### JMAP lives in `src/lib/jmap/`
+
+`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`.
+
### Access control
Two independent auth surfaces:
diff --git a/docs/api.md b/docs/api.md
index eeccbd8..41e1550 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -57,6 +57,12 @@ Messages composed in Mailflare are sent as HTML with a plain-text alternative de
The dashboard composer accepts up to 10 attachments, with a 10 MB limit per file and a 20 MB combined limit. Attachment metadata is stored in D1 and file content is stored in R2. Downloads require access to the mailbox containing the message.
+## JMAP
+
+Mailflare 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`.
+
## Real-time updates
Mailflare uses a Durable Object WebSocket hub to notify connected users after an inbound message is stored. Mailbox owners, the domain administrator, and delegated users receive events for mailboxes they can access.
diff --git a/src/app/.well-known/jmap/route.ts b/src/app/.well-known/jmap/route.ts
new file mode 100644
index 0000000..c0110de
--- /dev/null
+++ b/src/app/.well-known/jmap/route.ts
@@ -0,0 +1,8 @@
+import { getEnv } from "@/lib/cloudflare";
+import { handleJmapRequest } from "@/lib/jmap/handler";
+
+/** RFC 8620 §2.2 autodiscovery: redirects to the Session resource. */
+export async function GET(request: Request) {
+ return (await handleJmapRequest(request, getEnv())) ?? new Response("Not found", { status: 404 });
+}
+export const dynamic = "force-dynamic";
diff --git a/src/app/api/api-keys/route.ts b/src/app/api/api-keys/route.ts
index 2171f44..3645543 100644
--- a/src/app/api/api-keys/route.ts
+++ b/src/app/api/api-keys/route.ts
@@ -10,7 +10,7 @@ import { newId } from "@/lib/ids";
const createKeySchema = z.object({
name: z.string().min(1),
- scopes: z.array(z.enum(["send", "read"])).min(1),
+ scopes: z.array(z.enum(["send", "read", "jmap"])).min(1),
});
export async function GET(request: Request) {
diff --git a/src/app/jmap/[[...segments]]/route.ts b/src/app/jmap/[[...segments]]/route.ts
new file mode 100644
index 0000000..41913b0
--- /dev/null
+++ b/src/app/jmap/[[...segments]]/route.ts
@@ -0,0 +1,11 @@
+import { getEnv } from "@/lib/cloudflare";
+import { handleJmapRequest } from "@/lib/jmap/handler";
+
+async function handle(request: Request) {
+ return (await handleJmapRequest(request, getEnv())) ?? new Response("Not found", { status: 404 });
+}
+
+export const GET = handle;
+export const POST = handle;
+export const OPTIONS = handle;
+export const dynamic = "force-dynamic";
diff --git a/src/components/settings/account-settings.tsx b/src/components/settings/account-settings.tsx
index 79b1e46..d4683d6 100644
--- a/src/components/settings/account-settings.tsx
+++ b/src/components/settings/account-settings.tsx
@@ -3,6 +3,7 @@
import { useEffect, useState } from "react";
import { Skeleton } from "@/components/ui/skeleton";
import { ChangePasswordForm } from "./change-password-form";
+import { EmailClientsSettings } from "./email-clients-settings";
import { ForwardingEmailForm } from "./forwarding-email-form";
import { MailboxSignatureForm } from "./mailbox-signature-form";
import { ProfileForm } from "./profile-form";
@@ -94,6 +95,16 @@ export function AccountSettings() {
<ChangePasswordForm />
</div>
</section>
+
+ <section className="space-y-4">
+ <div>
+ <h2 className="text-xl font-semibold text-neutral-900">Email apps</h2>
+ <p className="mt-1 text-sm text-neutral-500">Use your mail from a desktop or mobile app over JMAP.</p>
+ </div>
+ <div className="space-y-4 rounded-3xl bg-white p-6">
+ <EmailClientsSettings />
+ </div>
+ </section>
</div>
);
}
diff --git a/src/components/settings/email-clients-settings.tsx b/src/components/settings/email-clients-settings.tsx
new file mode 100644
index 0000000..ecf18e7
--- /dev/null
+++ b/src/components/settings/email-clients-settings.tsx
@@ -0,0 +1,82 @@
+"use client";
+
+import { useState } from "react";
+import { Copy, KeyRound } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { createJmapApiKey } from "./utils";
+
+/**
+ * Settings > Account card for connecting an external mail app over JMAP.
+ * Mints an API key with the `jmap` scope and shows the details once.
+ */
+export function EmailClientsSettings() {
+ const [name, setName] = useState("");
+ const [key, setKey] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [copied, setCopied] = useState<string | null>(null);
+ const server = typeof window !== "undefined" ? window.location.origin : "";
+
+ async function submit(event: React.FormEvent) {
+ event.preventDefault();
+ setBusy(true);
+ setError(null);
+ try {
+ setKey(await createJmapApiKey(name.trim() || "Mail app"));
+ setName("");
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Could not create a key");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ function copy(label: string, value: string) {
+ void navigator.clipboard.writeText(value).then(() => setCopied(label));
+ }
+
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-neutral-500">
+ Apps that speak JMAP (Mailtemi, Twake Mail, aerc, and others) can read and send your mail. Point the app at this server and sign in with your email address and an API key as the password.
+ </p>
+ {key ? (
+ <div className="space-y-3 rounded-2xl bg-neutral-50 p-4">
+ <Field label="Server" value={server} onCopy={copy} copied={copied} />
+ <Field label="Username" value="any value" onCopy={copy} copied={copied} />
+ <Field label="Password (API key)" value={key} onCopy={copy} copied={copied} mono />
+ <p className="text-xs text-neutral-500">
+ This key is shown once. It can be revoked from the API keys page. Session discovery is at <code>{server}/.well-known/jmap</code>.
+ </p>
+ </div>
+ ) : (
+ <form onSubmit={submit} className="flex flex-wrap items-end gap-3">
+ <div className="min-w-56 flex-1 space-y-2">
+ <Label htmlFor="jmap-key-name">Device or app name</Label>
+ <Input id="jmap-key-name" value={name} onChange={(event) => setName(event.target.value)} placeholder="Phone" />
+ </div>
+ <Button type="submit" disabled={busy}>
+ <KeyRound className="h-4 w-4" />
+ {busy ? "Creating..." : "Create app password"}
+ </Button>
+ {error && <p className="w-full text-sm text-red-600">{error}</p>}
+ </form>
+ )}
+ </div>
+ );
+}
+
+function Field({ label, value, onCopy, copied, mono }: { label: string; value: string; onCopy: (label: string, value: string) => void; copied: string | null; mono?: boolean }) {
+ return (
+ <div className="flex items-center gap-3">
+ <span className="w-36 shrink-0 text-xs font-medium uppercase tracking-wide text-neutral-500">{label}</span>
+ <code className={`min-w-0 flex-1 truncate rounded-md bg-white px-2 py-1 text-sm ${mono ? "font-mono" : "font-sans"}`}>{value}</code>
+ <Button type="button" variant="ghost" size="sm" onClick={() => onCopy(label, value)} aria-label={`Copy ${label}`}>
+ <Copy className="h-4 w-4" />
+ {copied === label ? "Copied" : "Copy"}
+ </Button>
+ </div>
+ );
+}
diff --git a/src/components/settings/utils.ts b/src/components/settings/utils.ts
index 734c3b8..59909f0 100644
--- a/src/components/settings/utils.ts
+++ b/src/components/settings/utils.ts
@@ -112,3 +112,15 @@ export async function updatePassword(currentPassword: string, newPassword: strin
throw new Error(typeof data.error === "string" ? data.error : "Failed to change password");
}
}
+
+/** An API key limited to the JMAP scope, for external mail apps. */
+export async function createJmapApiKey(name: string): Promise<string> {
+ const res = await authFetch("/api/api-keys", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name, scopes: ["jmap"] }),
+ });
+ const data = (await res.json()) as { key?: string; error?: unknown };
+ if (!res.ok || !data.key) throw new Error(typeof data.error === "string" ? data.error : "Could not create a key");
+ return data.key;
+}
diff --git a/src/lib/api/auth.ts b/src/lib/api/auth.ts
index 7d1e118..ffa629b 100644
--- a/src/lib/api/auth.ts
+++ b/src/lib/api/auth.ts
@@ -1,50 +1,19 @@
-import { eq } from "drizzle-orm";
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth/cookies";
-import { getDb } from "@/db";
-import { apiKeys, users } from "@/db/schema";
-import { verifyApiKey, parseScopes } from "@/lib/api-keys";
+import { authenticateApiKeyValue, hasScope } from "@/lib/api/key-auth";
+import type { ApiAuthResult } from "@/lib/api/key-auth-types";
-export type ApiAuthResult = {
- userId: string;
- email: string;
- scopes: string[];
-};
+export type { ApiAuthResult };
export async function authenticateApiKey(
env: CloudflareEnv,
authorization: string | null,
): Promise<ApiAuthResult | null> {
if (!authorization?.startsWith("Bearer ")) return null;
- const key = authorization.slice(7).trim();
- if (!key) return null;
-
- const prefix = key.slice(0, 12);
- const db = getDb(env);
- const candidates = await db.select().from(apiKeys).where(eq(apiKeys.prefix, prefix));
-
- for (const candidate of candidates) {
- if (!verifyApiKey(key, candidate.keyHash)) continue;
- const [user] = await db.select().from(users).where(eq(users.id, candidate.userId)).limit(1);
- if (!user || user.disabled) continue;
-
- await db
- .update(apiKeys)
- .set({ lastUsedAt: new Date() })
- .where(eq(apiKeys.id, candidate.id));
-
- return {
- userId: user.id,
- email: user.email,
- scopes: parseScopes(candidate.scopes),
- };
- }
- return null;
+ return authenticateApiKeyValue(env, authorization.slice(7));
}
-export function requireScope(scopes: string[], required: string): boolean {
- return scopes.includes(required) || scopes.includes("*");
-}
+export const requireScope = hasScope;
/**
* Session auth for route handlers. `requireUser` throws a bare Error, which Next turns into
diff --git a/src/lib/api/key-auth-types.d.ts b/src/lib/api/key-auth-types.d.ts
new file mode 100644
index 0000000..a8803a5
--- /dev/null
+++ b/src/lib/api/key-auth-types.d.ts
@@ -0,0 +1,8 @@
+import type { users } from "@/db/schema";
+
+export type ApiAuthResult = {
+ userId: string;
+ email: string;
+ scopes: string[];
+ user: typeof users.$inferSelect;
+};
diff --git a/src/lib/api/key-auth.ts b/src/lib/api/key-auth.ts
new file mode 100644
index 0000000..8b45446
--- /dev/null
+++ b/src/lib/api/key-auth.ts
@@ -0,0 +1,59 @@
+import { and, eq, lt, or, isNull } from "drizzle-orm";
+import { getDb } from "@/db";
+import { apiKeys, users } from "@/db/schema";
+import { parseScopes, verifyApiKey } from "@/lib/api-keys";
+import type { ApiAuthResult } from "@/lib/api/key-auth-types";
+
+const LAST_USED_WRITE_INTERVAL_MS = 60_000;
+
+/**
+ * Resolve an API key to its user and scopes. Framework-free so it can run in
+ * `worker.ts` as well as route handlers. `lastUsedAt` is refreshed at most
+ * once a minute per key, since protocol clients make many small calls.
+ */
+export async function authenticateApiKeyValue(env: CloudflareEnv, key: string): Promise<ApiAuthResult | null> {
+ const trimmed = key.trim();
+ if (!trimmed) return null;
+ const prefix = trimmed.slice(0, 12);
+ const db = getDb(env);
+ const candidates = await db.select().from(apiKeys).where(eq(apiKeys.prefix, prefix));
+
+ for (const candidate of candidates) {
+ if (!verifyApiKey(trimmed, candidate.keyHash)) continue;
+ const [user] = await db.select().from(users).where(eq(users.id, candidate.userId)).limit(1);
+ if (!user || user.disabled) continue;
+
+ const stale = new Date(Date.now() - LAST_USED_WRITE_INTERVAL_MS);
+ await db
+ .update(apiKeys)
+ .set({ lastUsedAt: new Date() })
+ .where(and(eq(apiKeys.id, candidate.id), or(isNull(apiKeys.lastUsedAt), lt(apiKeys.lastUsedAt, stale))));
+
+ return { userId: user.id, email: user.email, scopes: parseScopes(candidate.scopes), user };
+ }
+ return null;
+}
+
+/**
+ * JMAP clients send the key either as a Bearer token or as the password of
+ * HTTP Basic auth (the username is ignored; the key identifies the account).
+ */
+export async function authenticateApiRequest(env: CloudflareEnv, request: Request): Promise<ApiAuthResult | null> {
+ const authorization = request.headers.get("Authorization") ?? "";
+ if (authorization.startsWith("Bearer ")) return authenticateApiKeyValue(env, authorization.slice(7));
+ if (authorization.startsWith("Basic ")) {
+ let decoded = "";
+ try {
+ decoded = atob(authorization.slice(6).trim());
+ } catch {
+ return null;
+ }
+ const separator = decoded.indexOf(":");
+ return authenticateApiKeyValue(env, separator >= 0 ? decoded.slice(separator + 1) : decoded);
+ }
+ return null;
+}
+
+export function hasScope(scopes: string[], required: string): boolean {
+ return scopes.includes(required) || scopes.includes("*");
+}
diff --git a/src/lib/jmap/access.ts b/src/lib/jmap/access.ts
new file mode 100644
index 0000000..733e807
--- /dev/null
+++ b/src/lib/jmap/access.ts
@@ -0,0 +1,47 @@
+import { and, eq, inArray } from "drizzle-orm";
+import { folders, mailboxes } from "@/db/schema";
+import { listAccessibleMailboxes } from "@/lib/mailboxes/access";
+import { getMailboxDomainAddresses } from "@/lib/mailboxes/domain-addresses";
+import type { AccessibleMailbox, JmapContext } from "./types";
+
+/** Every Mailflare mailbox the key's user can read, in a JMAP-shaped record. */
+export async function listJmapMailboxes(ctx: JmapContext): Promise<AccessibleMailbox[]> {
+ const rows = await listAccessibleMailboxes(ctx.db, ctx.auth.user);
+ return rows.map((row) => ({
+ id: row.id,
+ userId: row.userId,
+ localPart: row.localPart,
+ hostname: row.hostname,
+ displayName: row.displayName,
+ permission: row.permission,
+ type: row.type,
+ isPrimary: row.isPrimary,
+ }));
+}
+
+export async function listAccessibleMailboxIdSet(ctx: JmapContext): Promise<Set<string>> {
+ return new Set((await listJmapMailboxes(ctx)).map((row) => row.id));
+}
+
+/** User folders for a set of mailboxes, keyed by mailbox id. */
+export async function listFoldersByMailbox(ctx: JmapContext, mailboxIds: string[]): Promise<Map<string, Array<{ id: string; name: string }>>> {
+ const result = new Map<string, Array<{ id: string; name: string }>>();
+ if (mailboxIds.length === 0) return result;
+ const rows = await ctx.db
+ .select({ id: folders.id, mailboxId: folders.mailboxId, name: folders.name })
+ .from(folders)
+ .where(inArray(folders.mailboxId, mailboxIds));
+ for (const row of rows) {
+ const list = result.get(row.mailboxId) ?? [];
+ list.push({ id: row.id, name: row.name });
+ result.set(row.mailboxId, list);
+ }
+ return result;
+}
+
+/** Addresses each mailbox may send from, for Identity objects. */
+export async function listSendableAddresses(ctx: JmapContext, mailbox: AccessibleMailbox): Promise<string[]> {
+ const [row] = await ctx.db.select().from(mailboxes).where(and(eq(mailboxes.id, mailbox.id))).limit(1);
+ if (!row) return [];
+ return getMailboxDomainAddresses(ctx.db, row);
+}
diff --git a/src/lib/jmap/blobs.ts b/src/lib/jmap/blobs.ts
new file mode 100644
index 0000000..05da51c
--- /dev/null
+++ b/src/lib/jmap/blobs.ts
@@ -0,0 +1,74 @@
+import { and, eq } from "drizzle-orm";
+import { messageAttachments, messages } from "@/db/schema";
+import { newId } from "@/lib/ids";
+import { LIMITS } from "./constants";
+import { decodeBlobId, uploadBlobId } from "./ids";
+import { listAccessibleMailboxIdSet } from "./access";
+import type { JmapContext } from "./types";
+
+const UPLOAD_PREFIX = "jmap-uploads";
+
+/** 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, {
+ httpMetadata: { contentType: type },
+ customMetadata: { userId: ctx.auth.userId, ...(name ? { name } : {}) },
+ });
+ return { accountId: ctx.accountId, blobId: uploadBlobId(id), type, size: body.byteLength };
+}
+
+export async function readUpload(ctx: JmapContext, uploadId: string) {
+ const object = await ctx.env.BUCKET.get(`${UPLOAD_PREFIX}/${ctx.auth.userId}/${uploadId}`);
+ if (!object) return null;
+ return { content: await object.arrayBuffer(), type: object.httpMetadata?.contentType ?? "application/octet-stream", name: object.customMetadata?.name ?? null };
+}
+
+/**
+ * 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.
+ */
+export async function readBlob(ctx: JmapContext, blobId: string): Promise<{ body: ReadableStream | ArrayBuffer; type: string; name: string | null; size: number } | null> {
+ const decoded = decodeBlobId(blobId);
+ if (!decoded) return null;
+ const accessible = await listAccessibleMailboxIdSet(ctx);
+
+ if (decoded.kind === "up") {
+ const upload = await readUpload(ctx, decoded.id);
+ return upload ? { body: upload.content, type: upload.type, name: upload.name, size: upload.content.byteLength } : null;
+ }
+ if (decoded.kind === "att") {
+ const [row] = await ctx.db
+ .select({ r2Key: messageAttachments.r2Key, filename: messageAttachments.filename, type: messageAttachments.contentType, size: messageAttachments.size, mailboxId: messages.mailboxId })
+ .from(messageAttachments)
+ .innerJoin(messages, eq(messageAttachments.messageId, messages.id))
+ .where(eq(messageAttachments.id, decoded.id))
+ .limit(1);
+ if (!row || !row.mailboxId || !accessible.has(row.mailboxId)) return null;
+ const object = await ctx.env.BUCKET.get(row.r2Key);
+ return object ? { body: object.body, type: row.type, name: row.filename, size: row.size } : null;
+ }
+ const [row] = await ctx.db.select().from(messages).where(and(eq(messages.id, decoded.id))).limit(1);
+ if (!row || !row.mailboxId || !accessible.has(row.mailboxId)) return null;
+ if (row.rawR2Key) {
+ const object = await ctx.env.BUCKET.get(row.rawR2Key);
+ if (object) return { body: object.body, type: "message/rfc822", name: `${row.id}.eml`, size: object.size };
+ }
+ // Outbound and imported mail keeps no raw copy; rebuild a minimal RFC 5322 message.
+ const lines = [
+ `From: ${row.fromAddr}`,
+ `To: ${row.toAddr}`,
+ ...(row.ccAddr ? [`Cc: ${row.ccAddr}`] : []),
+ `Subject: ${row.subject ?? ""}`,
+ `Date: ${row.createdAt.toUTCString()}`,
+ ...(row.providerMessageId ? [`Message-ID: ${row.providerMessageId}`] : []),
+ ...(row.inReplyTo ? [`In-Reply-To: <${row.inReplyTo}>`] : []),
+ "MIME-Version: 1.0",
+ `Content-Type: ${row.htmlBody ? "text/html" : "text/plain"}; charset=utf-8`,
+ "",
+ row.htmlBody ?? row.textBody ?? "",
+ ];
+ const bytes = new TextEncoder().encode(lines.join("\r\n"));
+ return { body: bytes.buffer as ArrayBuffer, type: "message/rfc822", name: `${row.id}.eml`, size: bytes.byteLength };
+}
diff --git a/src/lib/jmap/constants.ts b/src/lib/jmap/constants.ts
new file mode 100644
index 0000000..baae9df
--- /dev/null
+++ b/src/lib/jmap/constants.ts
@@ -0,0 +1,18 @@
+export const CAPABILITY_CORE = "urn:ietf:params:jmap:core";
+export const CAPABILITY_MAIL = "urn:ietf:params:jmap:mail";
+export const CAPABILITY_SUBMISSION = "urn:ietf:params:jmap:submission";
+
+export const LIMITS = {
+ maxSizeUpload: 10 * 1024 * 1024,
+ maxSizeRequest: 10 * 1024 * 1024,
+ maxCallsInRequest: 32,
+ maxObjectsInGet: 200,
+ maxObjectsInSet: 100,
+ maxSizeAttachmentsPerEmail: 20 * 1024 * 1024,
+ /** Email/query never returns more than this many ids per call. */
+ maxQueryLimit: 250,
+};
+
+export const KEYWORD_SEEN = "$seen";
+export const KEYWORD_FLAGGED = "$flagged";
+export const KEYWORD_DRAFT = "$draft";
diff --git a/src/lib/jmap/email-objects.ts b/src/lib/jmap/email-objects.ts
new file mode 100644
index 0000000..774cc60
--- /dev/null
+++ b/src/lib/jmap/email-objects.ts
@@ -0,0 +1,192 @@
+import { inArray } from "drizzle-orm";
+import { messageAttachments, messages } from "@/db/schema";
+import { parseEmailAddressParts, splitEmailAddressList } from "@/lib/email/address";
+import { htmlToReadableText } from "@/lib/email/reply-content-utils";
+import { KEYWORD_DRAFT, KEYWORD_FLAGGED, KEYWORD_SEEN } from "./constants";
+import { attachmentBlobId, encodeMailboxRef, messageBlobId, statusToRole } from "./ids";
+import type { EmailAddressObject, EmailBodyPart, JmapContext } from "./types";
+
+type MessageRow = typeof messages.$inferSelect;
+type AttachmentRow = typeof messageAttachments.$inferSelect;
+
+export function toAddressObjects(value: string | null | undefined): EmailAddressObject[] | null {
+ const entries = splitEmailAddressList(value);
+ if (entries.length === 0) return null;
+ return entries.map((entry) => {
+ const parts = parseEmailAddressParts(entry);
+ return { name: parts.name, email: parts.address };
+ });
+}
+
+export function mailboxIdsFor(row: MessageRow): Record<string, boolean> {
+ if (!row.mailboxId) return {};
+ if (row.folderId) return { [encodeMailboxRef({ kind: "folder", mailboxId: row.mailboxId, folderId: row.folderId })]: true };
+ const role = statusToRole(row.status);
+ return role ? { [encodeMailboxRef({ kind: "role", mailboxId: row.mailboxId, role })]: true } : {};
+}
+
+export function keywordsFor(row: MessageRow): Record<string, boolean> {
+ const keywords: Record<string, boolean> = {};
+ if (row.read || row.direction === "outbound") keywords[KEYWORD_SEEN] = true;
+ if (row.starred) keywords[KEYWORD_FLAGGED] = true;
+ if (row.status === "draft") keywords[KEYWORD_DRAFT] = true;
+ return keywords;
+}
+
+export function threadIdFor(row: Pick<MessageRow, "id" | "threadId">): string {
+ return row.threadId ?? row.id;
+}
+
+function stripBrackets(value: string | null): string | null {
+ const trimmed = value?.trim().replace(/^<|>$/g, "");
+ return trimmed || null;
+}
+
+function bodyPart(partId: string, type: string, size: number): EmailBodyPart {
+ return { partId, blobId: null, size, headers: [], name: null, type, charset: "utf-8", disposition: null, cid: null, language: null, location: null };
+}
+
+function attachmentPart(attachment: AttachmentRow): EmailBodyPart {
+ return {
+ partId: null,
+ blobId: attachmentBlobId(attachment.id),
+ size: attachment.size,
+ headers: [],
+ name: attachment.filename,
+ type: attachment.contentType,
+ charset: null,
+ disposition: attachment.disposition,
+ cid: attachment.contentId ? attachment.contentId.replace(/^<|>$/g, "") : null,
+ language: null,
+ location: null,
+ };
+}
+
+/**
+ * The Email object (RFC 8621 §4.1) from a stored row. Bodies are the parsed
+ * text and HTML Mailflare keeps; attachments become parts with blob ids the
+ * download endpoint understands. Property filtering happens in the caller.
+ */
+export function buildEmailObject(row: MessageRow, attachments: AttachmentRow[], options: { fetchBodies: boolean; maxBodyValueBytes: number }) {
+ const text = row.textBody ?? "";
+ const html = row.htmlBody ?? "";
+ const textSize = new TextEncoder().encode(text).length;
+ const htmlSize = new TextEncoder().encode(html).length;
+ const textPart = text ? bodyPart("1", "text/plain", textSize) : null;
+ const htmlPart = html ? bodyPart("2", "text/html", htmlSize) : null;
+ const inline = attachments.filter((item) => item.disposition === "inline");
+ const attached = attachments.filter((item) => item.disposition !== "inline");
+
+ let structure: EmailBodyPart;
+ const bodyParts = [textPart, htmlPart].filter((part): part is EmailBodyPart => !!part);
+ const alternative: EmailBodyPart | null =
+ bodyParts.length > 1
+ ? { partId: null, blobId: null, size: textSize + htmlSize, name: null, type: "multipart/alternative", charset: null, disposition: null, cid: null, language: null, location: null, subParts: bodyParts }
+ : bodyParts[0] ?? bodyPart("1", "text/plain", 0);
+ if (attachments.length > 0) {
+ structure = { partId: null, blobId: null, size: 0, name: null, type: "multipart/mixed", charset: null, disposition: null, cid: null, language: null, location: null, subParts: [alternative, ...inline.map(attachmentPart), ...attached.map(attachmentPart)] };
+ } else {
+ structure = alternative;
+ }
+
+ const bodyValues: Record<string, { value: string; isEncodingProblem: boolean; isTruncated: boolean }> = {};
+ if (options.fetchBodies) {
+ const clip = (value: string) => {
+ const limit = options.maxBodyValueBytes;
+ if (!limit || value.length <= limit) return { value, isEncodingProblem: false, isTruncated: false };
+ return { value: value.slice(0, limit), isEncodingProblem: false, isTruncated: true };
+ };
+ if (textPart) bodyValues["1"] = clip(text);
+ if (htmlPart) bodyValues["2"] = clip(html);
+ }
+
+ const size = textSize + htmlSize + attachments.reduce((total, item) => total + item.size, 0);
+ const preview = (row.snippet ?? htmlToReadableText(html) ?? text).replace(/\s+/g, " ").trim().slice(0, 256);
+ const references = row.references ? row.references.split(/\s+/).filter(Boolean) : null;
+ const from = toAddressObjects(row.fromAddr);
+ const sentAt = row.createdAt.toISOString();
+
+ return {
+ id: row.id,
+ blobId: messageBlobId(row.id),
+ threadId: threadIdFor(row),
+ mailboxIds: mailboxIdsFor(row),
+ keywords: keywordsFor(row),
+ size,
+ receivedAt: sentAt,
+ messageId: stripBrackets(row.providerMessageId) ? [stripBrackets(row.providerMessageId)!] : null,
+ inReplyTo: row.inReplyTo ? [row.inReplyTo] : null,
+ references,
+ sender: from,
+ from,
+ to: toAddressObjects(row.toAddr),
+ cc: toAddressObjects(row.ccAddr),
+ bcc: toAddressObjects(row.bccAddr),
+ replyTo: null,
+ subject: row.subject,
+ sentAt,
+ hasAttachment: attached.length > 0,
+ preview,
+ bodyStructure: structure,
+ bodyValues,
+ textBody: textPart ? [textPart] : htmlPart ? [htmlPart] : [],
+ htmlBody: htmlPart ? [htmlPart] : textPart ? [textPart] : [],
+ attachments: [...inline, ...attached].map(attachmentPart),
+ };
+}
+
+/** Attachment rows for many messages in one query, keyed by message id. */
+export async function loadAttachmentsByMessage(ctx: JmapContext, messageIds: string[]): Promise<Map<string, AttachmentRow[]>> {
+ const result = new Map<string, AttachmentRow[]>();
+ if (messageIds.length === 0) return result;
+ const rows = await ctx.db.select().from(messageAttachments).where(inArray(messageAttachments.messageId, messageIds));
+ for (const row of rows) {
+ const list = result.get(row.messageId) ?? [];
+ list.push(row);
+ result.set(row.messageId, list);
+ }
+ return result;
+}
+
+/** `header:Name[:asForm]` properties, answered from stored fields; unknown headers are null. */
+export function resolveHeaderProperty(row: MessageRow, property: string): unknown {
+ const [, name, form] = property.split(":");
+ const lower = (name ?? "").toLowerCase();
+ const raw = (() => {
+ switch (lower) {
+ case "subject":
+ return row.subject;
+ case "from":
+ return row.fromAddr;
+ case "to":
+ return row.toAddr;
+ case "cc":
+ return row.ccAddr;
+ case "bcc":
+ return row.bccAddr;
+ case "message-id":
+ return row.providerMessageId;
+ case "in-reply-to":
+ return row.inReplyTo ? `<${row.inReplyTo}>` : null;
+ case "references":
+ return row.references ? row.references.split(/\s+/).map((id) => `<${id}>`).join(" ") : null;
+ case "date":
+ return row.createdAt.toUTCString();
+ default:
+ return null;
+ }
+ })();
+ if (raw == null) return null;
+ switch ((form ?? "asRaw").toLowerCase()) {
+ case "asaddresses":
+ return toAddressObjects(raw);
+ case "asmessageids":
+ return raw.split(/\s+/).map((id) => id.replace(/^<|>$/g, "")).filter(Boolean);
+ case "asdate":
+ return row.createdAt.toISOString();
+ case "astext":
+ return raw;
+ default:
+ return ` ${raw}`;
+ }
+}
diff --git a/src/lib/jmap/email-query.ts b/src/lib/jmap/email-query.ts
new file mode 100644
index 0000000..450790a
--- /dev/null
+++ b/src/lib/jmap/email-query.ts
@@ -0,0 +1,131 @@
+import { and, asc, desc, eq, exists, gt, gte, inArray, 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 { decodeMailboxRef, roleToStatus } from "./ids";
+import type { Comparator, Filter, FilterCondition, MailboxRef } from "./types";
+
+/** The SQL predicate for "is in this JMAP Mailbox". */
+export function mailboxRefCondition(ref: MailboxRef): SQL {
+ const base = eq(messages.mailboxId, ref.mailboxId);
+ if (ref.kind === "account") return base;
+ if (ref.kind === "folder") return and(base, eq(messages.folderId, ref.folderId))!;
+ const status = roleToStatus(ref.role);
+ if (ref.role === "inbox") return and(base, eq(messages.status, status), isNull(messages.folderId))!;
+ if (ref.role === "sent") return and(base, inArray(messages.status, ["sent", "queued", "failed"]), isNull(messages.folderId))!;
+ return and(base, eq(messages.status, status), isNull(messages.folderId))!;
+}
+
+function keywordCondition(keyword: string, present: boolean): SQL {
+ switch (keyword) {
+ case KEYWORD_SEEN:
+ return present ? or(eq(messages.read, true), eq(messages.direction, "outbound"))! : and(eq(messages.read, false), eq(messages.direction, "inbound"))!;
+ case KEYWORD_FLAGGED:
+ return eq(messages.starred, present);
+ case KEYWORD_DRAFT:
+ return present ? eq(messages.status, "draft") : ne(messages.status, "draft");
+ default:
+ // Unknown keywords are never set, so "has" matches nothing and "not" matches all.
+ return present ? sql`0` : sql`1`;
+ }
+}
+
+function likePattern(value: string): string {
+ return `%${value.replace(/[%_\\]/g, (char) => `\\${char}`)}%`;
+}
+
+function conditionToSql(condition: FilterCondition, accessible: Set<string>): SQL[] {
+ const parts: SQL[] = [];
+ if (condition.inMailbox !== undefined) {
+ const ref = decodeMailboxRef(condition.inMailbox);
+ if (!ref || !accessible.has(ref.mailboxId)) throw invalidArguments(`Unknown mailbox ${condition.inMailbox}`);
+ parts.push(mailboxRefCondition(ref));
+ }
+ if (condition.inMailboxOtherThan) {
+ for (const id of condition.inMailboxOtherThan) {
+ const ref = decodeMailboxRef(id);
+ if (ref && accessible.has(ref.mailboxId)) parts.push(not(mailboxRefCondition(ref)));
+ }
+ }
+ if (condition.before) parts.push(lt(messages.createdAt, new Date(condition.before)));
+ if (condition.after) parts.push(gte(messages.createdAt, new Date(condition.after)));
+ if (condition.hasKeyword) parts.push(keywordCondition(condition.hasKeyword, true));
+ if (condition.notKeyword) parts.push(keywordCondition(condition.notKeyword, false));
+ if (condition.someInThreadHaveKeyword) parts.push(keywordCondition(condition.someInThreadHaveKeyword, true));
+ if (condition.allInThreadHaveKeyword) parts.push(keywordCondition(condition.allInThreadHaveKeyword, true));
+ if (condition.noneInThreadHaveKeyword) parts.push(keywordCondition(condition.noneInThreadHaveKeyword, false));
+ if (condition.from) parts.push(like(messages.fromAddr, likePattern(condition.from)));
+ if (condition.to) parts.push(like(messages.toAddr, likePattern(condition.to)));
+ if (condition.cc) parts.push(like(messages.ccAddr, likePattern(condition.cc)));
+ if (condition.bcc) parts.push(like(messages.bccAddr, likePattern(condition.bcc)));
+ if (condition.subject) parts.push(like(messages.subject, likePattern(condition.subject)));
+ if (condition.body) parts.push(or(like(messages.textBody, likePattern(condition.body)), like(messages.htmlBody, likePattern(condition.body)))!);
+ if (condition.text) {
+ const pattern = likePattern(condition.text);
+ parts.push(
+ or(
+ like(messages.subject, pattern),
+ like(messages.fromAddr, pattern),
+ like(messages.toAddr, pattern),
+ like(messages.ccAddr, pattern),
+ like(messages.textBody, pattern),
+ like(messages.snippet, pattern),
+ )!,
+ );
+ }
+ if (condition.hasAttachment !== undefined) {
+ const hasOne = exists(
+ sql`(SELECT 1 FROM ${messageAttachments} WHERE ${messageAttachments.messageId} = ${messages.id} AND ${messageAttachments.disposition} = 'attachment')`,
+ );
+ parts.push(condition.hasAttachment ? hasOne : not(hasOne));
+ }
+ if (condition.minSize !== undefined) parts.push(gte(sql`length(coalesce(${messages.textBody}, '')) + length(coalesce(${messages.htmlBody}, ''))`, condition.minSize));
+ if (condition.maxSize !== undefined) parts.push(lt(sql`length(coalesce(${messages.textBody}, '')) + length(coalesce(${messages.htmlBody}, ''))`, condition.maxSize));
+ return parts;
+}
+
+/** FilterOperator trees become nested AND/OR/NOT; a bare condition is an AND of its fields. */
+export function filterToSql(filter: Filter | null | undefined, accessible: Set<string>): SQL | undefined {
+ if (!filter) return undefined;
+ if ("operator" in filter) {
+ const children = (filter.conditions ?? []).map((child) => filterToSql(child, accessible)).filter((part): part is SQL => !!part);
+ if (children.length === 0) return undefined;
+ if (filter.operator === "AND") return and(...children);
+ if (filter.operator === "OR") return or(...children);
+ if (filter.operator === "NOT") return not(and(...children)!);
+ throw invalidArguments(`Unknown operator ${String(filter.operator)}`);
+ }
+ const parts = conditionToSql(filter, accessible);
+ return parts.length ? and(...parts) : undefined;
+}
+
+export function sortToSql(sort: Comparator[] | null | undefined): SQL[] {
+ const comparators = sort && sort.length ? sort : [{ property: "receivedAt", isAscending: false }];
+ return comparators.map((item) => {
+ const direction = item.isAscending ? asc : desc;
+ switch (item.property) {
+ case "receivedAt":
+ case "sentAt":
+ return direction(messages.createdAt);
+ case "subject":
+ return direction(messages.subject);
+ case "from":
+ return direction(messages.fromAddr);
+ case "to":
+ return direction(messages.toAddr);
+ case "size":
+ return direction(sql`length(coalesce(${messages.textBody}, '')) + length(coalesce(${messages.htmlBody}, ''))`);
+ case "hasKeyword":
+ case "allInThreadHaveKeyword":
+ case "someInThreadHaveKeyword": {
+ const keyword = (item as Comparator & { keyword?: string }).keyword ?? KEYWORD_SEEN;
+ return direction(keyword === KEYWORD_FLAGGED ? messages.starred : messages.read);
+ }
+ default:
+ throw invalidArguments(`Cannot sort by ${item.property}`);
+ }
+ });
+}
+
+export { gt };
diff --git a/src/lib/jmap/emails.ts b/src/lib/jmap/emails.ts
new file mode 100644
index 0000000..cbca613
--- /dev/null
+++ b/src/lib/jmap/emails.ts
@@ -0,0 +1,342 @@
+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 { getAuthorizedSenderAddress } from "@/lib/email/sender";
+import { joinEmailAddressList } from "@/lib/email/address";
+import { storeMessageAttachments } from "@/lib/email/attachments";
+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 { 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 type { AttachmentContent } from "@/lib/email/attachment-types";
+
+type MessageRow = typeof messages.$inferSelect;
+
+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) };
+}
+
+export async function loadMessages(ctx: JmapContext, ids: string[]): Promise<MessageRow[]> {
+ if (ids.length === 0) return [];
+ const { condition } = await scope(ctx);
+ return ctx.db.select().from(messages).where(and(condition, inArray(messages.id, ids)));
+}
+
+export const emailGet: JmapMethodHandler = async (ctx, args) => {
+ const ids = args.ids as string[] | null | undefined;
+ if (!ids) throw new JmapError("requestTooLarge", "Email/get needs an explicit list of ids");
+ if (ids.length > LIMITS.maxObjectsInGet) throw new JmapError("requestTooLarge");
+ const properties = args.properties as string[] | null | undefined;
+ const fetchBodies = !!(args.fetchTextBodyValues || args.fetchHTMLBodyValues || args.fetchAllBodyValues);
+ const maxBodyValueBytes = Number(args.maxBodyValueBytes ?? 0);
+
+ const rows = await loadMessages(ctx, ids);
+ const attachments = await loadAttachmentsByMessage(ctx, rows.map((row) => row.id));
+ const found = new Set<string>();
+ const list = rows.map((row) => {
+ found.add(row.id);
+ const full = buildEmailObject(row, attachments.get(row.id) ?? [], { fetchBodies, maxBodyValueBytes });
+ if (!properties) return full;
+ const picked: Record<string, unknown> = { id: row.id };
+ for (const key of properties) {
+ if (key.startsWith("header:")) picked[key] = resolveHeaderProperty(row, key);
+ else if (key in full) picked[key] = (full as Record<string, unknown>)[key];
+ }
+ return picked;
+ });
+ return { accountId: ctx.accountId, state: await getEmailState(ctx), list, notFound: ids.filter((id) => !found.has(id)) };
+};
+
+export const emailQuery: JmapMethodHandler = async (ctx, args) => {
+ const { ids: accessibleIds, condition } = await scope(ctx);
+ const filter = filterToSql(args.filter as Filter | null | undefined, new Set(accessibleIds));
+ const where = filter ? and(condition, filter) : condition;
+ const order = sortToSql(args.sort as Comparator[] | null | undefined);
+ const collapse = !!args.collapseThreads;
+ const limit = Math.min(Math.max(Number(args.limit ?? LIMITS.maxQueryLimit), 0), LIMITS.maxQueryLimit);
+ let position = Number(args.position ?? 0);
+
+ // Anchors are resolved by materialising the ordered id list up to a bound;
+ // mailboxes here are small enough that this stays cheap.
+ const threadKey = sql<string>`coalesce(${messages.threadId}, ${messages.id})`;
+ const allRows = await ctx.db
+ .select({ id: messages.id, thread: threadKey })
+ .from(messages)
+ .where(where)
+ .orderBy(...order)
+ .limit(10_000);
+ let ordered = allRows.map((row) => row.id);
+ if (collapse) {
+ const seen = new Set<string>();
+ ordered = allRows.filter((row) => (seen.has(row.thread) ? false : (seen.add(row.thread), true))).map((row) => row.id);
+ }
+ if (args.anchor) {
+ const index = ordered.indexOf(String(args.anchor));
+ if (index < 0) return { type: "anchorNotFound" };
+ position = index + Number(args.anchorOffset ?? 0);
+ }
+ if (position < 0) position = Math.max(ordered.length + position, 0);
+ const page = ordered.slice(position, position + limit);
+
+ return {
+ accountId: ctx.accountId,
+ queryState: await getEmailState(ctx),
+ canCalculateChanges: false,
+ position,
+ ids: page,
+ ...(args.calculateTotal ? { total: ordered.length } : {}),
+ };
+};
+
+export const emailChanges: JmapMethodHandler = async () => {
+ return { type: "cannotCalculateChanges", description: "Email change history is not kept; run Email/query again." };
+};
+
+export const emailQueryChanges: JmapMethodHandler = async () => {
+ return { type: "cannotCalculateChanges" };
+};
+
+/** Where a patched `mailboxIds` puts the message: exactly one JMAP mailbox is supported. */
+function targetFromMailboxIds(row: MessageRow, patch: Record<string, unknown>, accessible: Set<string>): { status?: string; folderId?: string | null } | { error: Record<string, unknown> } | null {
+ let ids: string[] | null = null;
+ if (patch.mailboxIds && typeof patch.mailboxIds === "object") {
+ ids = Object.entries(patch.mailboxIds as Record<string, boolean>).filter(([, on]) => on).map(([id]) => id);
+ } else {
+ const current = new Set(Object.keys(buildEmailObject(row, [], { fetchBodies: false, maxBodyValueBytes: 0 }).mailboxIds));
+ let touched = false;
+ for (const [key, value] of Object.entries(patch)) {
+ if (!key.startsWith("mailboxIds/")) continue;
+ touched = true;
+ const id = key.slice("mailboxIds/".length);
+ if (value) current.add(id);
+ else current.delete(id);
+ }
+ if (touched) ids = Array.from(current);
+ }
+ if (!ids) return null;
+ if (ids.length !== 1) return { error: { type: "invalidProperties", properties: ["mailboxIds"], description: "A message belongs to exactly one mailbox" } };
+ const ref: MailboxRef | null = decodeMailboxRef(ids[0]);
+ if (!ref || !accessible.has(ref.mailboxId)) return { error: { type: "invalidProperties", properties: ["mailboxIds"], description: "Unknown mailbox" } };
+ if (ref.mailboxId !== row.mailboxId) return { error: { type: "invalidProperties", properties: ["mailboxIds"], description: "Messages cannot move between accounts' mailboxes" } };
+ if (ref.kind === "account") return { error: { type: "invalidProperties", properties: ["mailboxIds"], description: "Choose a folder or system mailbox" } };
+ if (ref.kind === "folder") return { status: row.direction === "outbound" && row.status !== "draft" ? "sent" : "received", folderId: ref.folderId };
+ if (ref.role === "sent" && row.direction === "inbound") return { error: { type: "invalidProperties", properties: ["mailboxIds"], description: "Received mail cannot be moved to Sent" } };
+ return { status: roleToStatus(ref.role), folderId: null };
+}
+
+function keywordsFromPatch(patch: Record<string, unknown>): { read?: boolean; starred?: boolean } {
+ const result: { read?: boolean; starred?: boolean } = {};
+ const apply = (keyword: string, value: unknown) => {
+ if (keyword === KEYWORD_SEEN) result.read = !!value;
+ if (keyword === KEYWORD_FLAGGED) result.starred = !!value;
+ };
+ if (patch.keywords && typeof patch.keywords === "object") {
+ const map = patch.keywords as Record<string, boolean>;
+ result.read = !!map[KEYWORD_SEEN];
+ result.starred = !!map[KEYWORD_FLAGGED];
+ }
+ for (const [key, value] of Object.entries(patch)) {
+ if (key.startsWith("keywords/")) apply(key.slice("keywords/".length), value);
+ }
+ return result;
+}
+
+/** 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 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 });
+ } catch (error) {
+ return { error: { type: "forbidden", description: error instanceof Error ? error.message : "Cannot send from that address" } };
+ }
+ const addressList = (list: unknown) =>
+ Array.isArray(list) ? joinEmailAddressList((list as EmailAddressObject[]).map((item) => (item.name ? `"${item.name.replace(/"/g, '\\"')}" <${item.email}>` : item.email))) : "";
+ const bodyValues = (value.bodyValues ?? {}) as Record<string, { value: string }>;
+ const partText = (parts: unknown) => (Array.isArray(parts) && parts[0]?.partId ? bodyValues[parts[0].partId]?.value ?? "" : "");
+ const text = partText(value.textBody);
+ const 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,
+ 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[] = [];
+ for (const part of (value.attachments as Array<{ blobId?: string; name?: string; type?: string; disposition?: string; cid?: string }> | undefined) ?? []) {
+ const blob = part.blobId ? decodeBlobId(part.blobId) : null;
+ if (!blob || blob.kind !== "up") continue;
+ const upload = await readUpload(ctx, blob.id);
+ if (!upload) continue;
+ uploads.push({ filename: part.name ?? upload.name ?? "attachment", type: part.type ?? upload.type, content: upload.content, disposition: part.disposition === "inline" ? ("inline" as const) : ("attachment" as const), contentId: part.cid ?? null });
+ }
+ if (uploads.length) {
+ try {
+ await storeMessageAttachments(ctx.env, id, uploads);
+ } catch (error) {
+ await ctx.db.delete(messages).where(eq(messages.id, id));
+ return { error: { type: "tooLarge", description: error instanceof Error ? error.message : "Attachments rejected" } };
+ }
+ }
+ return { id };
+}
+
+export const emailSet: JmapMethodHandler = async (ctx, args) => {
+ const oldState = await getEmailState(ctx);
+ if (args.ifInState && args.ifInState !== oldState) return { type: "stateMismatch" };
+ const accessible = await listAccessibleMailboxIdSet(ctx);
+ 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> = {};
+ const updated: Record<string, null> = {};
+ const notUpdated: Record<string, unknown> = {};
+ const destroyed: string[] = [];
+ const notDestroyed: Record<string, unknown> = {};
+
+ for (const [creationId, value] of Object.entries((args.create ?? {}) as Record<string, Record<string, unknown>>)) {
+ const result = await createDraft(ctx, value, writable);
+ if ("error" in result) {
+ notCreated[creationId] = result.error;
+ continue;
+ }
+ ctx.createdIds[creationId] = result.id;
+ const [row] = await loadMessages(ctx, [result.id]);
+ created[creationId] = row ? buildEmailObject(row, [], { fetchBodies: false, maxBodyValueBytes: 0 }) : { id: result.id };
+ }
+
+ const updates = Object.entries((args.update ?? {}) as Record<string, Record<string, unknown>>);
+ const rows = await loadMessages(ctx, updates.map(([id]) => id));
+ const byId = new Map(rows.map((row) => [row.id, row]));
+ for (const [id, patch] of updates) {
+ const row = byId.get(id);
+ if (!row || !row.mailboxId) {
+ notUpdated[id] = { type: "notFound" };
+ continue;
+ }
+ if (!writable.has(row.mailboxId)) {
+ notUpdated[id] = { type: "forbidden" };
+ continue;
+ }
+ const move = targetFromMailboxIds(row, patch, accessible);
+ if (move && "error" in move) {
+ notUpdated[id] = move.error;
+ continue;
+ }
+ const flags = keywordsFromPatch(patch);
+ const set: Partial<MessageRow> = {};
+ if (flags.read !== undefined) set.read = flags.read;
+ if (flags.starred !== undefined) set.starred = flags.starred;
+ if (move) {
+ if (move.status !== undefined) set.status = move.status;
+ if (move.folderId !== undefined) set.folderId = move.folderId;
+ }
+ if (Object.keys(set).length) await ctx.db.update(messages).set(set).where(eq(messages.id, id));
+ updated[id] = null;
+ }
+
+ // JMAP destroy is permanent; Mailflare keeps a trash, so destroy moves there
+ // and a second destroy from Trash deletes the row.
+ const destroyIds = (args.destroy ?? []) as string[];
+ const destroyRows = await loadMessages(ctx, destroyIds);
+ const destroyById = new Map(destroyRows.map((row) => [row.id, row]));
+ for (const id of destroyIds) {
+ const row = destroyById.get(id);
+ if (!row || !row.mailboxId) {
+ notDestroyed[id] = { type: "notFound" };
+ continue;
+ }
+ if (!writable.has(row.mailboxId)) {
+ notDestroyed[id] = { type: "forbidden" };
+ continue;
+ }
+ if (row.status === "trash" || row.status === "draft") await ctx.db.delete(messages).where(eq(messages.id, id));
+ else await ctx.db.update(messages).set({ status: "trash", folderId: null }).where(eq(messages.id, id));
+ destroyed.push(id);
+ }
+
+ return { accountId: ctx.accountId, oldState, newState: await getEmailState(ctx), created, updated, destroyed, notCreated, notUpdated, notDestroyed };
+};
+
+export const emailUnsupported = (method: string): JmapMethodHandler => async () => ({ type: "unknownMethod", description: `${method} is not supported` });
+
+/** Thread/get: every message sharing a thread key, oldest first. */
+export const threadGet: JmapMethodHandler = async (ctx, args) => {
+ const ids = args.ids as string[] | null | undefined;
+ if (!ids) throw new JmapError("requestTooLarge", "Thread/get needs an explicit list of ids");
+ const { condition } = await scope(ctx);
+ const threadKey = sql<string>`coalesce(${messages.threadId}, ${messages.id})`;
+ const rows = await ctx.db
+ .select({ id: messages.id, thread: threadKey })
+ .from(messages)
+ .where(and(condition, inArray(threadKey, ids)))
+ .orderBy(asc(messages.createdAt));
+ const grouped = new Map<string, string[]>();
+ for (const row of rows) grouped.set(row.thread, [...(grouped.get(row.thread) ?? []), row.id]);
+ return {
+ accountId: ctx.accountId,
+ state: await getEmailState(ctx),
+ list: Array.from(grouped, ([id, emailIds]) => ({ id, emailIds })),
+ notFound: ids.filter((id) => !grouped.has(id)),
+ };
+};
+
+export const threadChanges: JmapMethodHandler = async () => ({ type: "cannotCalculateChanges" });
+
+/** SearchSnippet/get: the subject and a body excerpt around the first match, with <mark> tags. */
+export const searchSnippetGet: JmapMethodHandler = async (ctx, args) => {
+ const ids = (args.emailIds as string[]) ?? [];
+ const filter = (args.filter ?? {}) as { text?: string; subject?: string; body?: string };
+ const term = (filter.text ?? filter.body ?? filter.subject ?? "").trim();
+ const rows = await loadMessages(ctx, ids);
+ const found = new Set<string>();
+ const escape = (value: string) => value.replace(/[&<>]/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[char]!);
+ const highlight = (value: string | null) => {
+ if (!value) return null;
+ if (!term) return escape(value);
+ const re = new RegExp(term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "ig");
+ return escape(value).replace(re, (match) => `<mark>${match}</mark>`);
+ };
+ const list = rows.map((row) => {
+ found.add(row.id);
+ const body = row.textBody ?? row.snippet ?? "";
+ let excerpt: string | null = null;
+ if (term) {
+ const index = body.toLowerCase().indexOf(term.toLowerCase());
+ if (index >= 0) excerpt = highlight(body.slice(Math.max(index - 80, 0), index + 160));
+ }
+ return { emailId: row.id, subject: highlight(row.subject), preview: excerpt };
+ });
+ return { accountId: ctx.accountId, list, notFound: ids.filter((id) => !found.has(id)) };
+};
+
+export { count, desc, mailboxRefCondition, invalidArguments };
diff --git a/src/lib/jmap/errors.ts b/src/lib/jmap/errors.ts
new file mode 100644
index 0000000..3ef5a2f
--- /dev/null
+++ b/src/lib/jmap/errors.ts
@@ -0,0 +1,36 @@
+import type { JmapMethodError } from "./types";
+
+export class JmapError extends Error {
+ constructor(
+ public readonly type: string,
+ description?: string,
+ public readonly extra: Record<string, unknown> = {},
+ ) {
+ super(description ?? type);
+ }
+
+ toMethodError(): JmapMethodError {
+ return { type: this.type, ...(this.message !== this.type ? { description: this.message } : {}), ...this.extra };
+ }
+}
+
+export function invalidArguments(description: string): JmapError {
+ return new JmapError("invalidArguments", 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 }), {
+ status,
+ headers: { "Content-Type": "application/problem+json", ...corsHeaders() },
+ });
+}
+
+export function corsHeaders(): Record<string, string> {
+ return {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
+ "Access-Control-Allow-Headers": "Authorization, Content-Type",
+ "Access-Control-Max-Age": "86400",
+ };
+}
diff --git a/src/lib/jmap/handler.ts b/src/lib/jmap/handler.ts
new file mode 100644
index 0000000..fb8bea7
--- /dev/null
+++ b/src/lib/jmap/handler.ts
@@ -0,0 +1,136 @@
+import { getDb } from "@/db";
+import { authenticateApiRequest, hasScope } from "@/lib/api/key-auth";
+import { LIMITS } from "./constants";
+import { corsHeaders, JmapError, problemResponse } from "./errors";
+import { readBlob, storeUpload } from "./blobs";
+import { processRequest, sessionState, validateRequest } from "./processor";
+import { buildSession } from "./session";
+import { getEmailState, getMailboxState } from "./state";
+import type { JmapContext } from "./types";
+
+const JSON_HEADERS = { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", ...corsHeaders() };
+
+/**
+ * Entry point for every /jmap/* path and /.well-known/jmap. Returns null for
+ * paths it does not own so the caller can fall through.
+ */
+export async function handleJmapRequest(request: Request, env: CloudflareEnv): Promise<Response | null> {
+ const url = new URL(request.url);
+ const path = url.pathname;
+
+ if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: corsHeaders() });
+ if (path === "/.well-known/jmap") {
+ return Response.redirect(`${url.origin}/jmap/session`, 301);
+ }
+ if (!path.startsWith("/jmap/")) return null;
+
+ const auth = await authenticateApiRequest(env, request);
+ if (!auth) {
+ return new Response(JSON.stringify({ error: "Unauthorized" }), {
+ status: 401,
+ headers: { ...JSON_HEADERS, "WWW-Authenticate": 'Basic realm="Mailflare JMAP", Bearer' },
+ });
+ }
+ if (!hasScope(auth.scopes, "jmap")) {
+ return new Response(JSON.stringify({ error: "This API key does not have the jmap scope" }), { status: 403, headers: JSON_HEADERS });
+ }
+ const ctx: JmapContext = { env, db: getDb(env), auth, accountId: auth.userId, origin: url.origin, createdIds: {} };
+
+ if (path === "/jmap/session" && request.method === "GET") {
+ return new Response(JSON.stringify(buildSession(ctx, await sessionState(ctx))), { headers: JSON_HEADERS });
+ }
+
+ if (path === "/jmap/api" && request.method === "POST") {
+ const length = Number(request.headers.get("content-length") ?? 0);
+ if (length > LIMITS.maxSizeRequest) return problemResponse("limit", 400, "Request too large", { limit: "maxSizeRequest" });
+ let body: unknown;
+ try {
+ body = await request.json();
+ } catch {
+ return problemResponse("notJSON", 400, "Body is not valid JSON");
+ }
+ try {
+ const response = await processRequest(ctx, validateRequest(body));
+ return new Response(JSON.stringify(response), { headers: JSON_HEADERS });
+ } catch (error) {
+ if (error instanceof JmapError) return problemResponse(error.type, 400, error.message, error.extra);
+ throw error;
+ }
+ }
+
+ const download = path.match(/^\/jmap\/download\/([^/]+)\/([^/]+)\/(.*)$/);
+ if (download && request.method === "GET") {
+ const [, accountId, blobId, rawName] = download;
+ if (decodeURIComponent(accountId) !== ctx.accountId) return new Response("Not found", { status: 404, headers: corsHeaders() });
+ const blob = await readBlob(ctx, decodeURIComponent(blobId));
+ if (!blob) return new Response("Not found", { status: 404, headers: corsHeaders() });
+ const name = decodeURIComponent(rawName) || blob.name || "blob";
+ const type = url.searchParams.get("type") || blob.type;
+ return new Response(blob.body, {
+ headers: {
+ "Content-Type": type,
+ "Content-Length": String(blob.size),
+ "Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
+ "Cache-Control": "private, max-age=3600",
+ "Content-Security-Policy": "default-src 'none'; sandbox",
+ ...corsHeaders(),
+ },
+ });
+ }
+
+ const upload = path.match(/^\/jmap\/upload\/([^/]+)$/);
+ if (upload && request.method === "POST") {
+ if (decodeURIComponent(upload[1]) !== ctx.accountId) return problemResponse("accountNotFound", 404, "Unknown account");
+ const type = request.headers.get("content-type") || "application/octet-stream";
+ const disposition = request.headers.get("content-disposition") ?? "";
+ const name = disposition.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i)?.[1] ?? null;
+ const stored = await storeUpload(ctx, await request.arrayBuffer(), type, name ? decodeURIComponent(name) : null);
+ if (!stored) return problemResponse("limit", 413, "Upload too large", { limit: "maxSizeUpload" });
+ return new Response(JSON.stringify(stored), { status: 201, headers: JSON_HEADERS });
+ }
+
+ if (path === "/jmap/eventsource" && request.method === "GET") {
+ return eventSource(ctx, url);
+ }
+
+ return new Response(JSON.stringify({ error: "Not found" }), { status: 404, headers: JSON_HEADERS });
+}
+
+/**
+ * Server-sent events. Mailflare has no per-account change log, so the stream
+ * sends the current states on connect and again whenever they move, polling
+ * every `ping` seconds (default 30, minimum 10) until the client leaves.
+ */
+function eventSource(ctx: JmapContext, url: URL): Response {
+ const ping = Math.max(Number(url.searchParams.get("ping") || 30), 10);
+ const closeAfter = url.searchParams.get("closeafter") === "state";
+ const encoder = new TextEncoder();
+ let last = "";
+ let timer: ReturnType<typeof setInterval> | null = null;
+
+ const stream = new ReadableStream<Uint8Array>({
+ async start(controller) {
+ const emit = async () => {
+ const [mailbox, email] = await Promise.all([getMailboxState(ctx), getEmailState(ctx)]);
+ const state = `${mailbox}|${email}`;
+ if (state === last) {
+ controller.enqueue(encoder.encode(`event: ping\ndata: {"interval": ${ping}}\n\n`));
+ return;
+ }
+ last = state;
+ const changed = { [ctx.accountId]: { Mailbox: mailbox, Email: email, Thread: email } };
+ controller.enqueue(encoder.encode(`event: state\ndata: ${JSON.stringify({ "@type": "StateChange", changed })}\n\n`));
+ if (closeAfter) {
+ controller.close();
+ if (timer) clearInterval(timer);
+ }
+ };
+ await emit();
+ if (!closeAfter) timer = setInterval(() => void emit().catch(() => timer && clearInterval(timer)), ping * 1000);
+ },
+ cancel() {
+ if (timer) clearInterval(timer);
+ },
+ });
+ return new Response(stream, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-store", Connection: "keep-alive", ...corsHeaders() } });
+}
diff --git a/src/lib/jmap/identities.ts b/src/lib/jmap/identities.ts
new file mode 100644
index 0000000..48ac97b
--- /dev/null
+++ b/src/lib/jmap/identities.ts
@@ -0,0 +1,138 @@
+import { and, eq } from "drizzle-orm";
+import { messages } from "@/db/schema";
+import { sendEmail } from "@/lib/email/send";
+import { loadMessageAttachmentContents } from "@/lib/email/attachments";
+import { decodeIdentityId, identityId } from "./ids";
+import { listJmapMailboxes, listSendableAddresses } from "./access";
+import { getEmailState } from "./state";
+import { JmapError } from "./errors";
+import type { JmapContext, JmapMethodHandler } from "./types";
+
+/** One Identity per address the account may send from. */
+export async function buildIdentities(ctx: JmapContext) {
+ const list: Array<Record<string, unknown>> = [];
+ for (const mailbox of await listJmapMailboxes(ctx)) {
+ if (mailbox.permission === "read_only") continue;
+ for (const address of await listSendableAddresses(ctx, mailbox)) {
+ list.push({
+ id: identityId(mailbox.id, address),
+ name: mailbox.displayName ?? "",
+ email: address,
+ replyTo: null,
+ bcc: null,
+ textSignature: "",
+ htmlSignature: "",
+ mayDelete: false,
+ });
+ }
+ }
+ return list;
+}
+
+export const identityGet: JmapMethodHandler = async (ctx, args) => {
+ const all = await buildIdentities(ctx);
+ const ids = args.ids as string[] | null | undefined;
+ const list = ids ? all.filter((item) => ids.includes(item.id as string)) : all;
+ const found = new Set(list.map((item) => item.id as string));
+ return { accountId: ctx.accountId, state: "identities", list, notFound: ids ? ids.filter((id) => !found.has(id)) : [] };
+};
+
+export const identityChanges: JmapMethodHandler = async () => ({ type: "cannotCalculateChanges" });
+export const identitySet: JmapMethodHandler = async (ctx, args) => ({
+ accountId: ctx.accountId,
+ oldState: "identities",
+ newState: "identities",
+ created: {},
+ updated: {},
+ destroyed: [],
+ notCreated: Object.fromEntries(Object.keys((args.create ?? {}) as object).map((id) => [id, { type: "forbidden" }])),
+ notUpdated: Object.fromEntries(Object.keys((args.update ?? {}) as object).map((id) => [id, { type: "forbidden" }])),
+ notDestroyed: Object.fromEntries(((args.destroy ?? []) as string[]).map((id) => [id, { type: "forbidden" }])),
+});
+
+/**
+ * EmailSubmission/set: send a draft. Mailflare's send writes a fresh Sent row,
+ * so the draft is removed afterwards and the submission id is the sent
+ * message's id; onSuccessDestroyEmail / onSuccessUpdateEmail are honoured
+ * by reporting the draft as destroyed.
+ */
+export const emailSubmissionSet: JmapMethodHandler = async (ctx, args) => {
+ const oldState = await getEmailState(ctx);
+ const created: Record<string, unknown> = {};
+ const notCreated: Record<string, unknown> = {};
+ const destroyedEmails: string[] = [];
+
+ for (const [creationId, value] of Object.entries((args.create ?? {}) as Record<string, Record<string, unknown>>)) {
+ const emailId = ctx.createdIds[String(value.emailId).replace(/^#/, "")] ?? String(value.emailId ?? "");
+ const identity = typeof value.identityId === "string" ? decodeIdentityId(value.identityId) : null;
+ if (!identity) {
+ notCreated[creationId] = { type: "invalidProperties", properties: ["identityId"] };
+ continue;
+ }
+ const [draft] = await ctx.db.select().from(messages).where(and(eq(messages.id, emailId), eq(messages.status, "draft"))).limit(1);
+ if (!draft || draft.userId !== ctx.auth.userId) {
+ notCreated[creationId] = { type: "invalidProperties", properties: ["emailId"], description: "Not a draft of this account" };
+ continue;
+ }
+ try {
+ const attachments = await loadMessageAttachmentContents(ctx.env, draft.id);
+ const result = await sendEmail(ctx.env, {
+ userId: ctx.auth.userId,
+ from: identity.address,
+ to: draft.toAddr,
+ cc: draft.ccAddr ?? undefined,
+ bcc: draft.bccAddr ?? undefined,
+ subject: draft.subject ?? "(no subject)",
+ text: draft.textBody ?? undefined,
+ html: draft.htmlBody ?? undefined,
+ inReplyTo: draft.inReplyTo,
+ references: draft.references,
+ threadId: draft.threadId,
+ mailboxId: identity.mailboxId,
+ attachments,
+ });
+ await ctx.db.delete(messages).where(eq(messages.id, draft.id));
+ destroyedEmails.push(draft.id);
+ ctx.createdIds[creationId] = result.messageId;
+ created[creationId] = {
+ id: result.messageId,
+ identityId: value.identityId,
+ emailId: result.messageId,
+ threadId: draft.threadId ?? result.messageId,
+ envelope: null,
+ sendAt: new Date().toISOString(),
+ undoStatus: "final",
+ deliveryStatus: null,
+ dsnBlobIds: [],
+ mdnBlobIds: [],
+ };
+ } catch (error) {
+ notCreated[creationId] = { type: "forbidden", description: error instanceof Error ? error.message : "Send failed" };
+ }
+ }
+
+ return {
+ accountId: ctx.accountId,
+ oldState,
+ newState: await getEmailState(ctx),
+ created,
+ updated: {},
+ destroyed: [],
+ notCreated,
+ notUpdated: Object.fromEntries(Object.keys((args.update ?? {}) as object).map((id) => [id, { type: "forbidden" }])),
+ notDestroyed: Object.fromEntries(((args.destroy ?? []) as string[]).map((id) => [id, { type: "forbidden" }])),
+ // Surfaced so the processor can append the implicit Email/set response.
+ __destroyedEmails: destroyedEmails,
+ };
+};
+
+export const emailSubmissionGet: JmapMethodHandler = async (ctx, args) => ({
+ accountId: ctx.accountId,
+ state: await getEmailState(ctx),
+ list: [],
+ notFound: ((args.ids ?? []) as string[]) ?? [],
+});
+export const emailSubmissionQuery: JmapMethodHandler = async (ctx) => ({ accountId: ctx.accountId, queryState: await getEmailState(ctx), canCalculateChanges: false, position: 0, ids: [], total: 0 });
+export const emailSubmissionChanges: JmapMethodHandler = async () => ({ type: "cannotCalculateChanges" });
+
+export { JmapError };
diff --git a/src/lib/jmap/ids.ts b/src/lib/jmap/ids.ts
new file mode 100644
index 0000000..533fed9
--- /dev/null
+++ b/src/lib/jmap/ids.ts
@@ -0,0 +1,91 @@
+import type { MailboxRef, SystemRole } from "./types";
+
+/**
+ * JMAP Mailbox ids encode Mailflare's model: a top-level Mailbox per Mailflare
+ * mailbox (all its mail), system children keyed by status, and one child per
+ * user folder. Ids are stable strings so clients can cache them.
+ */
+const SEP = "~";
+export const SYSTEM_ROLES: SystemRole[] = ["inbox", "sent", "drafts", "archive", "junk", "trash"];
+
+export function encodeMailboxRef(ref: MailboxRef): string {
+ if (ref.kind === "account") return ref.mailboxId;
+ if (ref.kind === "role") return `${ref.mailboxId}${SEP}${ref.role}`;
+ return `${ref.mailboxId}${SEP}f${SEP}${ref.folderId}`;
+}
+
+export function decodeMailboxRef(id: string): MailboxRef | null {
+ const parts = id.split(SEP);
+ if (parts.length === 1 && parts[0]) return { kind: "account", mailboxId: parts[0] };
+ if (parts.length === 2 && (SYSTEM_ROLES as string[]).includes(parts[1])) {
+ return { kind: "role", mailboxId: parts[0], role: parts[1] as SystemRole };
+ }
+ if (parts.length === 3 && parts[1] === "f" && parts[2]) return { kind: "folder", mailboxId: parts[0], folderId: parts[2] };
+ return null;
+}
+
+/** Blob ids name either a stored attachment, a message's raw MIME, or a client upload. */
+export function attachmentBlobId(attachmentId: string): string {
+ return `att${SEP}${attachmentId}`;
+}
+export function messageBlobId(messageId: string): string {
+ return `msg${SEP}${messageId}`;
+}
+export function uploadBlobId(uploadId: string): string {
+ return `up${SEP}${uploadId}`;
+}
+export function decodeBlobId(blobId: string): { kind: "att" | "msg" | "up"; id: string } | null {
+ const index = blobId.indexOf(SEP);
+ if (index < 0) return null;
+ const kind = blobId.slice(0, index);
+ const id = blobId.slice(index + 1);
+ if (!id || (kind !== "att" && kind !== "msg" && kind !== "up")) return null;
+ return { kind, id };
+}
+
+export function identityId(mailboxId: string, address: string): string {
+ return `${mailboxId}${SEP}${address.toLowerCase()}`;
+}
+export function decodeIdentityId(id: string): { mailboxId: string; address: string } | null {
+ const index = id.indexOf(SEP);
+ if (index < 0) return null;
+ return { mailboxId: id.slice(0, index), address: id.slice(index + 1) };
+}
+
+/** Status/folder predicate for each system role, as a plain description the query layer turns into SQL. */
+export function roleToStatus(role: SystemRole): string {
+ switch (role) {
+ case "inbox":
+ return "received";
+ case "sent":
+ return "sent";
+ case "drafts":
+ return "draft";
+ case "archive":
+ return "archived";
+ case "junk":
+ return "spam";
+ case "trash":
+ return "trash";
+ }
+}
+export function statusToRole(status: string): SystemRole | null {
+ switch (status) {
+ case "received":
+ return "inbox";
+ case "sent":
+ case "queued":
+ case "failed":
+ return "sent";
+ case "draft":
+ return "drafts";
+ case "archived":
+ return "archive";
+ case "spam":
+ return "junk";
+ case "trash":
+ return "trash";
+ default:
+ return null;
+ }
+}
diff --git a/src/lib/jmap/mailboxes.ts b/src/lib/jmap/mailboxes.ts
new file mode 100644
index 0000000..55b6d8d
--- /dev/null
+++ b/src/lib/jmap/mailboxes.ts
@@ -0,0 +1,292 @@
+import { and, count, eq, inArray, isNull, sql } from "drizzle-orm";
+import { folders, messages } from "@/db/schema";
+import { newId } from "@/lib/ids";
+import { JmapError } from "./errors";
+import { decodeMailboxRef, encodeMailboxRef, roleToStatus, SYSTEM_ROLES } from "./ids";
+import { getMailboxState } from "./state";
+import type { AccessibleMailbox, JmapContext, JmapMethodHandler, SystemRole } from "./types";
+import { listFoldersByMailbox, listJmapMailboxes } from "./access";
+
+const ROLE_NAMES: Record<SystemRole, string> = {
+ inbox: "Inbox",
+ sent: "Sent",
+ drafts: "Drafts",
+ archive: "Archive",
+ junk: "Spam",
+ trash: "Trash",
+};
+const ROLE_ORDER: Record<SystemRole, number> = { inbox: 1, drafts: 2, sent: 3, archive: 4, junk: 5, trash: 6 };
+
+type Counts = { total: number; unread: number };
+
+/**
+ * Per-mailbox tallies in one pass: rows grouped by (mailbox, status, folder)
+ * are folded into the JMAP Mailbox each combination belongs to.
+ */
+async function loadCounts(ctx: JmapContext, mailboxIds: string[]): Promise<Map<string, Counts>> {
+ const result = new Map<string, Counts>();
+ if (mailboxIds.length === 0) return result;
+ const rows = await ctx.db
+ .select({
+ mailboxId: messages.mailboxId,
+ status: messages.status,
+ folderId: messages.folderId,
+ total: count(),
+ unread: sql<number>`sum(case when ${messages.read} = 0 and ${messages.direction} = 'inbound' then 1 else 0 end)`,
+ })
+ .from(messages)
+ .where(inArray(messages.mailboxId, mailboxIds))
+ .groupBy(messages.mailboxId, messages.status, messages.folderId);
+
+ const add = (key: string, row: { total: number; unread: number }) => {
+ const current = result.get(key) ?? { total: 0, unread: 0 };
+ result.set(key, { total: current.total + row.total, unread: current.unread + Number(row.unread ?? 0) });
+ };
+ for (const row of rows) {
+ if (!row.mailboxId) continue;
+ add(encodeMailboxRef({ kind: "account", mailboxId: row.mailboxId }), row);
+ if (row.folderId) {
+ add(encodeMailboxRef({ kind: "folder", mailboxId: row.mailboxId, folderId: row.folderId }), row);
+ continue;
+ }
+ const role = statusRole(row.status);
+ if (role) add(encodeMailboxRef({ kind: "role", mailboxId: row.mailboxId, role }), row);
+ }
+ return result;
+}
+
+function statusRole(status: string): SystemRole | null {
+ for (const role of SYSTEM_ROLES) if (roleToStatus(role) === status) return role;
+ if (status === "queued" || status === "failed") return "sent";
+ return null;
+}
+
+function rights(mailbox: AccessibleMailbox, system: boolean) {
+ const canWrite = mailbox.permission !== "read_only";
+ const canSend = mailbox.permission === "send_as" || mailbox.permission === "send_on_behalf" || mailbox.permission === "full_access";
+ return {
+ mayReadItems: true,
+ mayAddItems: canWrite,
+ mayRemoveItems: canWrite,
+ maySetSeen: canWrite,
+ maySetKeywords: canWrite,
+ mayCreateChild: mailbox.permission === "full_access",
+ mayRename: !system && mailbox.permission === "full_access",
+ mayDelete: !system && mailbox.permission === "full_access",
+ maySubmit: canSend,
+ };
+}
+
+/** Every Mailbox object visible to the account. */
+export async function buildAllMailboxes(ctx: JmapContext) {
+ const accessible = await listJmapMailboxes(ctx);
+ const ids = accessible.map((row) => row.id);
+ const [foldersByMailbox, counts] = await Promise.all([listFoldersByMailbox(ctx, ids), loadCounts(ctx, ids)]);
+ const list: Array<Record<string, unknown>> = [];
+ let sortBase = 0;
+
+ for (const mailbox of accessible) {
+ const address = `${mailbox.localPart}@${mailbox.hostname}`;
+ const accountId = encodeMailboxRef({ kind: "account", mailboxId: mailbox.id });
+ const accountCounts = counts.get(accountId) ?? { total: 0, unread: 0 };
+ list.push({
+ id: accountId,
+ name: mailbox.displayName ? `${mailbox.displayName} <${address}>` : address,
+ parentId: null,
+ role: null,
+ sortOrder: sortBase,
+ totalEmails: accountCounts.total,
+ unreadEmails: accountCounts.unread,
+ totalThreads: accountCounts.total,
+ unreadThreads: accountCounts.unread,
+ myRights: rights(mailbox, true),
+ isSubscribed: true,
+ });
+ for (const role of SYSTEM_ROLES) {
+ const id = encodeMailboxRef({ kind: "role", mailboxId: mailbox.id, role });
+ const c = counts.get(id) ?? { total: 0, unread: 0 };
+ list.push({
+ id,
+ name: ROLE_NAMES[role],
+ parentId: accountId,
+ role,
+ sortOrder: sortBase + ROLE_ORDER[role],
+ totalEmails: c.total,
+ unreadEmails: role === "inbox" ? c.unread : 0,
+ totalThreads: c.total,
+ unreadThreads: role === "inbox" ? c.unread : 0,
+ myRights: rights(mailbox, true),
+ isSubscribed: true,
+ });
+ }
+ for (const folder of foldersByMailbox.get(mailbox.id) ?? []) {
+ const id = encodeMailboxRef({ kind: "folder", mailboxId: mailbox.id, folderId: folder.id });
+ const c = counts.get(id) ?? { total: 0, unread: 0 };
+ list.push({
+ id,
+ name: folder.name,
+ parentId: accountId,
+ role: null,
+ sortOrder: sortBase + 10,
+ totalEmails: c.total,
+ unreadEmails: c.unread,
+ totalThreads: c.total,
+ unreadThreads: c.unread,
+ myRights: rights(mailbox, false),
+ isSubscribed: true,
+ });
+ }
+ sortBase += 100;
+ }
+ return list;
+}
+
+export const mailboxGet: JmapMethodHandler = async (ctx, args) => {
+ const all = await buildAllMailboxes(ctx);
+ const ids = args.ids as string[] | null | undefined;
+ const properties = args.properties as string[] | null | undefined;
+ const wanted = ids ? all.filter((item) => ids.includes(item.id as string)) : all;
+ const found = new Set(wanted.map((item) => item.id as string));
+ return {
+ accountId: ctx.accountId,
+ state: await getMailboxState(ctx),
+ list: wanted.map((item) => pick(item, properties)),
+ notFound: ids ? ids.filter((id) => !found.has(id)) : [],
+ };
+};
+
+export const mailboxQuery: JmapMethodHandler = async (ctx, args) => {
+ const all = await buildAllMailboxes(ctx);
+ const filter = (args.filter ?? {}) as { parentId?: string | null; name?: string; role?: string | null; hasAnyRole?: boolean };
+ let rows = all;
+ if (filter.parentId !== undefined) rows = rows.filter((item) => item.parentId === filter.parentId);
+ if (filter.name) rows = rows.filter((item) => String(item.name).toLowerCase().includes(filter.name!.toLowerCase()));
+ if (filter.role !== undefined) rows = rows.filter((item) => item.role === filter.role);
+ if (filter.hasAnyRole !== undefined) rows = rows.filter((item) => (item.role !== null) === filter.hasAnyRole);
+ rows = [...rows].sort((a, b) => Number(a.sortOrder) - Number(b.sortOrder));
+ const position = Math.max(Number(args.position ?? 0), 0);
+ const limit = args.limit == null ? rows.length : Math.max(Number(args.limit), 0);
+ return {
+ accountId: ctx.accountId,
+ queryState: await getMailboxState(ctx),
+ canCalculateChanges: false,
+ position,
+ ids: rows.slice(position, position + limit).map((item) => item.id),
+ total: rows.length,
+ };
+};
+
+export const mailboxChanges: JmapMethodHandler = async () => {
+ return { type: "cannotCalculateChanges", description: "Mailbox change history is not kept; run Mailbox/get again." };
+};
+
+/** Folders can be created, renamed and removed; system mailboxes cannot. */
+export const mailboxSet: JmapMethodHandler = async (ctx, args) => {
+ const oldState = await getMailboxState(ctx);
+ if (args.ifInState && args.ifInState !== oldState) return { type: "stateMismatch" };
+ const accessible = await listJmapMailboxes(ctx);
+ const created: Record<string, unknown> = {};
+ const notCreated: Record<string, unknown> = {};
+ const updated: Record<string, null> = {};
+ const notUpdated: Record<string, unknown> = {};
+ const destroyed: string[] = [];
+ const notDestroyed: Record<string, unknown> = {};
+
+ for (const [creationId, value] of Object.entries((args.create ?? {}) as Record<string, Record<string, unknown>>)) {
+ const parent = typeof value.parentId === "string" ? decodeMailboxRef(value.parentId) : null;
+ const name = typeof value.name === "string" ? value.name.trim() : "";
+ const mailbox = parent && accessible.find((row) => row.id === parent.mailboxId);
+ if (!parent || parent.kind !== "account" || !mailbox || mailbox.permission !== "full_access") {
+ notCreated[creationId] = { type: "invalidProperties", properties: ["parentId"], description: "Folders live directly under a mailbox" };
+ continue;
+ }
+ if (!name || name.length > 80) {
+ notCreated[creationId] = { type: "invalidProperties", properties: ["name"] };
+ continue;
+ }
+ const id = newId("fld");
+ try {
+ await ctx.db.insert(folders).values({ id, userId: mailbox.userId, mailboxId: mailbox.id, name });
+ } catch {
+ notCreated[creationId] = { type: "invalidProperties", properties: ["name"], description: "A folder with that name already exists" };
+ continue;
+ }
+ const jmapId = encodeMailboxRef({ kind: "folder", mailboxId: mailbox.id, folderId: id });
+ ctx.createdIds[creationId] = jmapId;
+ created[creationId] = { id: jmapId, role: null, sortOrder: 0, totalEmails: 0, unreadEmails: 0, totalThreads: 0, unreadThreads: 0, isSubscribed: true };
+ }
+
+ for (const [id, patch] of Object.entries((args.update ?? {}) as Record<string, Record<string, unknown>>)) {
+ const ref = decodeMailboxRef(id);
+ const mailbox = ref && accessible.find((row) => row.id === ref.mailboxId);
+ if (!ref || !mailbox) {
+ notUpdated[id] = { type: "notFound" };
+ continue;
+ }
+ const keys = Object.keys(patch).filter((key) => key !== "isSubscribed" && key !== "sortOrder");
+ if (ref.kind !== "folder") {
+ notUpdated[id] = keys.length ? { type: "forbidden", description: "System mailboxes cannot be changed" } : undefined!;
+ if (!keys.length) updated[id] = null;
+ continue;
+ }
+ if (keys.some((key) => key !== "name")) {
+ notUpdated[id] = { type: "invalidProperties", properties: keys.filter((key) => key !== "name") };
+ continue;
+ }
+ if (typeof patch.name === "string" && patch.name.trim()) {
+ await ctx.db
+ .update(folders)
+ .set({ name: patch.name.trim() })
+ .where(and(eq(folders.id, ref.folderId), eq(folders.mailboxId, mailbox.id)));
+ }
+ updated[id] = null;
+ }
+
+ for (const id of (args.destroy ?? []) as string[]) {
+ const ref = decodeMailboxRef(id);
+ const mailbox = ref && accessible.find((row) => row.id === ref.mailboxId);
+ if (!ref || !mailbox) {
+ notDestroyed[id] = { type: "notFound" };
+ continue;
+ }
+ if (ref.kind !== "folder" || mailbox.permission !== "full_access") {
+ notDestroyed[id] = { type: "forbidden" };
+ continue;
+ }
+ if (args.onDestroyRemoveEmails) {
+ await ctx.db.update(messages).set({ status: "trash", folderId: null }).where(eq(messages.folderId, ref.folderId));
+ } else {
+ const [inUse] = await ctx.db.select({ n: count() }).from(messages).where(and(eq(messages.folderId, ref.folderId), isNull(messages.snoozedUntil)));
+ if ((inUse?.n ?? 0) > 0) {
+ notDestroyed[id] = { type: "mailboxHasEmail" };
+ continue;
+ }
+ }
+ await ctx.db.delete(folders).where(and(eq(folders.id, ref.folderId), eq(folders.mailboxId, mailbox.id)));
+ destroyed.push(id);
+ }
+
+ return {
+ accountId: ctx.accountId,
+ oldState,
+ newState: await getMailboxState(ctx),
+ created,
+ updated,
+ destroyed,
+ notCreated,
+ notUpdated,
+ notDestroyed,
+ };
+};
+
+export function pick(item: Record<string, unknown>, properties: string[] | null | undefined): Record<string, unknown> {
+ if (!properties) return item;
+ const result: Record<string, unknown> = { id: item.id };
+ for (const key of properties) if (key in item) result[key] = item[key];
+ return result;
+}
+
+export function ensureJmapError(error: unknown): never {
+ if (error instanceof JmapError) throw error;
+ throw error;
+}
diff --git a/src/lib/jmap/processor.ts b/src/lib/jmap/processor.ts
new file mode 100644
index 0000000..c4b7292
--- /dev/null
+++ b/src/lib/jmap/processor.ts
@@ -0,0 +1,141 @@
+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 { emailSubmissionChanges, emailSubmissionGet, emailSubmissionQuery, emailSubmissionSet, identityChanges, identityGet, identitySet } from "./identities";
+import { getEmailState, getMailboxState } from "./state";
+import type { JmapContext, JmapInvocation, JmapMethodHandler, JmapRequest, JmapResponse } from "./types";
+
+const METHODS: Record<string, JmapMethodHandler> = {
+ "Core/echo": async (_ctx, args) => args,
+ "Mailbox/get": mailboxGet,
+ "Mailbox/query": mailboxQuery,
+ "Mailbox/changes": mailboxChanges,
+ "Mailbox/queryChanges": async () => ({ type: "cannotCalculateChanges" }),
+ "Mailbox/set": mailboxSet,
+ "Thread/get": threadGet,
+ "Thread/changes": threadChanges,
+ "Email/get": emailGet,
+ "Email/query": emailQuery,
+ "Email/changes": emailChanges,
+ "Email/queryChanges": emailQueryChanges,
+ "Email/set": emailSet,
+ "Email/copy": emailUnsupported("Email/copy"),
+ "Email/import": emailUnsupported("Email/import"),
+ "Email/parse": emailUnsupported("Email/parse"),
+ "SearchSnippet/get": searchSnippetGet,
+ "Identity/get": identityGet,
+ "Identity/changes": identityChanges,
+ "Identity/set": identitySet,
+ "EmailSubmission/get": emailSubmissionGet,
+ "EmailSubmission/query": emailSubmissionQuery,
+ "EmailSubmission/changes": emailSubmissionChanges,
+ "EmailSubmission/queryChanges": async () => ({ type: "cannotCalculateChanges" }),
+ "EmailSubmission/set": emailSubmissionSet,
+};
+
+export const SUPPORTED_CAPABILITIES = new Set([CAPABILITY_CORE, CAPABILITY_MAIL, CAPABILITY_SUBMISSION]);
+
+/** JSON Pointer lookup with the JMAP `*` array-flattening extension. */
+function resolvePointer(value: unknown, path: string): unknown {
+ const segments = path.split("/").slice(1).map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
+ let current: unknown = value;
+ for (let index = 0; index < segments.length; index += 1) {
+ const segment = segments[index];
+ if (segment === "*" && Array.isArray(current)) {
+ const rest = `/${segments.slice(index + 1).join("/")}`;
+ return current.flatMap((item) => {
+ const resolved = segments.length > index + 1 ? resolvePointer(item, rest) : item;
+ return Array.isArray(resolved) ? resolved : [resolved];
+ });
+ }
+ if (current === null || typeof current !== "object") throw new JmapError("invalidResultReference", `Path ${path} not found`);
+ current = (current as Record<string, unknown>)[segment];
+ }
+ return current;
+}
+
+/** Replace `#arg` result references with values from earlier responses. */
+function resolveReferences(args: Record<string, unknown>, responses: JmapInvocation[]): Record<string, unknown> {
+ const resolved: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(args)) {
+ if (!key.startsWith("#")) {
+ resolved[key] = value;
+ continue;
+ }
+ const ref = value as { resultOf: string; name: string; path: string };
+ const source = responses.find(([name, , callId]) => callId === ref.resultOf && name === ref.name);
+ if (!source) throw new JmapError("invalidResultReference", `No response ${ref.name} for call ${ref.resultOf}`);
+ resolved[key.slice(1)] = resolvePointer(source[1], ref.path);
+ }
+ return resolved;
+}
+
+/** Client creation ids (`#draft1`) become server ids once the create has run. */
+function resolveCreatedIds(args: Record<string, unknown>, createdIds: Record<string, string>): Record<string, unknown> {
+ const walk = (value: unknown): unknown => {
+ if (typeof value === "string" && value.startsWith("#") && createdIds[value.slice(1)]) return createdIds[value.slice(1)];
+ if (Array.isArray(value)) return value.map(walk);
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, walk(v)]));
+ return value;
+ };
+ return walk(args) as Record<string, unknown>;
+}
+
+export async function processRequest(ctx: JmapContext, request: JmapRequest): Promise<JmapResponse> {
+ const responses: JmapInvocation[] = [];
+ Object.assign(ctx.createdIds, request.createdIds ?? {});
+
+ for (const [name, rawArgs, callId] of request.methodCalls) {
+ const handler = METHODS[name];
+ if (!handler) {
+ responses.push(["error", { type: "unknownMethod" }, callId]);
+ continue;
+ }
+ try {
+ const args = resolveCreatedIds(resolveReferences(rawArgs ?? {}, responses), ctx.createdIds);
+ if (args.accountId !== undefined && args.accountId !== ctx.accountId && name !== "Core/echo") {
+ responses.push(["error", { type: "accountNotFound" }, callId]);
+ continue;
+ }
+ const result = await handler(ctx, args);
+ if ("type" in result && typeof result.type === "string" && !("accountId" in result) && !("list" in result)) {
+ responses.push(["error", result, callId]);
+ continue;
+ }
+ const { __destroyedEmails, ...clean } = result as Record<string, unknown> & { __destroyedEmails?: string[] };
+ responses.push([name, clean, callId]);
+ // A successful submission removed the draft: report it the way RFC 8621 §7.5 describes.
+ if (name === "EmailSubmission/set" && __destroyedEmails?.length) {
+ responses.push(["Email/set", { accountId: ctx.accountId, oldState: clean.oldState, newState: clean.newState, updated: {}, destroyed: __destroyedEmails, created: {} }, callId]);
+ }
+ } catch (error) {
+ if (error instanceof JmapError) {
+ responses.push(["error", error.toMethodError(), callId]);
+ } else {
+ console.error(`JMAP ${name} failed`, error);
+ responses.push(["error", { type: "serverFail", description: error instanceof Error ? error.message : "Unexpected error" }, callId]);
+ }
+ }
+ }
+
+ return { methodResponses: responses, createdIds: Object.keys(ctx.createdIds).length ? ctx.createdIds : undefined, sessionState: await sessionState(ctx) };
+}
+
+export async function sessionState(ctx: JmapContext): Promise<string> {
+ return `${await getMailboxState(ctx)}:${(await getEmailState(ctx)).split(".")[0]}`;
+}
+
+export function validateRequest(body: unknown): JmapRequest {
+ if (!body || typeof body !== "object") throw new JmapError("notRequest");
+ const request = body as Partial<JmapRequest>;
+ if (!Array.isArray(request.using) || !Array.isArray(request.methodCalls)) throw new JmapError("notRequest");
+ for (const capability of request.using) {
+ if (!SUPPORTED_CAPABILITIES.has(String(capability))) throw new JmapError("unknownCapability", String(capability));
+ }
+ if (request.methodCalls.length > LIMITS.maxCallsInRequest) throw new JmapError("limit", "Too many method calls", { limit: "maxCallsInRequest" });
+ for (const call of request.methodCalls) {
+ if (!Array.isArray(call) || call.length !== 3 || typeof call[0] !== "string" || typeof call[2] !== "string") throw new JmapError("notRequest");
+ }
+ return request as JmapRequest;
+}
diff --git a/src/lib/jmap/session.ts b/src/lib/jmap/session.ts
new file mode 100644
index 0000000..aae6262
--- /dev/null
+++ b/src/lib/jmap/session.ts
@@ -0,0 +1,54 @@
+import { CAPABILITY_CORE, CAPABILITY_MAIL, CAPABILITY_SUBMISSION, LIMITS } from "./constants";
+import type { JmapContext } from "./types";
+
+/** The Session object (RFC 8620 §2). One account per API key: the key's user. */
+export function buildSession(ctx: JmapContext, sessionState: string) {
+ const base = `${ctx.origin}/jmap`;
+ return {
+ capabilities: {
+ [CAPABILITY_CORE]: {
+ maxSizeUpload: LIMITS.maxSizeUpload,
+ maxConcurrentUpload: 4,
+ maxSizeRequest: LIMITS.maxSizeRequest,
+ maxConcurrentRequests: 4,
+ maxCallsInRequest: LIMITS.maxCallsInRequest,
+ maxObjectsInGet: LIMITS.maxObjectsInGet,
+ maxObjectsInSet: LIMITS.maxObjectsInSet,
+ collationAlgorithms: ["i;ascii-casemap", "i;unicode-casemap"],
+ },
+ [CAPABILITY_MAIL]: {},
+ [CAPABILITY_SUBMISSION]: {},
+ },
+ accounts: {
+ [ctx.accountId]: {
+ name: ctx.auth.email,
+ isPersonal: true,
+ isReadOnly: false,
+ accountCapabilities: {
+ [CAPABILITY_MAIL]: {
+ maxMailboxesPerEmail: 1,
+ maxMailboxDepth: 2,
+ maxSizeMailboxName: 80,
+ maxSizeAttachmentsPerEmail: LIMITS.maxSizeAttachmentsPerEmail,
+ emailQuerySortOptions: ["receivedAt", "sentAt", "subject", "from", "size", "hasKeyword"],
+ mayCreateTopLevelMailbox: false,
+ },
+ [CAPABILITY_SUBMISSION]: {
+ maxDelayedSend: 0,
+ submissionExtensions: {},
+ },
+ },
+ },
+ },
+ primaryAccounts: {
+ [CAPABILITY_MAIL]: ctx.accountId,
+ [CAPABILITY_SUBMISSION]: ctx.accountId,
+ },
+ username: ctx.auth.email,
+ apiUrl: `${base}/api`,
+ downloadUrl: `${base}/download/{accountId}/{blobId}/{name}?type={type}`,
+ uploadUrl: `${base}/upload/{accountId}`,
+ eventSourceUrl: `${base}/eventsource?types={types}&closeafter={closeafter}&ping={ping}`,
+ state: sessionState,
+ };
+}
diff --git a/src/lib/jmap/state.ts b/src/lib/jmap/state.ts
new file mode 100644
index 0000000..573c370
--- /dev/null
+++ b/src/lib/jmap/state.ts
@@ -0,0 +1,38 @@
+import { count, inArray, max, sql, sum } from "drizzle-orm";
+import { folders, messages } from "@/db/schema";
+import type { JmapContext } from "./types";
+import { listAccessibleMailboxIdSet } from "./access";
+
+/**
+ * Opaque state strings. Messages have no updated_at, so the Email state is a
+ * digest of what a client would notice changing: row count, newest row, and
+ * the flag and status tallies. Changes cannot be replayed from it, so
+ * /changes answers cannotCalculateChanges and clients re-query.
+ */
+export async function getEmailState(ctx: JmapContext): Promise<string> {
+ const ids = Array.from(await listAccessibleMailboxIdSet(ctx));
+ if (ids.length === 0) return "0";
+ const [row] = await ctx.db
+ .select({
+ total: count(),
+ newest: max(sql<number>`${messages}.rowid`),
+ read: sum(sql`case when ${messages.read} then 1 else 0 end`),
+ starred: sum(sql`case when ${messages.starred} then 1 else 0 end`),
+ status: sum(sql`length(${messages.status})`),
+ folder: sum(sql`case when ${messages.folderId} is null then 0 else 1 end`),
+ })
+ .from(messages)
+ .where(inArray(messages.mailboxId, ids));
+ return [row?.total ?? 0, row?.newest ?? 0, row?.read ?? 0, row?.starred ?? 0, row?.status ?? 0, row?.folder ?? 0].join(".");
+}
+
+export async function getMailboxState(ctx: JmapContext): Promise<string> {
+ const ids = Array.from(await listAccessibleMailboxIdSet(ctx));
+ if (ids.length === 0) return "0";
+ const [row] = await ctx.db
+ .select({ total: count(), newest: max(sql<number>`${folders}.rowid`), names: sum(sql`length(${folders.name})`) })
+ .from(folders)
+ .where(inArray(folders.mailboxId, ids));
+ // Counts live on Mailbox objects, so the mailbox state moves with the email state too.
+ return `${ids.length}.${row?.total ?? 0}.${row?.newest ?? 0}.${row?.names ?? 0}.${await getEmailState(ctx)}`;
+}
diff --git a/src/lib/jmap/types.d.ts b/src/lib/jmap/types.d.ts
new file mode 100644
index 0000000..4254724
--- /dev/null
+++ b/src/lib/jmap/types.d.ts
@@ -0,0 +1,96 @@
+import type { ApiAuthResult } from "@/lib/api/key-auth-types";
+import type { AppDatabase } from "@/db";
+
+export type JmapId = string;
+
+/** [methodName, arguments, callId] */
+export type JmapInvocation = [string, Record<string, unknown>, string];
+
+export type JmapRequest = {
+ using: string[];
+ methodCalls: JmapInvocation[];
+ createdIds?: Record<string, JmapId>;
+};
+
+export type JmapResponse = {
+ methodResponses: JmapInvocation[];
+ createdIds?: Record<string, JmapId>;
+ sessionState: string;
+};
+
+export type JmapMethodError = { type: string; description?: string; [key: string]: unknown };
+
+export type JmapContext = {
+ env: CloudflareEnv;
+ db: AppDatabase;
+ auth: ApiAuthResult;
+ accountId: string;
+ origin: string;
+ /** Client-assigned creation ids resolved so far in this request. */
+ createdIds: Record<string, JmapId>;
+};
+
+export type JmapMethodHandler = (ctx: JmapContext, args: Record<string, unknown>) => Promise<Record<string, unknown> | JmapMethodError>;
+
+/** How a JMAP Mailbox id maps onto Mailflare's mailbox × status/folder model. */
+export type MailboxRef =
+ | { kind: "account"; mailboxId: string }
+ | { kind: "role"; mailboxId: string; role: SystemRole }
+ | { kind: "folder"; mailboxId: string; folderId: string };
+
+export type SystemRole = "inbox" | "sent" | "drafts" | "archive" | "junk" | "trash";
+
+export type AccessibleMailbox = {
+ id: string;
+ userId: string;
+ localPart: string;
+ hostname: string;
+ displayName: string | null;
+ permission: "read_only" | "send_as" | "send_on_behalf" | "full_access";
+ type: "personal" | "shared";
+ isPrimary: boolean;
+};
+
+export type EmailAddressObject = { name: string | null; email: string };
+
+export type EmailBodyPart = {
+ partId: string | null;
+ blobId: string | null;
+ size: number;
+ headers?: Array<{ name: string; value: string }>;
+ name: string | null;
+ type: string;
+ charset: string | null;
+ disposition: string | null;
+ cid: string | null;
+ language: string[] | null;
+ location: string | null;
+ subParts?: EmailBodyPart[];
+};
+
+export type FilterCondition = {
+ inMailbox?: string;
+ inMailboxOtherThan?: string[];
+ before?: string;
+ after?: string;
+ minSize?: number;
+ maxSize?: number;
+ hasKeyword?: string;
+ notKeyword?: string;
+ allInThreadHaveKeyword?: string;
+ someInThreadHaveKeyword?: string;
+ noneInThreadHaveKeyword?: string;
+ text?: string;
+ from?: string;
+ to?: string;
+ cc?: string;
+ bcc?: string;
+ subject?: string;
+ body?: string;
+ hasAttachment?: boolean;
+};
+
+export type FilterOperator = { operator: "AND" | "OR" | "NOT"; conditions: Filter[] };
+export type Filter = FilterOperator | FilterCondition;
+
+export type Comparator = { property: string; isAscending?: boolean; collation?: string };
diff --git a/wrangler.jsonc b/wrangler.jsonc
index 21a7c75..14ee4c9 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -57,7 +57,7 @@
"send_email": [
{
"name": "EMAIL",
- "remote": true,
+ "remote": false,
},
],
"d1_databases": [