Email for professionals and teams
Merge remote-tracking branch 'origin/main' into pr/34
Hieu Nguyen (Jack)3e8a9519b216
diff --cc CLAUDE.mdindex 82f51a2,65cd782..4c6b13a--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -79,10 -79,14 +79,18 @@@ Schema lives in one file: `src/db/schemThe 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`.++ ### Password reset and MFA++ `reset_email` on `users` is the destination for reset links (`src/lib/auth/password-reset.ts`); links are hashed, single-use, 30 minutes, and redeeming one revokes every session. Reset mail is sent by `sendSystemEmail` (`src/lib/email/system-mail.ts`), which writes straight to the send binding from the first admin mailbox on a sending-enabled domain, so nothing lands in Sent and no webhooks fire. If no domain can send, the request still returns 200 and a warning is logged. TOTP lives in `src/lib/auth/totp.ts` (RFC 6238 over Web Crypto, no dependency); the secret is stored on `users` at enrolment but only counts once `totp_enabled` is set by a verified code. A login with MFA returns `{ mfaRequired, challengeToken }` (`login_challenges`, 5 minutes) instead of a session, and `/api/auth/mfa/verify` finishes it with a TOTP or recovery code. Password changes and admin resets call `deleteUserSessions`.++ ### Search is an FTS5 index kept by triggers++ `messages_fts` (migration 0030) is an external-content FTS5 table over `messages`; three triggers in the same migration keep it in sync on insert, update and delete, so no application code touches the index. `buildSearchConditions` in `src/lib/search/conditions.ts` turns the Gmail-style grammar (`src/lib/search/query-utils.ts`) into a `rowid IN (SELECT rowid FROM messages_fts WHERE messages_fts MATCH ?)` predicate plus plain column filters. Two consequences: the bootstrap SQL in `src/lib/setup/migration.ts` is split with `splitSqlStatements`, which keeps trigger bodies whole; and the backup coverage check skips `messages_fts%`, since the shadow tables are derived and repopulate on restore. `wrangler d1 export` does not work on databases with virtual tables; the app's own JSON backup is unaffected.+### Access controlTwo independent auth surfaces:diff --cc docs/api.mdindex 41e1550,8d11337..de71a19--- a/docs/api.md+++ b/docs/api.md@@@ -57,12 -57,28 +57,34 @@@ Messages composed in Mailflare are senThe 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`.++ ## Password reset and two-factor authentication++ `POST /api/auth/password-reset/request` with `{ email }` always answers `200 { ok: true }`; when the account exists and has a recovery email, a single-use link valid for 30 minutes is mailed there. `POST /api/auth/password-reset/confirm` with `{ token, password }` sets the password and signs the account out everywhere.++ When two-factor authentication is on, `POST /api/auth/login` returns `{ ok: true, mfaRequired: true, challengeToken }` instead of a session. `POST /api/auth/mfa/verify` with `{ challengeToken, code }` completes the sign-in; `code` is a 6-digit TOTP or one of the recovery codes. Challenges expire after 5 minutes. Enrolment, recovery codes and turning it off are under `/api/settings/mfa/*` (session auth) and always re-check the password.++ ## Searching++ `GET /api/messages?q=...` (session) and `GET /api/v1/messages?q=...` (API key, `read` scope) accept the same query grammar, backed by an FTS5 index over subject, sender, recipients and body:++ | Syntax | Meaning |+ |---|---|+ | `invoice` | prefix match anywhere (`inv` finds "invoice") |+ | `"private window"` | exact phrase |+ | `-word` | exclude |+ | `from:maya`, `to:sam`, `subject:report` | restrict a term to one field (`to:` covers Cc) |+ | `has:attachment` | at least one non-inline attachment |+ | `is:unread`, `is:read`, `is:starred` | flags |+ | `after:2026-09-01`, `before:2026-09-30` | date bounds (UTC, `before` exclusive) |++ Terms combine with AND. Admins can check or rebuild the index with `GET` / `POST /api/admin/search-index`; triggers keep it current, so a rebuild is only needed after restoring a backup made before the index existed.+## Real-time updatesMailflare 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 --cc src/components/settings/account-settings.tsxindex d4683d6,fdf3ccf..c4460bd--- a/src/components/settings/account-settings.tsx+++ b/src/components/settings/account-settings.tsx@@@ -3,7 -3,7 +3,8 @@@import { useEffect, useState } from "react";import { Skeleton } from "@/components/ui/skeleton";import { ChangePasswordForm } from "./change-password-form";+import { EmailClientsSettings } from "./email-clients-settings";+ import { MfaSettings } from "./mfa-settings";import { ForwardingEmailForm } from "./forwarding-email-form";import { MailboxSignatureForm } from "./mailbox-signature-form";import { ProfileForm } from "./profile-form";@@@ -94,17 -94,14 +95,24 @@@ export function AccountSettings()</div><ChangePasswordForm /></div>+ <div className="space-y-4 rounded-3xl bg-white p-6">+ <div>+ <h3 className="text-lg font-semibold text-neutral-900">Two-factor authentication</h3>+ <p className="mt-1 text-sm text-neutral-500">Require a code from an authenticator app when signing in.</p>+ </div>+ <MfaSettings />+ </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 --cc src/components/settings/utils.tsindex 59909f0,e832669..abb1cb8--- a/src/components/settings/utils.ts+++ b/src/components/settings/utils.ts@@@ -113,14 -119,56 +119,68 @@@ export async function updatePassword(cu}}+/** 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;+}+++ function errorMessage(data: { error?: unknown }, fallback: string): string {+ return typeof data.error === "string" ? data.error : fallback;+ }++ export async function loadMfaStatus(): Promise<MfaStatusResponse> {+ const res = await authFetch("/api/settings/mfa");+ const data = (await res.json()) as MfaStatusResponse;+ if (!res.ok) throw new Error(errorMessage(data, "Failed to load two-factor settings"));+ return data;+ }++ export async function beginMfaEnrollment(password: string): Promise<Required<Pick<MfaEnrollmentResponse, "secret" | "otpauthUrl" | "qrSvg">>> {+ const res = await authFetch("/api/settings/mfa/enroll", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password }),+ });+ const data = (await res.json()) as MfaEnrollmentResponse;+ if (!res.ok || !data.secret || !data.otpauthUrl || !data.qrSvg) throw new Error(errorMessage(data, "Could not start enrolment"));+ return { secret: data.secret, otpauthUrl: data.otpauthUrl, qrSvg: data.qrSvg };+ }++ export async function confirmMfaEnrollment(code: string): Promise<string[]> {+ const res = await authFetch("/api/settings/mfa/confirm", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ code }),+ });+ const data = (await res.json()) as MfaRecoveryCodesResponse;+ if (!res.ok || !data.recoveryCodes) throw new Error(errorMessage(data, "Could not confirm the code"));+ return data.recoveryCodes;+ }++ export async function disableMfa(password: string, code: string): Promise<void> {+ const res = await authFetch("/api/settings/mfa/disable", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password, code }),+ });+ const data = (await res.json()) as { error?: unknown };+ if (!res.ok) throw new Error(errorMessage(data, "Could not turn off two-factor authentication"));+ }++ export async function regenerateRecoveryCodes(password: string): Promise<string[]> {+ const res = await authFetch("/api/settings/mfa/recovery-codes", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password }),+ });+ const data = (await res.json()) as MfaRecoveryCodesResponse;+ if (!res.ok || !data.recoveryCodes) throw new Error(errorMessage(data, "Could not generate new codes"));+ return data.recoveryCodes;+ }