Skip to content

Email for professionals and teams

Add JMAP change log, mobile device sign-in and native push relay (#154)

Hieu Nguyen (Jack)c9137ca3b8c6
diff --git a/CLAUDE.md b/CLAUDE.md
index 2bad16c..2befb26 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -101,7 +101,13 @@ The app reaches every platform service through `getEnv()` (`src/lib/cloudflare.t
### 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`.
+`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).
+
+States are positions in a change log (`changes.ts`): the `jmap_changes_*` triggers of migration 0064 write a row per created, updated or destroyed message and per folder or mailbox change into `jmap_changes`, so `Email/changes`, `Mailbox/changes` and `Thread/changes` return real deltas (`Email/queryChanges` still answers `cannotCalculateChanges`). A state is `c1:<seq>:<access fingerprint>`; a sharing change alters the fingerprint, and the daily cron prunes rows older than 30 days and raises `jmap_change_floor`, and either makes older states answer `cannotCalculateChanges`. Like `jmap_mailbox_revisions`, these tables are derived and excluded from backups. Never write to them from application code.
+
+### Mobile apps: device keys and native push
+
+`POST /api/auth/device` signs a mobile app in with email + password (+ MFA via the login challenge) and returns a `jmap`-scoped API key of `kind = 'device'`, named after the device. It has its own rate limit (`DEVICE_LOGIN_RATE_LIMIT`) since it skips Turnstile. Device keys are listed and revoked under Settings → Security (`/api/devices`), hidden from the API keys list, and `deleteUserSessions` revokes them all (password change, reset, MFA change). Apps register their APNs token with `PUT /api/mobile/push` using the device key; `push_devices` rows cascade with the key. `notifyUsersOfNewMessage` fans out to `sendNativePush` (`src/lib/push/native.ts`), which needs the `APNS_KEY_ID`, `APNS_TEAM_ID` and `APNS_PRIVATE_KEY` secrets and encrypts sender and subject to each device's P-256 key (`native-crypto.ts`), or sends a content-free alert when the device turned previews off.
`Email/set` create and `Email/import` share one insert (`insertDraft` in `emails.ts`) and one target rule (`resolveDraftsMailbox` in `email-import-utils.ts`): a new message goes into exactly one Drafts mailbox, never Inbox or a folder, because delivered mail is the inbound pipeline's job. `Email/import` parses the uploaded blob with `parseRawMime`, stores the `Message-ID` in `providerMessageId` with its angle brackets (as inbound rows do) and keeps the uploaded bytes at `drafts/<messageId>.eml` in `rawR2Key`, so `readBlob` serves the client's own MIME back instead of the rebuilt minimal message; the `jmap-uploads/` object is deleted once claimed. `Email/copy` and `Email/parse` are still `emailUnsupported`.
diff --git a/drizzle/migrations/0064_add_jmap_changes_and_devices.sql b/drizzle/migrations/0064_add_jmap_changes_and_devices.sql
new file mode 100644
index 0000000..c882443
--- /dev/null
+++ b/drizzle/migrations/0064_add_jmap_changes_and_devices.sql
@@ -0,0 +1,83 @@
+CREATE TABLE `jmap_changes` (
+ `seq` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `mailbox_id` text NOT NULL,
+ `object_type` text NOT NULL,
+ `object_id` text NOT NULL,
+ `thread_id` text,
+ `change` text NOT NULL,
+ `created_at` integer DEFAULT (unixepoch()) NOT NULL
+);
+--> statement-breakpoint
+CREATE INDEX `jmap_changes_mailbox_seq_idx` ON `jmap_changes` (`mailbox_id`,`seq`);
+--> statement-breakpoint
+CREATE TABLE `jmap_change_floor` (
+ `id` integer PRIMARY KEY NOT NULL,
+ `seq` integer DEFAULT 0 NOT NULL
+);
+--> statement-breakpoint
+INSERT INTO `jmap_change_floor` (`id`, `seq`) VALUES (1, 0);
+--> statement-breakpoint
+CREATE TRIGGER `jmap_changes_messages_ai` AFTER INSERT ON `messages`
+WHEN NEW.mailbox_id IS NOT NULL BEGIN
+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)
+ VALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'created');
+END;
+--> statement-breakpoint
+CREATE TRIGGER `jmap_changes_messages_au` AFTER UPDATE ON `messages`
+WHEN NEW.mailbox_id IS NOT NULL AND OLD.mailbox_id IS NEW.mailbox_id BEGIN
+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)
+ VALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'updated');
+END;
+--> statement-breakpoint
+CREATE TRIGGER `jmap_changes_messages_au_moved` AFTER UPDATE OF mailbox_id ON `messages`
+WHEN OLD.mailbox_id IS NOT NEW.mailbox_id BEGIN
+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)
+ SELECT OLD.mailbox_id, 'email', OLD.id, coalesce(OLD.thread_id, OLD.id), 'destroyed' WHERE OLD.mailbox_id IS NOT NULL;
+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)
+ SELECT NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'created' WHERE NEW.mailbox_id IS NOT NULL;
+END;
+--> statement-breakpoint
+CREATE TRIGGER `jmap_changes_messages_ad` AFTER DELETE ON `messages`
+WHEN OLD.mailbox_id IS NOT NULL BEGIN
+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)
+ VALUES (OLD.mailbox_id, 'email', OLD.id, coalesce(OLD.thread_id, OLD.id), 'destroyed');
+END;
+--> statement-breakpoint
+CREATE TRIGGER `jmap_changes_folders_ai` AFTER INSERT ON `folders` BEGIN
+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (NEW.mailbox_id, 'mailbox', NEW.id, 'created');
+END;
+--> statement-breakpoint
+CREATE TRIGGER `jmap_changes_folders_au` AFTER UPDATE ON `folders` BEGIN
+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, change)
+ SELECT OLD.mailbox_id, 'mailbox', OLD.id, 'destroyed' WHERE OLD.mailbox_id IS NOT NEW.mailbox_id;
+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, change)
+ VALUES (NEW.mailbox_id, 'mailbox', NEW.id, CASE WHEN OLD.mailbox_id IS NEW.mailbox_id THEN 'updated' ELSE 'created' END);
+END;
+--> statement-breakpoint
+CREATE TRIGGER `jmap_changes_folders_ad` AFTER DELETE ON `folders` BEGIN
+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (OLD.mailbox_id, 'mailbox', OLD.id, 'destroyed');
+END;
+--> statement-breakpoint
+CREATE TRIGGER `jmap_changes_mailboxes_au` AFTER UPDATE ON `mailboxes` BEGIN
+ INSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (NEW.id, 'mailbox', NEW.id, 'updated');
+END;
+--> statement-breakpoint
+CREATE TABLE `push_devices` (
+ `id` text PRIMARY KEY NOT NULL,
+ `user_id` text NOT NULL,
+ `api_key_id` text NOT NULL,
+ `platform` text NOT NULL,
+ `token` text NOT NULL,
+ `environment` text DEFAULT 'production' NOT NULL,
+ `topic` text NOT NULL,
+ `public_key` text,
+ `previews` integer DEFAULT true NOT NULL,
+ `created_at` integer NOT NULL,
+ `updated_at` integer NOT NULL,
+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`api_key_id`) REFERENCES `api_keys`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `push_devices_platform_token_idx` ON `push_devices` (`platform`,`token`);
+--> statement-breakpoint
+CREATE INDEX `push_devices_user_idx` ON `push_devices` (`user_id`);
diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.json
index 79ae972..7f1ee1f 100644
--- a/drizzle/migrations/meta/_journal.json
+++ b/drizzle/migrations/meta/_journal.json
@@ -393,6 +393,13 @@
"when": 1788850804023,
"tag": "0063_add_account_deletion",
"breakpoints": true
+ },
+ {
+ "idx": 56,
+ "version": "6",
+ "when": 1788850805023,
+ "tag": "0064_add_jmap_changes_and_devices",
+ "breakpoints": true
}
]
}
diff --git a/env.d.ts b/env.d.ts
index dfe42e2..6a4cb82 100644
--- a/env.d.ts
+++ b/env.d.ts
@@ -20,6 +20,13 @@ interface CloudflareEnv {
import("./src/lib/realtime/hub").RealtimeHub
>;
LOGIN_RATE_LIMIT?: RateLimit;
+ /** Mobile device sign-in (`/api/auth/device`), stricter than the web login. */
+ DEVICE_LOGIN_RATE_LIMIT?: RateLimit;
+ /** APNs auth key for the mobile push relay (src/lib/push/native.ts). */
+ APNS_KEY_ID?: string;
+ APNS_TEAM_ID?: string;
+ /** The .p8 file contents (PKCS#8 PEM). */
+ APNS_PRIVATE_KEY?: string;
AGENT_RATE_LIMIT?: RateLimit;
/**
* Backblaze B2 storage. When all four are set, B2 replaces the R2 binding for raw mail, attachments, Drive,
diff --git a/server/runtime/env.ts b/server/runtime/env.ts
index 5770cac..93a6b79 100644
--- a/server/runtime/env.ts
+++ b/server/runtime/env.ts
@@ -56,6 +56,7 @@ export function createNodeRuntime(): NodeRuntime {
IMAGES: undefined as unknown as CloudflareEnv["IMAGES"],
WORKER_SELF_REFERENCE: undefined as unknown as CloudflareEnv["WORKER_SELF_REFERENCE"],
LOGIN_RATE_LIMIT: openRateLimiter(20, 60),
+ DEVICE_LOGIN_RATE_LIMIT: openRateLimiter(10, 60),
AGENT_RATE_LIMIT: openRateLimiter(120, 60),
B2_KEY_ID: optional("B2_KEY_ID"),
B2_APPLICATION_KEY: optional("B2_APPLICATION_KEY"),
diff --git a/server/runtime/scheduler.ts b/server/runtime/scheduler.ts
index 6fa9d22..d26f412 100644
--- a/server/runtime/scheduler.ts
+++ b/server/runtime/scheduler.ts
@@ -3,6 +3,7 @@ import { runAgentMaintenance } from "@/lib/agent/maintenance";
import { runTrashRetention } from "@/lib/email/trash-retention";
import { runDriveTrashRetention } from "@/lib/drive/retention";
import { runAccountRetention } from "@/lib/accounts/deletion";
+import { runJmapChangeRetention } from "@/lib/jmap/changes";
/** Fire the daily 02:00 UTC backup and the recurring maintenance jobs, matching the cron triggers in wrangler.jsonc. */
export function startScheduler(env: CloudflareEnv) {
@@ -17,6 +18,7 @@ export function startScheduler(env: CloudflareEnv) {
runScheduledDatabaseBackup(env, now).catch((error) => console.error("Scheduled backup failed", error));
runDriveTrashRetention(env, now).catch((error) => console.error("Drive trash retention failed", error));
runAccountRetention(env, now).catch((error) => console.error("Account retention failed", error));
+ runJmapChangeRetention(env, now).catch((error) => console.error("JMAP change retention failed", error));
}, 60_000);
return () => clearInterval(timer);
}
diff --git a/src/app/(settings)/settings/security/page.tsx b/src/app/(settings)/settings/security/page.tsx
index f091aa9..6ae934a 100644
--- a/src/app/(settings)/settings/security/page.tsx
+++ b/src/app/(settings)/settings/security/page.tsx
@@ -1,6 +1,7 @@
import { getServerTranslator } from "@/lib/i18n/server";
import { ChangePasswordForm } from "@/components/settings/change-password-form";
import { MfaSettings } from "@/components/settings/mfa-settings";
+import { DeviceSettings } from "@/components/settings/device-settings";
export default async function SecuritySettingsPage() {
const t = await getServerTranslator();
@@ -24,6 +25,13 @@ export default async function SecuritySettingsPage() {
</div>
<MfaSettings />
</div>
+ <div className="space-y-4 rounded-3xl bg-white p-6">
+ <div>
+ <h2 className="text-lg font-semibold text-neutral-900">{t("settingsPage.security.devices")}</h2>
+ <p className="mt-1 text-sm text-neutral-500">{t("settingsPage.security.devicesDescription")}</p>
+ </div>
+ <DeviceSettings />
+ </div>
</section>
</div>;
}
diff --git a/src/app/api/api-keys/route.ts b/src/app/api/api-keys/route.ts
index 4864dc7..0e05ef7 100644
--- a/src/app/api/api-keys/route.ts
+++ b/src/app/api/api-keys/route.ts
@@ -37,7 +37,7 @@ export async function GET(request: Request) {
.where(eq(apiKeys.userId, user.id));
const keyIds = rows.map((row) => row.id);
const allowed = keyIds.length ? await db.select().from(mcpKeyMailboxes).where(inArray(mcpKeyMailboxes.keyId, keyIds)) : [];
- return NextResponse.json({ apiKeys: rows.filter((row) => !parseScopes(row.scopes).some((scope) => (ADMIN_API_KEY_SCOPES as readonly string[]).includes(scope))).map((row) => ({ ...row, mailboxIds: allowed.filter((item) => item.keyId === row.id).map((item) => item.mailboxId) })) });
+ return NextResponse.json({ apiKeys: rows.filter((row) => row.kind !== "device" && !parseScopes(row.scopes).some((scope) => (ADMIN_API_KEY_SCOPES as readonly string[]).includes(scope))).map((row) => ({ ...row, mailboxIds: allowed.filter((item) => item.keyId === row.id).map((item) => item.mailboxId) })) });
}
export async function POST(request: Request) {
diff --git a/src/app/api/auth/device/route.ts b/src/app/api/auth/device/route.ts
new file mode 100644
index 0000000..7a565d5
--- /dev/null
+++ b/src/app/api/auth/device/route.ts
@@ -0,0 +1,75 @@
+import { NextResponse } from "next/server";
+import { eq } from "drizzle-orm";
+import { getEnv } from "@/lib/cloudflare";
+import { getDb } from "@/db";
+import { users } from "@/db/schema";
+import { verifyPassword } from "@/lib/auth/password";
+import { deviceLoginSchema } from "@/lib/validators";
+import { allowDeviceLoginAttempt } from "@/lib/auth/rate-limit";
+import { readJsonBody } from "@/lib/http/request";
+import { RequestBodyTooLargeError } from "@/lib/http/errors";
+import { recordAuthActivity } from "@/lib/auth/activity";
+import { consumeLoginChallenge, createLoginChallenge, getLoginChallengeUserId } from "@/lib/auth/login-challenge";
+import { verifySecondFactor } from "@/lib/auth/mfa";
+import { createDeviceKey, revokeDeviceKey } from "@/lib/auth/device-keys";
+import { authenticateApiRequest } from "@/lib/api/key-auth";
+
+function json(body: unknown, status = 200, headers: Record<string, string> = {}) {
+ return NextResponse.json(body, { status, headers: { "Cache-Control": "no-store", ...headers } });
+}
+
+/**
+ * Mobile sign-in with the account password. Answers with a `jmap`-scoped
+ * device key (shown under Settings → Devices, revocable) instead of a session.
+ * With MFA on, the first call returns `{ mfaRequired, challengeToken }` and a
+ * second call with `{ challengeToken, code, deviceName }` finishes.
+ */
+export async function POST(request: Request) {
+ const env = getEnv();
+ let body: unknown;
+ try {
+ body = await readJsonBody(request, 16 * 1024);
+ } catch (error) {
+ return json({ error: "Invalid sign-in request" }, error instanceof RequestBodyTooLargeError ? 413 : 400);
+ }
+ const parsed = deviceLoginSchema.safeParse(body);
+ if (!parsed.success) return json({ error: "Invalid sign-in request" }, 400);
+ if (!(await allowDeviceLoginAttempt(env, request))) {
+ return json({ error: "Too many sign-in attempts. Try again shortly." }, 429, { "Retry-After": "60" });
+ }
+
+ const db = getDb(env);
+ let userId: string;
+ if ("password" in parsed.data) {
+ const [user] = await db.select().from(users).where(eq(users.email, parsed.data.email)).limit(1);
+ if (!user || !verifyPassword(parsed.data.password, user.passwordHash)) return json({ error: "Invalid credentials" }, 401);
+ if (user.disabled || user.deletedAt) return json({ error: "Account disabled" }, 403);
+ if (user.totpEnabled && user.totpSecret) {
+ return json({ ok: true, mfaRequired: true, challengeToken: await createLoginChallenge(env, user.id) });
+ }
+ userId = user.id;
+ } else {
+ const challengeUserId = await getLoginChallengeUserId(env, parsed.data.challengeToken);
+ if (!challengeUserId) return json({ error: "This sign-in attempt has expired. Start again." }, 401);
+ const [user] = await db.select().from(users).where(eq(users.id, challengeUserId)).limit(1);
+ if (!user || user.disabled || user.deletedAt) return json({ error: "Account disabled" }, 403);
+ if (!(await verifySecondFactor(env, user, parsed.data.code))) return json({ error: "That code did not match" }, 401);
+ await consumeLoginChallenge(env, parsed.data.challengeToken);
+ userId = user.id;
+ }
+
+ const [user] = await db.select({ email: users.email }).from(users).where(eq(users.id, userId)).limit(1);
+ const device = await createDeviceKey(env, userId, parsed.data.deviceName);
+ await recordAuthActivity(env, { action: "auth.device_login", userId, request });
+ const origin = env.APP_URL?.trim().replace(/\/+$/, "") || new URL(request.url).origin;
+ return json({ ok: true, key: device.key, keyId: device.id, email: user?.email, sessionUrl: `${origin}/jmap/session` });
+}
+
+/** Signing out in the app: the device key revokes itself (and its push registration). */
+export async function DELETE(request: Request) {
+ const env = getEnv();
+ const auth = await authenticateApiRequest(env, request);
+ if (!auth || auth.keyKind !== "device") return json({ error: "Unauthorized" }, 401);
+ await revokeDeviceKey(env, auth.userId, auth.keyId);
+ return json({ ok: true });
+}
diff --git a/src/app/api/devices/[id]/route.ts b/src/app/api/devices/[id]/route.ts
new file mode 100644
index 0000000..d7fab58
--- /dev/null
+++ b/src/app/api/devices/[id]/route.ts
@@ -0,0 +1,16 @@
+import { NextResponse } from "next/server";
+import { getEnv } from "@/lib/cloudflare";
+import { requireSessionUser } from "@/lib/api/auth";
+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";
+import { revokeDeviceKey } from "@/lib/auth/device-keys";
+
+/** Signs a device out: its key stops working and its push registration goes. */
+export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
+ const env = getEnv();
+ const { user, error } = await requireSessionUser(env, request);
+ if (error) return error;
+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });
+ const { id } = await params;
+ if (!(await revokeDeviceKey(env, user.id, id))) return NextResponse.json({ error: "Device not found" }, { status: 404 });
+ return NextResponse.json({ ok: true });
+}
diff --git a/src/app/api/devices/route.ts b/src/app/api/devices/route.ts
new file mode 100644
index 0000000..b2c7c18
--- /dev/null
+++ b/src/app/api/devices/route.ts
@@ -0,0 +1,12 @@
+import { NextResponse } from "next/server";
+import { getEnv } from "@/lib/cloudflare";
+import { requireSessionUser } from "@/lib/api/auth";
+import { listDeviceKeys } from "@/lib/auth/device-keys";
+
+/** Mobile devices signed in to this account (Settings → Devices). */
+export async function GET(request: Request) {
+ const env = getEnv();
+ const { user, error } = await requireSessionUser(env, request);
+ if (error) return error;
+ return NextResponse.json({ devices: await listDeviceKeys(env, user.id) });
+}
diff --git a/src/app/api/mobile/push/route.ts b/src/app/api/mobile/push/route.ts
new file mode 100644
index 0000000..c181f59
--- /dev/null
+++ b/src/app/api/mobile/push/route.ts
@@ -0,0 +1,48 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+import { getEnv } from "@/lib/cloudflare";
+import { authenticateApiRequest, hasScope } from "@/lib/api/key-auth";
+import { readJsonBody } from "@/lib/http/request";
+import { registerPushDevice, unregisterPushDevice } from "@/lib/push/native";
+import { isValidDevicePublicKey } from "@/lib/push/native-crypto";
+
+const registrationSchema = z.object({
+ platform: z.literal("apns"),
+ token: z.string().regex(/^[0-9a-fA-F]{32,200}$/),
+ environment: z.enum(["production", "sandbox"]).default("production"),
+ topic: z.string().min(3).max(200),
+ publicKey: z.string().max(200).nullable().default(null),
+ previews: z.boolean().default(true),
+});
+
+async function authenticate(env: CloudflareEnv, request: Request) {
+ const auth = await authenticateApiRequest(env, request);
+ if (!auth) return { auth: null, error: NextResponse.json({ error: "Unauthorized" }, { status: 401 }) } as const;
+ if (!hasScope(auth.scopes, "jmap")) return { auth: null, error: NextResponse.json({ error: "This key does not have the jmap scope" }, { status: 403 }) } as const;
+ return { auth, error: null } as const;
+}
+
+/**
+ * The mobile app registers its APNs token here, authenticated with the same
+ * device key it uses for JMAP. Revoking the key removes the registration.
+ */
+export async function PUT(request: Request) {
+ const env = getEnv();
+ const { auth, error } = await authenticate(env, request);
+ if (error) return error;
+ const parsed = registrationSchema.safeParse(await readJsonBody(request, 8 * 1024).catch(() => null));
+ if (!parsed.success) return NextResponse.json({ error: "Invalid registration" }, { status: 400 });
+ if (parsed.data.publicKey && !isValidDevicePublicKey(parsed.data.publicKey)) {
+ return NextResponse.json({ error: "publicKey must be a raw uncompressed P-256 point" }, { status: 400 });
+ }
+ await registerPushDevice(env, auth.userId, auth.keyId, { ...parsed.data, token: parsed.data.token.toLowerCase() });
+ return NextResponse.json({ ok: true });
+}
+
+export async function DELETE(request: Request) {
+ const env = getEnv();
+ const { auth, error } = await authenticate(env, request);
+ if (error) return error;
+ await unregisterPushDevice(env, auth.keyId);
+ return NextResponse.json({ ok: true });
+}
diff --git a/src/components/settings/device-settings-types.d.ts b/src/components/settings/device-settings-types.d.ts
new file mode 100644
index 0000000..dcbef9c
--- /dev/null
+++ b/src/components/settings/device-settings-types.d.ts
@@ -0,0 +1,7 @@
+export type MobileDevice = {
+ id: string;
+ name: string;
+ createdAt: string;
+ lastUsedAt: string | null;
+ pushEnabled: boolean;
+};
diff --git a/src/components/settings/device-settings-utils.ts b/src/components/settings/device-settings-utils.ts
new file mode 100644
index 0000000..6e56219
--- /dev/null
+++ b/src/components/settings/device-settings-utils.ts
@@ -0,0 +1,17 @@
+import { authFetch } from "@/lib/auth/client";
+import type { MobileDevice } from "./device-settings-types";
+
+export async function loadDevices(): Promise<MobileDevice[]> {
+ const res = await authFetch("/api/devices");
+ const data = (await res.json()) as { devices?: MobileDevice[]; error?: string };
+ if (!res.ok) throw new Error(data.error ?? "Failed to load devices");
+ return data.devices ?? [];
+}
+
+export async function signOutDevice(id: string): Promise<void> {
+ const res = await authFetch(`/api/devices/${encodeURIComponent(id)}`, { method: "DELETE" });
+ if (!res.ok) {
+ const data = (await res.json().catch(() => ({}))) as { error?: string };
+ throw new Error(data.error ?? "Failed to sign the device out");
+ }
+}
diff --git a/src/components/settings/device-settings.tsx b/src/components/settings/device-settings.tsx
new file mode 100644
index 0000000..4774885
--- /dev/null
+++ b/src/components/settings/device-settings.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Bell, Smartphone } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
+import { Button } from "@/components/ui/button";
+import { formatUserDate } from "@/lib/time/utils";
+import type { MobileDevice } from "./device-settings-types";
+import { loadDevices, signOutDevice } from "./device-settings-utils";
+
+/**
+ * Settings > Security card listing phones and tablets signed in with the
+ * mobile app. Each holds a device key; signing one out revokes the key and
+ * its push registration.
+ */
+export function DeviceSettings() {
+ const { t } = useLanguage();
+ const [devices, setDevices] = useState<MobileDevice[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState<string | null>(null);
+
+ useEffect(() => {
+ loadDevices().then(setDevices).catch((err) => setError(err instanceof Error ? err.message : t("devices.loadFailed")));
+ }, [t]);
+
+ async function remove(device: MobileDevice) {
+ if (!window.confirm(t("devices.signOutConfirm", { name: device.name }))) return;
+ setBusy(device.id);
+ try {
+ await signOutDevice(device.id);
+ setDevices((list) => list?.filter((item) => item.id !== device.id) ?? null);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : t("devices.loadFailed"));
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ if (!devices) return <p className="text-sm text-neutral-500">{error ?? t("devices.loading")}</p>;
+ if (devices.length === 0) return <p className="text-sm text-neutral-500">{t("devices.empty")}</p>;
+
+ return (
+ <div className="space-y-3">
+ {error ? <p className="text-sm text-red-600">{error}</p> : null}
+ <ul className="divide-y divide-neutral-100 rounded-2xl bg-neutral-50">
+ {devices.map((device) => (
+ <li key={device.id} className="flex items-center gap-3 p-4">
+ <Smartphone className="h-5 w-5 shrink-0 text-neutral-500" />
+ <div className="min-w-0 flex-1">
+ <p className="flex items-center gap-2 truncate text-sm font-medium text-neutral-900">
+ {device.name}
+ {device.pushEnabled ? <Bell className="h-3.5 w-3.5 text-neutral-400" aria-label={t("devices.push")} /> : null}
+ </p>
+ <p className="truncate text-sm text-neutral-500">
+ {t("devices.signedIn", { date: formatUserDate(device.createdAt, { dateStyle: "short" }) })} ·{" "}
+ {device.lastUsedAt ? t("apiKeys.lastUsed", { date: formatUserDate(device.lastUsedAt, { dateStyle: "short" }) }) : t("apiKeys.neverUsed")}
+ </p>
+ </div>
+ <Button variant="outline" size="sm" disabled={busy === device.id} onClick={() => remove(device)}>
+ {t("devices.signOut")}
+ </Button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts
index 643789d..2cac2d7 100644
--- a/src/db/schema/index.ts
+++ b/src/db/schema/index.ts
@@ -217,9 +217,36 @@ export const jmapMailboxRevisions = sqliteTable("jmap_mailbox_revisions", {
revision: integer("revision").notNull().default(0),
});
+/**
+ * JMAP change log, written only by the `jmap_changes_*` triggers of migration
+ * 0064: one row per created, updated or destroyed Email (and per folder or
+ * mailbox change), so `Email/changes`, `Mailbox/changes` and `Thread/changes`
+ * return real deltas. `seq` is the state; rows older than the retention
+ * window are pruned and `jmap_change_floor` records the last pruned seq.
+ */
+export const jmapChanges = sqliteTable(
+ "jmap_changes",
+ {
+ seq: integer("seq").primaryKey({ autoIncrement: true }),
+ mailboxId: text("mailbox_id").notNull(),
+ objectType: text("object_type", { enum: ["email", "mailbox"] }).notNull(),
+ objectId: text("object_id").notNull(),
+ threadId: text("thread_id"),
+ change: text("change", { enum: ["created", "updated", "destroyed"] }).notNull(),
+ createdAt: integer("created_at").notNull().default(sql`(unixepoch())`),
+ },
+ (table) => [index("jmap_changes_mailbox_seq_idx").on(table.mailboxId, table.seq)],
+);
+
+export const jmapChangeFloor = sqliteTable("jmap_change_floor", {
+ id: integer("id").primaryKey(),
+ seq: integer("seq").notNull().default(0),
+});
+
export const apiKeys = sqliteTable("api_keys", {
id: text("id").primaryKey(),
- kind: text("kind", { enum: ["legacy", "mcp"] }).notNull().default("legacy"),
+ /** `device` keys come from a mobile sign-in (`/api/auth/device`) and are listed under Devices. */
+ kind: text("kind", { enum: ["legacy", "mcp", "device"] }).notNull().default("legacy"),
userId: text("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
@@ -566,6 +593,30 @@ export const sessions = sqliteTable("sessions", {
.$defaultFn(() => new Date()),
});
+/** A native app's push registration (APNs), owned by the device's API key. */
+export const pushDevices = sqliteTable(
+ "push_devices",
+ {
+ id: text("id").primaryKey(),
+ userId: text("user_id")
+ .notNull()
+ .references(() => users.id, { onDelete: "cascade" }),
+ apiKeyId: text("api_key_id")
+ .notNull()
+ .references(() => apiKeys.id, { onDelete: "cascade" }),
+ platform: text("platform", { enum: ["apns"] }).notNull(),
+ token: text("token").notNull(),
+ environment: text("environment", { enum: ["production", "sandbox"] }).notNull().default("production"),
+ topic: text("topic").notNull(),
+ /** Base64 raw P-256 public key; previews are encrypted to it. */
+ publicKey: text("public_key"),
+ previews: integer("previews", { mode: "boolean" }).notNull().default(true),
+ createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull(),
+ },
+ (table) => [uniqueIndex("push_devices_platform_token_idx").on(table.platform, table.token), index("push_devices_user_idx").on(table.userId)],
+);
+
export const pushSubscriptions = sqliteTable(
"push_subscriptions",
{
diff --git a/src/lib/api/key-auth-types.d.ts b/src/lib/api/key-auth-types.d.ts
index 238a449..875e824 100644
--- a/src/lib/api/key-auth-types.d.ts
+++ b/src/lib/api/key-auth-types.d.ts
@@ -1,6 +1,9 @@
import type { users } from "@/db/schema";
export type ApiAuthResult = {
+ /** The API key that authenticated; mobile push registrations hang off it. */
+ keyId: string;
+ keyKind: "legacy" | "mcp" | "device";
userId: string;
email: string;
scopes: string[];
diff --git a/src/lib/api/key-auth.ts b/src/lib/api/key-auth.ts
index 2d2d2e2..8b4aab0 100644
--- a/src/lib/api/key-auth.ts
+++ b/src/lib/api/key-auth.ts
@@ -35,7 +35,7 @@ export async function authenticateApiKeyValue(env: CloudflareEnv, key: string):
const allowed = candidate.mailboxScopeEnabled
? await db.select({ mailboxId: mcpKeyMailboxes.mailboxId }).from(mcpKeyMailboxes).where(eq(mcpKeyMailboxes.keyId, candidate.id))
: null;
- return { userId: user.id, email: user.email, scopes: scopes.some((scope) => ADMIN_SCOPES.has(scope)) ? scopes.filter((scope) => ADMIN_SCOPES.has(scope)) : scopes, mailboxIds: allowed?.map((row) => row.mailboxId) ?? null, user };
+ return { keyId: candidate.id, keyKind: candidate.kind, userId: user.id, email: user.email, scopes: scopes.some((scope) => ADMIN_SCOPES.has(scope)) ? scopes.filter((scope) => ADMIN_SCOPES.has(scope)) : scopes, mailboxIds: allowed?.map((row) => row.mailboxId) ?? null, user };
}
return null;
}
diff --git a/src/lib/auth/activity-types.d.ts b/src/lib/auth/activity-types.d.ts
index 4f459a2..924c1d4 100644
--- a/src/lib/auth/activity-types.d.ts
+++ b/src/lib/auth/activity-types.d.ts
@@ -1,4 +1,4 @@
-export type AuthActivityAction = "auth.login" | "auth.logout" | "auth.mfa_verified" | "auth.password_reset";
+export type AuthActivityAction = "auth.login" | "auth.logout" | "auth.mfa_verified" | "auth.password_reset" | "auth.device_login";
export type AuthActivityMetadata = {
ipAddress: string;
diff --git a/src/lib/auth/device-keys.ts b/src/lib/auth/device-keys.ts
new file mode 100644
index 0000000..bbe7353
--- /dev/null
+++ b/src/lib/auth/device-keys.ts
@@ -0,0 +1,53 @@
+import { and, desc, eq } from "drizzle-orm";
+import { getDb } from "@/db";
+import { apiKeys, pushDevices } from "@/db/schema";
+import { generateApiKey, scopesToJson } from "@/lib/api-keys";
+import { newId } from "@/lib/ids";
+
+/**
+ * Device keys: what a mobile app receives from `/api/auth/device`. Each is a
+ * `jmap`-scoped API key named after the device, with no mailbox restriction
+ * (access follows `mailbox_access` live). They never carry admin scopes and
+ * are revoked with the user's sessions.
+ */
+export async function createDeviceKey(env: CloudflareEnv, userId: string, deviceName: string): Promise<{ id: string; key: string }> {
+ const { fullKey, prefix, hash } = generateApiKey();
+ const id = newId("key");
+ await getDb(env).insert(apiKeys).values({
+ id,
+ kind: "device",
+ userId,
+ name: deviceName.slice(0, 100),
+ prefix,
+ keyHash: hash,
+ scopes: scopesToJson(["jmap"]),
+ mailboxScopeEnabled: false,
+ });
+ return { id, key: fullKey };
+}
+
+export async function listDeviceKeys(env: CloudflareEnv, userId: string) {
+ const db = getDb(env);
+ const keys = await db
+ .select({ id: apiKeys.id, name: apiKeys.name, createdAt: apiKeys.createdAt, lastUsedAt: apiKeys.lastUsedAt })
+ .from(apiKeys)
+ .where(and(eq(apiKeys.userId, userId), eq(apiKeys.kind, "device")))
+ .orderBy(desc(apiKeys.createdAt));
+ const push = await db.select({ apiKeyId: pushDevices.apiKeyId }).from(pushDevices).where(eq(pushDevices.userId, userId));
+ const withPush = new Set(push.map((row) => row.apiKeyId));
+ return keys.map((key) => ({ ...key, pushEnabled: withPush.has(key.id) }));
+}
+
+/** Returns whether a key was removed. Its push registrations cascade. */
+export async function revokeDeviceKey(env: CloudflareEnv, userId: string, keyId: string): Promise<boolean> {
+ const db = getDb(env);
+ const removed = await db
+ .delete(apiKeys)
+ .where(and(eq(apiKeys.id, keyId), eq(apiKeys.userId, userId), eq(apiKeys.kind, "device")))
+ .returning({ id: apiKeys.id });
+ return removed.length > 0;
+}
+
+export async function revokeAllDeviceKeys(env: CloudflareEnv, userId: string): Promise<void> {
+ await getDb(env).delete(apiKeys).where(and(eq(apiKeys.userId, userId), eq(apiKeys.kind, "device")));
+}
diff --git a/src/lib/auth/rate-limit.ts b/src/lib/auth/rate-limit.ts
index dfd29ae..ea94f52 100644
--- a/src/lib/auth/rate-limit.ts
+++ b/src/lib/auth/rate-limit.ts
@@ -1,3 +1,16 @@
+/** Mobile sign-ins have their own, stricter budget (they skip Turnstile). */
+export async function allowDeviceLoginAttempt(env: CloudflareEnv, request: Request): Promise<boolean> {
+ const limiter = env.DEVICE_LOGIN_RATE_LIMIT ?? env.LOGIN_RATE_LIMIT;
+ if (!limiter) return true;
+ const ip = request.headers.get("cf-connecting-ip")?.trim() || "unknown";
+ try {
+ return (await limiter.limit({ key: `device:${ip}` })).success;
+ } catch (error) {
+ console.warn("Device login rate limiter unavailable", error);
+ return true;
+ }
+}
+
export async function allowLoginAttempt(env: CloudflareEnv, request: Request): Promise<boolean> {
if (!env.LOGIN_RATE_LIMIT) return true;
const ip = request.headers.get("cf-connecting-ip")?.trim() || "unknown";
diff --git a/src/lib/auth/session.ts b/src/lib/auth/session.ts
index 4551a8e..eba21fa 100644
--- a/src/lib/auth/session.ts
+++ b/src/lib/auth/session.ts
@@ -1,4 +1,5 @@
import { and, eq, gt, ne } from "drizzle-orm";
+import { revokeAllDeviceKeys } from "@/lib/auth/device-keys";
import { newId } from "@/lib/ids";
import { getDb } from "@/db";
import { sessions, users } from "@/db/schema";
@@ -70,8 +71,14 @@ export async function deleteSession(env: CloudflareEnv, token: string): Promise<
* Sign the user out everywhere, optionally keeping the session that made the
* request. Used after a password change or reset and when MFA is switched on.
*/
+/**
+ * Signs the user out everywhere: every session (but `keepToken`'s) and every
+ * mobile device key, so a password change or "sign out everywhere" also
+ * disconnects the apps.
+ */
export async function deleteUserSessions(env: CloudflareEnv, userId: string, keepToken?: string): Promise<void> {
const db = getDb(env);
+ await revokeAllDeviceKeys(env, userId);
if (keepToken) {
const keepHash = await hashSessionToken(keepToken);
await db.delete(sessions).where(and(eq(sessions.userId, userId), ne(sessions.tokenHash, keepHash)));
diff --git a/src/lib/backups/export.ts b/src/lib/backups/export.ts
index 23ce2fd..00a8fe1 100644
--- a/src/lib/backups/export.ts
+++ b/src/lib/backups/export.ts
@@ -30,6 +30,12 @@ const INTERNAL_TABLES = [
// Exporting it would make restore fail, since the triggers recreate these
// primary keys before the table's own rows would be inserted.
"jmap_mailbox_revisions",
+ // The JMAP change log is derived the same way (jmap_changes_* triggers);
+ // after a restore clients resync because their states no longer apply.
+ "jmap_changes",
+ "jmap_change_floor",
+ // Push registrations are re-sent by each app on launch.
+ "push_devices",
];
/**
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index 99bbe6d..f8985bb 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -730,6 +730,15 @@
"settingsPage.security.changePasswordDescription": "Use at least 8 characters for your new password.",
"settingsPage.security.mfa": "Two-factor authentication",
"settingsPage.security.mfaDescription": "Require a code from an authenticator app when signing in.",
+ "settingsPage.security.devices": "Mobile devices",
+ "settingsPage.security.devicesDescription": "Phones and tablets signed in with the Mailflare app. Signing a device out stops its mail and notifications. Changing your password signs out every device.",
+ "devices.loading": "Loading devices...",
+ "devices.loadFailed": "Failed to load devices",
+ "devices.empty": "No devices are signed in.",
+ "devices.signedIn": "Signed in {date}",
+ "devices.push": "Notifications on",
+ "devices.signOut": "Sign out",
+ "devices.signOutConfirm": "Sign out {name}? The app will ask for your password again.",
"settingsPage.appPasswords.title": "App Passwords",
"settingsPage.appPasswords.description": "Use your mail from a desktop or mobile app over JMAP.",
"folder.drafts.empty": "No drafts",
diff --git a/src/lib/jmap/changes-utils.ts b/src/lib/jmap/changes-utils.ts
new file mode 100644
index 0000000..e423bd4
--- /dev/null
+++ b/src/lib/jmap/changes-utils.ts
@@ -0,0 +1,39 @@
+/** Pure helpers for JMAP change states; see changes.ts. */
+
+const PREFIX = "c1";
+
+export function formatState(seq: number, fingerprint: string): string {
+ return `${PREFIX}:${seq}:${fingerprint}`;
+}
+
+export function parseState(value: unknown): { seq: number; fingerprint: string } | null {
+ if (typeof value !== "string") return null;
+ const [prefix, seq, fingerprint, ...rest] = value.split(":");
+ if (prefix !== PREFIX || !fingerprint || rest.length) return null;
+ const number = Number(seq);
+ return Number.isSafeInteger(number) && number >= 0 ? { seq: number, fingerprint } : null;
+}
+
+/**
+ * Folds ordered change rows into JMAP's created/updated/destroyed sets: an
+ * object created and destroyed in the window is not reported at all, one
+ * destroyed and created again (moved away and back) is updated.
+ */
+export function coalesceChanges(rows: Array<{ id: string; change: string }>): { created: string[]; updated: string[]; destroyed: string[] } {
+ const created = new Set<string>();
+ const updated = new Set<string>();
+ const destroyed = new Set<string>();
+ for (const { id, change } of rows) {
+ if (change === "created") {
+ if (destroyed.delete(id)) updated.add(id);
+ else created.add(id);
+ } else if (change === "updated") {
+ if (!created.has(id)) updated.add(id);
+ } else if (change === "destroyed") {
+ if (created.delete(id)) continue;
+ updated.delete(id);
+ destroyed.add(id);
+ }
+ }
+ return { created: [...created], updated: [...updated], destroyed: [...destroyed] };
+}
diff --git a/src/lib/jmap/changes.ts b/src/lib/jmap/changes.ts
new file mode 100644
index 0000000..11f70cb
--- /dev/null
+++ b/src/lib/jmap/changes.ts
@@ -0,0 +1,197 @@
+import { and, asc, eq, gt, inArray, sql } from "drizzle-orm";
+import { getDb, type AppDatabase } from "@/db";
+import { jmapChangeFloor, jmapChanges, messages } from "@/db/schema";
+import { listFoldersByMailbox, listJmapMailboxes } from "./access";
+import { encodeMailboxRef, SYSTEM_ROLES } from "./ids";
+import type { AccessibleMailbox, JmapContext } from "./types";
+import { coalesceChanges, formatState, parseState } from "./changes-utils";
+
+/**
+ * States are `c1:<seq>:<access>`: the newest change-log sequence among the
+ * account's mailboxes, plus a fingerprint of which mailboxes it can see and
+ * how. A sharing change alters the fingerprint, so a `Foo/changes` call from an older
+ * state answers `cannotCalculateChanges` and the client resyncs.
+ */
+async function accessFingerprint(mailboxes: AccessibleMailbox[]): Promise<string> {
+ const material = JSON.stringify(mailboxes.map((m) => [m.id, m.permission]).sort((a, b) => String(a[0]).localeCompare(String(b[0]))));
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(material));
+ return Array.from(new Uint8Array(digest).slice(0, 8), (b) => b.toString(16).padStart(2, "0")).join("");
+}
+
+async function floorSeq(ctx: JmapContext): Promise<number> {
+ const [row] = await ctx.db.select({ seq: jmapChangeFloor.seq }).from(jmapChangeFloor).where(eq(jmapChangeFloor.id, 1)).limit(1);
+ return row?.seq ?? 0;
+}
+
+/** Newest sequence per mailbox, one indexed MAX per mailbox. */
+async function latestSeq(ctx: JmapContext, mailboxIds: string[]): Promise<number> {
+ let latest = 0;
+ for (let offset = 0; offset < mailboxIds.length; offset += 50) {
+ const chunk = mailboxIds.slice(offset, offset + 50);
+ const parts = chunk.map((id) => sql`SELECT (SELECT max(seq) FROM jmap_changes WHERE mailbox_id = ${id}) AS seq`);
+ const rows = await ctx.db.all<{ seq: number | null }>(sql.join(parts, sql` UNION ALL `));
+ for (const row of rows) latest = Math.max(latest, row.seq ?? 0);
+ }
+ return latest;
+}
+
+export type ChangeScope = {
+ mailboxes: AccessibleMailbox[];
+ seq: number;
+ fingerprint: string;
+ state: string;
+};
+
+export async function currentChangeScope(ctx: JmapContext): Promise<ChangeScope> {
+ const mailboxes = await listJmapMailboxes(ctx);
+ const [seq, fingerprint, floor] = await Promise.all([latestSeq(ctx, mailboxes.map((m) => m.id)), accessFingerprint(mailboxes), floorSeq(ctx)]);
+ const effective = Math.max(seq, floor);
+ return { mailboxes, seq: effective, fingerprint, state: formatState(effective, fingerprint) };
+}
+
+type ChangeRow = { seq: number; mailboxId: string; objectType: string; objectId: string; threadId: string | null; change: string };
+
+/**
+ * Log rows after `sinceState`, or null when the state cannot be continued
+ * from (unknown format, pruned history, or the account's access changed).
+ */
+async function rowsSince(
+ ctx: JmapContext,
+ sinceState: unknown,
+ objectType: "email" | "mailbox" | null,
+ limit: number,
+): Promise<{ scope: ChangeScope; rows: ChangeRow[]; hasMore: boolean } | null> {
+ const since = parseState(sinceState);
+ const scope = await currentChangeScope(ctx);
+ if (!since || since.fingerprint !== scope.fingerprint || since.seq > scope.seq) return null;
+ if (since.seq < (await floorSeq(ctx))) return null;
+ const ids = scope.mailboxes.map((m) => m.id);
+ if (ids.length === 0) return { scope, rows: [], hasMore: false };
+ const conditions = [inArray(jmapChanges.mailboxId, ids), gt(jmapChanges.seq, since.seq)];
+ if (objectType) conditions.push(eq(jmapChanges.objectType, objectType));
+ const rows = await ctx.db
+ .select({
+ seq: jmapChanges.seq,
+ mailboxId: jmapChanges.mailboxId,
+ objectType: jmapChanges.objectType,
+ objectId: jmapChanges.objectId,
+ threadId: jmapChanges.threadId,
+ change: jmapChanges.change,
+ })
+ .from(jmapChanges)
+ .where(and(...conditions))
+ .orderBy(asc(jmapChanges.seq))
+ .limit(limit + 1);
+ const hasMore = rows.length > limit;
+ return { scope, rows: hasMore ? rows.slice(0, limit) : rows, hasMore };
+}
+
+function maxChangesOf(args: Record<string, unknown>): number {
+ const requested = typeof args.maxChanges === "number" && args.maxChanges > 0 ? Math.floor(args.maxChanges) : 500;
+ return Math.min(requested, 5000);
+}
+
+function cannot() {
+ return { type: "cannotCalculateChanges", description: "The state is too old or access changed; fetch again." };
+}
+
+export async function emailChangesSince(ctx: JmapContext, args: Record<string, unknown>) {
+ const limit = maxChangesOf(args);
+ const result = await rowsSince(ctx, args.sinceState, "email", limit);
+ if (!result) return cannot();
+ const { created, updated, destroyed } = coalesceChanges(result.rows.map((row) => ({ id: row.objectId, change: row.change })));
+ const newState = result.hasMore ? formatState(result.rows[result.rows.length - 1].seq, result.scope.fingerprint) : result.scope.state;
+ return { accountId: ctx.accountId, oldState: args.sinceState, newState, hasMoreChanges: result.hasMore, created, updated, destroyed };
+}
+
+/**
+ * Threads touched since the state. A thread whose messages are all gone is
+ * destroyed; one first seen in this window is created; the rest are updated.
+ */
+export async function threadChangesSince(ctx: JmapContext, args: Record<string, unknown>) {
+ const limit = maxChangesOf(args);
+ const result = await rowsSince(ctx, args.sinceState, "email", limit);
+ if (!result) return cannot();
+ const firstChange = new Map<string, string>();
+ for (const row of result.rows) {
+ const thread = row.threadId ?? row.objectId;
+ if (!firstChange.has(thread)) firstChange.set(thread, row.change);
+ }
+ const threads = Array.from(firstChange.keys());
+ const ids = result.scope.mailboxes.map((m) => m.id);
+ const threadKey = sql<string>`coalesce(${messages.threadId}, ${messages.id})`;
+ const alive = new Set<string>();
+ for (let offset = 0; offset < threads.length; offset += 100) {
+ const chunk = threads.slice(offset, offset + 100);
+ const rows = await ctx.db
+ .selectDistinct({ thread: threadKey })
+ .from(messages)
+ .where(and(inArray(threadKey, chunk), inArray(messages.mailboxId, ids)));
+ for (const row of rows) alive.add(row.thread);
+ }
+ const created: string[] = [];
+ const updated: string[] = [];
+ const destroyed: string[] = [];
+ for (const [thread, first] of firstChange) {
+ if (!alive.has(thread)) destroyed.push(thread);
+ else if (first === "created" && result.rows.every((row) => (row.threadId ?? row.objectId) !== thread || row.change === "created")) created.push(thread);
+ else updated.push(thread);
+ }
+ const newState = result.hasMore ? formatState(result.rows[result.rows.length - 1].seq, result.scope.fingerprint) : result.scope.state;
+ return { accountId: ctx.accountId, oldState: args.sinceState, newState, hasMoreChanges: result.hasMore, created, updated, destroyed };
+}
+
+/**
+ * Mailbox changes. Any message change alters counts, so every JMAP mailbox of
+ * a touched address is reported updated; folder rows add creations and
+ * deletions.
+ */
+export async function mailboxChangesSince(ctx: JmapContext, args: Record<string, unknown>) {
+ const limit = maxChangesOf(args) * 20;
+ const result = await rowsSince(ctx, args.sinceState, null, limit);
+ if (!result) return cannot();
+ const touched = new Set<string>();
+ const folderChanges: Array<{ id: string; change: string }> = [];
+ for (const row of result.rows) {
+ touched.add(row.mailboxId);
+ if (row.objectType === "mailbox" && row.objectId !== row.mailboxId) {
+ folderChanges.push({ id: encodeMailboxRef({ kind: "folder", mailboxId: row.mailboxId, folderId: row.objectId }), change: row.change });
+ }
+ }
+ const { created, updated, destroyed } = coalesceChanges(folderChanges);
+ const reported = new Set([...created, ...updated, ...destroyed]);
+ const folders = await listFoldersByMailbox(ctx, [...touched]);
+ for (const mailboxId of touched) {
+ const all = [
+ encodeMailboxRef({ kind: "account", mailboxId }),
+ ...SYSTEM_ROLES.map((role) => encodeMailboxRef({ kind: "role", mailboxId, role })),
+ ...(folders.get(mailboxId) ?? []).map((folder) => encodeMailboxRef({ kind: "folder", mailboxId, folderId: folder.id })),
+ ];
+ for (const id of all) {
+ if (!reported.has(id)) {
+ updated.push(id);
+ reported.add(id);
+ }
+ }
+ }
+ const newState = result.hasMore ? formatState(result.rows[result.rows.length - 1].seq, result.scope.fingerprint) : result.scope.state;
+ return { accountId: ctx.accountId, oldState: args.sinceState, newState, hasMoreChanges: result.hasMore, updatedProperties: null, created, updated, destroyed };
+}
+
+/** Change-log retention. Clients older than this resync from scratch. */
+export const CHANGE_RETENTION_DAYS = 30;
+
+/** Prunes old change rows and raises the floor; run from the daily cron. */
+export async function pruneJmapChanges(db: AppDatabase, now = Date.now()): Promise<number> {
+ const cutoff = Math.floor(now / 1000) - CHANGE_RETENTION_DAYS * 86400;
+ const [row] = await db.all<{ seq: number | null }>(sql`SELECT max(seq) AS seq FROM jmap_changes WHERE created_at < ${cutoff}`);
+ const floor = row?.seq ?? 0;
+ if (!floor) return 0;
+ await db.run(sql`UPDATE jmap_change_floor SET seq = max(seq, ${floor}) WHERE id = 1`);
+ const deleted = await db.run(sql`DELETE FROM jmap_changes WHERE seq <= ${floor}`);
+ return Number((deleted as { meta?: { changes?: number } }).meta?.changes ?? 0);
+}
+
+export async function runJmapChangeRetention(env: CloudflareEnv, now: Date): Promise<void> {
+ await pruneJmapChanges(getDb(env), now.getTime());
+}
diff --git a/src/lib/jmap/emails.ts b/src/lib/jmap/emails.ts
index 0b024a2..bcecf61 100644
--- a/src/lib/jmap/emails.ts
+++ b/src/lib/jmap/emails.ts
@@ -1,4 +1,5 @@
import { and, asc, count, desc, eq, inArray, sql } from "drizzle-orm";
+import { emailChangesSince, threadChangesSince } from "./changes";
import { messages } from "@/db/schema";
import { newId } from "@/lib/ids";
import { buildSnippet, parseRawMime } from "@/lib/email/parse";
@@ -147,9 +148,7 @@ export const emailQuery: JmapMethodHandler = async (ctx, args) => {
};
};
-export const emailChanges: JmapMethodHandler = async () => {
- return { type: "cannotCalculateChanges", description: "Email change history is not kept; run Email/query again." };
-};
+export const emailChanges: JmapMethodHandler = async (ctx, args) => emailChangesSince(ctx, args);
export const emailQueryChanges: JmapMethodHandler = async () => {
return { type: "cannotCalculateChanges" };
@@ -464,7 +463,7 @@ export const threadGet: JmapMethodHandler = async (ctx, args) => {
};
};
-export const threadChanges: JmapMethodHandler = async () => ({ type: "cannotCalculateChanges" });
+export const threadChanges: JmapMethodHandler = async (ctx, args) => threadChangesSince(ctx, args);
/** SearchSnippet/get: the subject and a body excerpt around the first match, with <mark> tags. */
export const searchSnippetGet: JmapMethodHandler = async (ctx, args) => {
diff --git a/src/lib/jmap/mailboxes.ts b/src/lib/jmap/mailboxes.ts
index 55b6d8d..b0f9317 100644
--- a/src/lib/jmap/mailboxes.ts
+++ b/src/lib/jmap/mailboxes.ts
@@ -1,4 +1,5 @@
import { and, count, eq, inArray, isNull, sql } from "drizzle-orm";
+import { mailboxChangesSince } from "./changes";
import { folders, messages } from "@/db/schema";
import { newId } from "@/lib/ids";
import { JmapError } from "./errors";
@@ -176,9 +177,7 @@ export const mailboxQuery: JmapMethodHandler = async (ctx, args) => {
};
};
-export const mailboxChanges: JmapMethodHandler = async () => {
- return { type: "cannotCalculateChanges", description: "Mailbox change history is not kept; run Mailbox/get again." };
-};
+export const mailboxChanges: JmapMethodHandler = async (ctx, args) => mailboxChangesSince(ctx, args);
/** Folders can be created, renamed and removed; system mailboxes cannot. */
export const mailboxSet: JmapMethodHandler = async (ctx, args) => {
diff --git a/src/lib/jmap/revision.ts b/src/lib/jmap/revision.ts
deleted file mode 100644
index c5990d8..0000000
--- a/src/lib/jmap/revision.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { inArray } from "drizzle-orm";
-import { jmapMailboxRevisions } from "@/db/schema";
-import { listJmapMailboxes } from "./access";
-import type { JmapContext } from "./types";
-
-/** A cheap change signal for the stream; every message and folder write bumps a mailbox revision. */
-export async function getJmapRevision(ctx: JmapContext): Promise<string> {
- const mailboxes = await listJmapMailboxes(ctx);
- const ids = mailboxes.map((mailbox) => mailbox.id);
- if (ids.length === 0) return "[]";
- const revisions = new Map<string, number>();
- for (let offset = 0; offset < ids.length; offset += 100) {
- const rows = await ctx.db
- .select({ mailboxId: jmapMailboxRevisions.mailboxId, revision: jmapMailboxRevisions.revision })
- .from(jmapMailboxRevisions)
- .where(inArray(jmapMailboxRevisions.mailboxId, ids.slice(offset, offset + 100)));
- for (const row of rows) revisions.set(row.mailboxId, row.revision);
- }
- return JSON.stringify(mailboxes.map((mailbox) => [mailbox.id, mailbox.permission, mailbox.localPart, mailbox.hostname, mailbox.displayName, revisions.get(mailbox.id) ?? 0]).sort((a, b) => String(a[0]).localeCompare(String(b[0]))));
-}
diff --git a/src/lib/jmap/state.ts b/src/lib/jmap/state.ts
index ab34f2f..6d44386 100644
--- a/src/lib/jmap/state.ts
+++ b/src/lib/jmap/state.ts
@@ -1,11 +1,15 @@
import type { JmapContext } from "./types";
-import { getJmapRevision } from "./revision";
+import { currentChangeScope } from "./changes";
-/** Opaque revision tokens change on every message or folder write. */
+/**
+ * States are change-log positions (see changes.ts), shared by every type:
+ * any message, folder or mailbox write moves them, and `*\/changes` can
+ * continue from them.
+ */
export async function getEmailState(ctx: JmapContext): Promise<string> {
- return getJmapRevision(ctx);
+ return (await currentChangeScope(ctx)).state;
}
export async function getMailboxState(ctx: JmapContext, emailState?: string): Promise<string> {
- return emailState ?? getJmapRevision(ctx);
+ return emailState ?? getEmailState(ctx);
}
diff --git a/src/lib/push/native-crypto.ts b/src/lib/push/native-crypto.ts
new file mode 100644
index 0000000..6ddd60a
--- /dev/null
+++ b/src/lib/push/native-crypto.ts
@@ -0,0 +1,88 @@
+/**
+ * Crypto for native (APNs) push, on Web Crypto so it runs on Workers and Node.
+ *
+ * Previews are encrypted per device so Apple never sees sender or subject:
+ * an ephemeral P-256 key agrees with the device's registered public key
+ * (ECDH), HKDF-SHA256 (random salt, info "mailflare-push-v1") derives an
+ * AES-256-GCM key, and the payload carries the ephemeral public key, salt, IV
+ * and ciphertext. The app's Notification Service Extension reverses it with
+ * the private key it keeps in the Secure Enclave (CryptoKit:
+ * `sharedSecret.hkdfDerivedSymmetricKey(using: SHA256, salt:, sharedInfo:, outputByteCount: 32)`).
+ */
+
+export const PUSH_HKDF_INFO = "mailflare-push-v1";
+
+export type EncryptedPreview = {
+ /** Ephemeral public key, raw uncompressed point, base64. */
+ epk: string;
+ salt: string;
+ iv: string;
+ /** AES-GCM ciphertext with the 16-byte tag appended, base64. */
+ ct: string;
+};
+
+export function toBase64(bytes: Uint8Array): string {
+ let binary = "";
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary);
+}
+
+export function fromBase64(value: string): Uint8Array {
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
+ const padded = normalized + "=".repeat((4 - (normalized.length % 4)) % 4);
+ return Uint8Array.from(atob(padded), (char) => char.charCodeAt(0));
+}
+
+function base64Url(bytes: Uint8Array): string {
+ return toBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
+}
+
+function buffer(bytes: Uint8Array): ArrayBuffer {
+ const out = new ArrayBuffer(bytes.byteLength);
+ new Uint8Array(out).set(bytes);
+ return out;
+}
+
+/** A device public key must be an uncompressed P-256 point (65 bytes, 0x04 prefix). */
+export function isValidDevicePublicKey(value: string): boolean {
+ try {
+ const bytes = fromBase64(value);
+ return bytes.length === 65 && bytes[0] === 4;
+ } catch {
+ return false;
+ }
+}
+
+export async function encryptPreview(devicePublicKey: string, plaintext: Uint8Array): Promise<EncryptedPreview> {
+ const recipient = await crypto.subtle.importKey("raw", buffer(fromBase64(devicePublicKey)), { name: "ECDH", namedCurve: "P-256" }, false, []);
+ const ephemeral = (await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits"])) as CryptoKeyPair;
+ const shared = await crypto.subtle.deriveBits({ name: "ECDH", public: recipient }, ephemeral.privateKey, 256);
+ const salt = crypto.getRandomValues(new Uint8Array(16));
+ const iv = crypto.getRandomValues(new Uint8Array(12));
+ const hkdf = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
+ const key = await crypto.subtle.deriveKey(
+ { name: "HKDF", hash: "SHA-256", salt: buffer(salt), info: new TextEncoder().encode(PUSH_HKDF_INFO) },
+ hkdf,
+ { name: "AES-GCM", length: 256 },
+ false,
+ ["encrypt"],
+ );
+ const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv: buffer(iv) }, key, buffer(plaintext));
+ const epk = new Uint8Array(await crypto.subtle.exportKey("raw", ephemeral.publicKey));
+ return { epk: toBase64(epk), salt: toBase64(salt), iv: toBase64(iv), ct: toBase64(new Uint8Array(ciphertext)) };
+}
+
+/** Imports an APNs auth key (the .p8 file: PKCS#8 PEM). */
+export async function importApnsKey(pem: string): Promise<CryptoKey> {
+ const body = pem.replace(/-----(BEGIN|END) PRIVATE KEY-----/g, "").replace(/\s+/g, "");
+ return crypto.subtle.importKey("pkcs8", buffer(fromBase64(body)), { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
+}
+
+/** The provider token APNs expects: an ES256 JWT with the key id and team id. */
+export async function signApnsJwt(key: CryptoKey, keyId: string, teamId: string, issuedAt = Math.floor(Date.now() / 1000)): Promise<string> {
+ const encoder = new TextEncoder();
+ const header = base64Url(encoder.encode(JSON.stringify({ alg: "ES256", kid: keyId })));
+ const claims = base64Url(encoder.encode(JSON.stringify({ iss: teamId, iat: issuedAt })));
+ const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, encoder.encode(`${header}.${claims}`));
+ return `${header}.${claims}.${base64Url(new Uint8Array(signature))}`;
+}
diff --git a/src/lib/push/native.ts b/src/lib/push/native.ts
new file mode 100644
index 0000000..78473fe
--- /dev/null
+++ b/src/lib/push/native.ts
@@ -0,0 +1,114 @@
+import { eq, inArray } from "drizzle-orm";
+import { getDb } from "@/db";
+import { pushDevices } from "@/db/schema";
+import { newId } from "@/lib/ids";
+import type { NewMessageNotification } from "@/lib/realtime/types";
+import { encryptPreview, importApnsKey, signApnsJwt } from "./native-crypto";
+
+/**
+ * Native push relay for the mobile apps (APNs). Configured with the
+ * `APNS_KEY_ID`, `APNS_TEAM_ID` and `APNS_PRIVATE_KEY` (the .p8 contents)
+ * secrets; without them registrations are kept but nothing is sent.
+ */
+type ApnsConfig = { keyId: string; teamId: string; privateKey: string };
+
+function apnsConfig(env: CloudflareEnv): ApnsConfig | null {
+ const keyId = env.APNS_KEY_ID?.trim();
+ const teamId = env.APNS_TEAM_ID?.trim();
+ const privateKey = env.APNS_PRIVATE_KEY?.trim();
+ return keyId && teamId && privateKey ? { keyId, teamId, privateKey } : null;
+}
+
+export function isNativePushConfigured(env: CloudflareEnv): boolean {
+ return apnsConfig(env) !== null;
+}
+
+/** APNs accepts a provider token for up to an hour; refresh well before. */
+let cachedToken: { value: string; keyId: string; expiresAt: number } | null = null;
+
+async function providerToken(config: ApnsConfig): Promise<string> {
+ const now = Date.now();
+ if (cachedToken && cachedToken.keyId === config.keyId && cachedToken.expiresAt > now) return cachedToken.value;
+ const key = await importApnsKey(config.privateKey);
+ const value = await signApnsJwt(key, config.keyId, config.teamId, Math.floor(now / 1000));
+ cachedToken = { value, keyId: config.keyId, expiresAt: now + 45 * 60 * 1000 };
+ return value;
+}
+
+export type PushRegistration = {
+ platform: "apns";
+ token: string;
+ environment: "production" | "sandbox";
+ topic: string;
+ publicKey: string | null;
+ previews: boolean;
+};
+
+/** Registers (or moves) a device token to the key that authenticated. */
+export async function registerPushDevice(env: CloudflareEnv, userId: string, apiKeyId: string, registration: PushRegistration): Promise<void> {
+ const now = new Date();
+ await getDb(env)
+ .insert(pushDevices)
+ .values({ id: newId("pdev"), userId, apiKeyId, ...registration, createdAt: now, updatedAt: now })
+ .onConflictDoUpdate({
+ target: [pushDevices.platform, pushDevices.token],
+ set: { userId, apiKeyId, environment: registration.environment, topic: registration.topic, publicKey: registration.publicKey, previews: registration.previews, updatedAt: now },
+ });
+}
+
+export async function unregisterPushDevice(env: CloudflareEnv, apiKeyId: string): Promise<void> {
+ await getDb(env).delete(pushDevices).where(eq(pushDevices.apiKeyId, apiKeyId));
+}
+
+/** The APNs JSON for one device: encrypted preview, or content-free when previews are off. */
+export async function buildApnsPayload(device: { publicKey: string | null; previews: boolean }, accountId: string, message: NewMessageNotification) {
+ const base = { v: 1, accountId, mailboxId: message.mailboxId };
+ if (!device.previews || !device.publicKey) {
+ return { aps: { alert: { title: "Mailflare", body: "New message" }, "mutable-content": 1, sound: "default", "thread-id": message.mailboxId }, mf: base };
+ }
+ const preview = new TextEncoder().encode(
+ JSON.stringify({ from: message.from, fromName: message.fromName, subject: message.subject, messageId: message.messageId }),
+ );
+ return {
+ // Shown only if the extension cannot decrypt in time.
+ aps: { alert: { title: "Mailflare", body: "New message" }, "mutable-content": 1, sound: "default", "thread-id": message.mailboxId },
+ mf: { ...base, enc: await encryptPreview(device.publicKey, preview) },
+ };
+}
+
+/** Sends a new-message push to every registered device of `userIds`. Expired tokens are dropped. */
+export async function sendNativePush(env: CloudflareEnv, userIds: string[], message: NewMessageNotification): Promise<void> {
+ const config = apnsConfig(env);
+ if (!config || userIds.length === 0) return;
+ const db = getDb(env);
+ const devices = await db.select().from(pushDevices).where(inArray(pushDevices.userId, userIds));
+ if (devices.length === 0) return;
+ const token = await providerToken(config);
+ const stale: string[] = [];
+ await Promise.allSettled(
+ devices.map(async (device) => {
+ const host = device.environment === "sandbox" ? "api.sandbox.push.apple.com" : "api.push.apple.com";
+ const payload = await buildApnsPayload(device, device.userId, message);
+ const response = await fetch(`https://${host}/3/device/${device.token}`, {
+ method: "POST",
+ headers: {
+ authorization: `bearer ${token}`,
+ "apns-topic": device.topic,
+ "apns-push-type": "alert",
+ "apns-priority": "10",
+ "apns-collapse-id": message.messageId.slice(0, 64),
+ "content-type": "application/json",
+ },
+ body: JSON.stringify(payload),
+ });
+ if (response.ok) return;
+ const reason = ((await response.json().catch(() => ({}))) as { reason?: string }).reason;
+ if (response.status === 410 || reason === "BadDeviceToken" || reason === "Unregistered" || reason === "DeviceTokenNotForTopic") {
+ stale.push(device.id);
+ } else {
+ console.warn(`APNs push failed (${response.status} ${reason ?? ""})`);
+ }
+ }),
+ );
+ if (stale.length) await db.delete(pushDevices).where(inArray(pushDevices.id, stale));
+}
diff --git a/src/lib/realtime/utils.ts b/src/lib/realtime/utils.ts
index 307fe7a..da030a4 100644
--- a/src/lib/realtime/utils.ts
+++ b/src/lib/realtime/utils.ts
@@ -4,6 +4,7 @@ import { domains, mailboxAccess, mailboxes } from "@/db/schema";
import { isTeamMailboxSharingEnabled } from "@/lib/mailboxes/access-utils";
import type { NewMessageNotification, AgentDraftNotification } from "./types";
import { sendPushNotifications } from "@/lib/push/server";
+import { sendNativePush } from "@/lib/push/native";
export function getSessionTokenFromRequest(request: Request): string | undefined {
const cookie = request.headers.get("Cookie");
@@ -65,6 +66,6 @@ export async function notifyUsersOfNewMessage(
body: JSON.stringify(payload),
});
}),
- ...(payload.type === "agent_draft" ? [] : [sendPushNotifications(env, userIds, payload)]),
+ ...(payload.type === "agent_draft" ? [] : [sendPushNotifications(env, userIds, payload), sendNativePush(env, userIds, payload)]),
]);
}
diff --git a/src/lib/validators.ts b/src/lib/validators.ts
index 801b876..c94b070 100644
--- a/src/lib/validators.ts
+++ b/src/lib/validators.ts
@@ -92,6 +92,12 @@ export const passwordResetConfirmSchema = z.object({
password: z.string().min(8).max(128),
});
+/** `/api/auth/device`: either email + password, or a challenge + code after MFA. */
+export const deviceLoginSchema = z.union([
+ z.object({ email: z.string().trim().email(), password: z.string().min(1), deviceName: z.string().trim().min(1).max(100) }),
+ z.object({ challengeToken: z.string().min(8).max(200), code: z.string().trim().min(6).max(32), deviceName: z.string().trim().min(1).max(100) }),
+]);
+
export const mfaVerifySchema = z.object({
challengeToken: z.string().min(8).max(200),
code: z.string().trim().min(6).max(32),
diff --git a/tests/mobile-sync-push.test.mjs b/tests/mobile-sync-push.test.mjs
new file mode 100644
index 0000000..85ca4a3
--- /dev/null
+++ b/tests/mobile-sync-push.test.mjs
@@ -0,0 +1,92 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test, { after } from "node:test";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { build } from "esbuild";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const outDir = mkdtempSync(join(tmpdir(), "mailflare-mobile-"));
+after(() => rmSync(outDir, { recursive: true, force: true }));
+
+async function bundle(entry, outfile) {
+ await build({
+ entryPoints: [join(root, entry)],
+ outfile: join(outDir, outfile),
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ target: "node22",
+ logLevel: "silent",
+ alias: { "@": join(root, "src") },
+ });
+ return import(pathToFileURL(join(outDir, outfile)).href);
+}
+
+const changes = await bundle("src/lib/jmap/changes-utils.ts", "changes-utils.mjs");
+const push = await bundle("src/lib/push/native-crypto.ts", "native-crypto.mjs");
+
+test("JMAP states round-trip and reject other formats", () => {
+ assert.deepEqual(changes.parseState(changes.formatState(42, "abcd")), { seq: 42, fingerprint: "abcd" });
+ assert.equal(changes.parseState('[["mbx","full_access"]]'), null);
+ assert.equal(changes.parseState("c1:-1:abcd"), null);
+ assert.equal(changes.parseState(null), null);
+});
+
+test("change rows coalesce into JMAP created/updated/destroyed", () => {
+ const result = changes.coalesceChanges([
+ { id: "a", change: "created" },
+ { id: "a", change: "updated" },
+ { id: "b", change: "updated" },
+ { id: "c", change: "created" },
+ { id: "c", change: "destroyed" },
+ { id: "d", change: "updated" },
+ { id: "d", change: "destroyed" },
+ { id: "e", change: "destroyed" },
+ { id: "e", change: "created" },
+ ]);
+ assert.deepEqual(result.created, ["a"]);
+ assert.deepEqual(result.updated.sort(), ["b", "e"]);
+ assert.deepEqual(result.destroyed, ["d"]);
+});
+
+test("push previews decrypt with the device key (ECDH + HKDF + AES-GCM)", async () => {
+ const device = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits"]);
+ const publicKey = push.toBase64(new Uint8Array(await crypto.subtle.exportKey("raw", device.publicKey)));
+ assert.equal(push.isValidDevicePublicKey(publicKey), true);
+ assert.equal(push.isValidDevicePublicKey("AAAA"), false);
+
+ const message = JSON.stringify({ from: "[email protected]", subject: "Hello" });
+ const enc = await push.encryptPreview(publicKey, new TextEncoder().encode(message));
+
+ const ephemeral = await crypto.subtle.importKey("raw", push.fromBase64(enc.epk), { name: "ECDH", namedCurve: "P-256" }, false, []);
+ const shared = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeral }, device.privateKey, 256);
+ const hkdf = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
+ const key = await crypto.subtle.deriveKey(
+ { name: "HKDF", hash: "SHA-256", salt: push.fromBase64(enc.salt), info: new TextEncoder().encode(push.PUSH_HKDF_INFO) },
+ hkdf,
+ { name: "AES-GCM", length: 256 },
+ false,
+ ["decrypt"],
+ );
+ const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: push.fromBase64(enc.iv) }, key, push.fromBase64(enc.ct));
+ assert.equal(new TextDecoder().decode(plain), message);
+});
+
+test("APNs provider tokens are verifiable ES256 JWTs", async () => {
+ const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);
+ const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
+ const pem = `-----BEGIN PRIVATE KEY-----\n${push.toBase64(pkcs8)}\n-----END PRIVATE KEY-----`;
+ const jwt = await push.signApnsJwt(await push.importApnsKey(pem), "KEY123", "TEAM456", 1700000000);
+ const [header, claims, signature] = jwt.split(".");
+ assert.deepEqual(JSON.parse(Buffer.from(header, "base64url").toString()), { alg: "ES256", kid: "KEY123" });
+ assert.deepEqual(JSON.parse(Buffer.from(claims, "base64url").toString()), { iss: "TEAM456", iat: 1700000000 });
+ const valid = await crypto.subtle.verify(
+ { name: "ECDSA", hash: "SHA-256" },
+ pair.publicKey,
+ Buffer.from(signature, "base64url"),
+ new TextEncoder().encode(`${header}.${claims}`),
+ );
+ assert.equal(valid, true);
+});
diff --git a/worker.ts b/worker.ts
index 02527c4..e97a05e 100644
--- a/worker.ts
+++ b/worker.ts
@@ -23,6 +23,7 @@ import { runAgentMaintenance } from "./src/lib/agent/maintenance";
import { runTrashRetention } from "./src/lib/email/trash-retention";
import { runDriveTrashRetention } from "./src/lib/drive/retention";
import { runAccountRetention } from "./src/lib/accounts/deletion";
+import { runJmapChangeRetention } from "./src/lib/jmap/changes";
export { RealtimeHub } from "./src/lib/realtime/hub";
export default {
@@ -136,5 +137,6 @@ export default {
if (controller.cron === "0 2 * * *") ctx.waitUntil(runAccountRetention(env, new Date(controller.scheduledTime)));
// Drive trash is emptied once a day, with the 02:00 UTC cron; the 5-minute cron is for queue-like upkeep.
if (controller.cron === "0 2 * * *") ctx.waitUntil(runDriveTrashRetention(env, new Date(controller.scheduledTime)));
+ if (controller.cron === "0 2 * * *") ctx.waitUntil(runJmapChangeRetention(env, new Date(controller.scheduledTime)));
},
} satisfies ExportedHandler<CloudflareEnv>;
diff --git a/wrangler.jsonc b/wrangler.jsonc
index eb903e3..ba96658 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -49,6 +49,11 @@
"period": 60,
},
},
+ {
+ "name": "DEVICE_LOGIN_RATE_LIMIT",
+ "namespace_id": "1003",
+ "simple": { "limit": 10, "period": 60 },
+ },
{
"name": "AGENT_RATE_LIMIT",
"namespace_id": "1002",