Email for professionals and teams
feat(auth): password reset by recovery email and TOTP two-factor authentication
Oday Bakkour2e3c3e6f0b74
diff --git a/CLAUDE.md b/CLAUDE.mdindex 5a1b6e7..d3fa852 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 gThe setup path only ever initializes an empty database — it refuses to touch one that already has tables.+### 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`.+### Access controlTwo independent auth surfaces:diff --git a/docs/api.md b/docs/api.mdindex eeccbd8..13096b3 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 deThe 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.+## 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.+## 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 --git a/drizzle/migrations/0031_add_password_reset_and_mfa.sql b/drizzle/migrations/0031_add_password_reset_and_mfa.sqlnew file mode 100644index 0000000..15f79d1--- /dev/null+++ b/drizzle/migrations/0031_add_password_reset_and_mfa.sql@@ -0,0 +1,28 @@+-- Password reset links and TOTP two-factor authentication.+ALTER TABLE `users` ADD `totp_secret` text;--> statement-breakpoint+ALTER TABLE `users` ADD `totp_enabled` integer DEFAULT false NOT NULL;--> statement-breakpoint+ALTER TABLE `users` ADD `totp_confirmed_at` integer;--> statement-breakpoint+CREATE TABLE `password_reset_tokens` (+ `id` text PRIMARY KEY NOT NULL,+ `user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade,+ `token_hash` text NOT NULL UNIQUE,+ `expires_at` integer NOT NULL,+ `used_at` integer,+ `created_at` integer NOT NULL+);--> statement-breakpoint+CREATE INDEX `password_reset_tokens_user_idx` ON `password_reset_tokens` (`user_id`);--> statement-breakpoint+CREATE TABLE `mfa_recovery_codes` (+ `id` text PRIMARY KEY NOT NULL,+ `user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade,+ `code_hash` text NOT NULL UNIQUE,+ `used_at` integer,+ `created_at` integer NOT NULL+);--> statement-breakpoint+CREATE INDEX `mfa_recovery_codes_user_idx` ON `mfa_recovery_codes` (`user_id`);--> statement-breakpoint+CREATE TABLE `login_challenges` (+ `id` text PRIMARY KEY NOT NULL,+ `user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade,+ `token_hash` text NOT NULL UNIQUE,+ `expires_at` integer NOT NULL,+ `created_at` integer NOT NULL+);diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.jsonindex 0f60979..4b9cba3 100644--- a/drizzle/migrations/meta/_journal.json+++ b/drizzle/migrations/meta/_journal.json@@ -204,6 +204,20 @@"when": 1788850800000,"tag": "0028_add_keyboard_shortcuts_setting","breakpoints": true+ },+ {+ "idx": 29,+ "version": "6",+ "when": 1788850800001,+ "tag": "0029_add_spam_protection",+ "breakpoints": true+ },+ {+ "idx": 30,+ "version": "6",+ "when": 1788850800002,+ "tag": "0031_add_password_reset_and_mfa",+ "breakpoints": true}]}diff --git a/package-lock.json b/package-lock.jsonindex e1f91f8..4e33cf8 100644--- a/package-lock.json+++ b/package-lock.json@@ -29,6 +29,7 @@"nanoid": "^5.1.16","next": "16.3.3","postal-mime": "^2.7.4",+ "qrcode": "^1.5.4","react": "^19.1.7","react-dom": "^19.1.7","tailwind-merge": "^3.6.0",@@ -40,6 +41,7 @@"@tailwindcss/postcss": "^4","@types/bcryptjs": "^2.4.6","@types/node": "^20.19.41",+ "@types/qrcode": "^1.5.6","@types/react": "^19.1.7","@types/react-dom": "^19.1.7","drizzle-kit": "^0.31.10",@@ -4801,6 +4803,16 @@"form-data": "^4.0.4"}},+ "node_modules/@types/qrcode": {+ "version": "1.5.6",+ "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz",+ "integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@types/react": {"version": "19.2.15","devOptional": true,@@ -5917,6 +5929,15 @@"node": ">=6"}},+ "node_modules/camelcase": {+ "version": "5.3.1",+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",+ "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/caniuse-lite": {"version": "1.0.30001810","funding": [@@ -6040,7 +6061,6 @@},"node_modules/color-convert": {"version": "2.0.1",- "dev": true,"license": "MIT","dependencies": {"color-name": "~1.1.4"@@ -6051,7 +6071,6 @@},"node_modules/color-name": {"version": "1.1.4",- "dev": true,"license": "MIT"},"node_modules/combined-stream": {@@ -6243,6 +6262,15 @@}}},+ "node_modules/decamelize": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",+ "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/deep-is": {"version": "0.1.4","dev": true,@@ -6305,6 +6333,12 @@"version": "1.1.0","license": "MIT"},+ "node_modules/dijkstrajs": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",+ "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",+ "license": "MIT"+ },"node_modules/doctrine": {"version": "2.1.0","dev": true,@@ -8155,6 +8189,15 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/is-fullwidth-code-point": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/is-generator-function": {"version": "1.1.2","dev": true,@@ -10009,6 +10052,15 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/p-try": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",+ "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/package-json-from-dist": {"version": "1.0.1","license": "BlueOak-1.0.0"@@ -10033,7 +10085,6 @@},"node_modules/path-exists": {"version": "4.0.0",- "dev": true,"license": "MIT","engines": {"node": ">=8"@@ -10107,6 +10158,15 @@"url": "https://github.com/sponsors/jonschlinkert"}},+ "node_modules/pngjs": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",+ "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",+ "license": "MIT",+ "engines": {+ "node": ">=10.13.0"+ }+ },"node_modules/possible-typed-array-names": {"version": "1.1.0","dev": true,@@ -10198,6 +10258,176 @@"node": ">=6"}},+ "node_modules/qrcode": {+ "version": "1.5.4",+ "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",+ "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",+ "license": "MIT",+ "dependencies": {+ "dijkstrajs": "^1.0.1",+ "pngjs": "^5.0.0",+ "yargs": "^15.3.1"+ },+ "bin": {+ "qrcode": "bin/qrcode"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/qrcode/node_modules/ansi-styles": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",+ "license": "MIT",+ "dependencies": {+ "color-convert": "^2.0.1"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/qrcode/node_modules/cliui": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",+ "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^4.2.0",+ "strip-ansi": "^6.0.0",+ "wrap-ansi": "^6.2.0"+ }+ },+ "node_modules/qrcode/node_modules/emoji-regex": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",+ "license": "MIT"+ },+ "node_modules/qrcode/node_modules/find-up": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",+ "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",+ "license": "MIT",+ "dependencies": {+ "locate-path": "^5.0.0",+ "path-exists": "^4.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/qrcode/node_modules/locate-path": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",+ "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",+ "license": "MIT",+ "dependencies": {+ "p-locate": "^4.1.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/qrcode/node_modules/p-limit": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",+ "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",+ "license": "MIT",+ "dependencies": {+ "p-try": "^2.0.0"+ },+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/qrcode/node_modules/p-locate": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",+ "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",+ "license": "MIT",+ "dependencies": {+ "p-limit": "^2.2.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/qrcode/node_modules/string-width": {+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^8.0.0",+ "is-fullwidth-code-point": "^3.0.0",+ "strip-ansi": "^6.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/qrcode/node_modules/wrap-ansi": {+ "version": "6.2.0",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",+ "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^4.0.0",+ "string-width": "^4.1.0",+ "strip-ansi": "^6.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/qrcode/node_modules/y18n": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",+ "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",+ "license": "ISC"+ },+ "node_modules/qrcode/node_modules/yargs": {+ "version": "15.4.1",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",+ "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^6.0.0",+ "decamelize": "^1.2.0",+ "find-up": "^4.1.0",+ "get-caller-file": "^2.0.1",+ "require-directory": "^2.1.1",+ "require-main-filename": "^2.0.0",+ "set-blocking": "^2.0.0",+ "string-width": "^4.2.0",+ "which-module": "^2.0.0",+ "y18n": "^4.0.0",+ "yargs-parser": "^18.1.2"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/qrcode/node_modules/yargs-parser": {+ "version": "18.1.3",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",+ "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",+ "license": "ISC",+ "dependencies": {+ "camelcase": "^5.0.0",+ "decamelize": "^1.2.0"+ },+ "engines": {+ "node": ">=6"+ }+ },"node_modules/qs": {"version": "6.15.2","license": "BSD-3-Clause",@@ -10375,6 +10605,21 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/require-directory": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/require-main-filename": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",+ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",+ "license": "ISC"+ },"node_modules/resolve": {"version": "2.0.0-next.7","dev": true,@@ -10572,6 +10817,12 @@"url": "https://opencollective.com/express"}},+ "node_modules/set-blocking": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",+ "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",+ "license": "ISC"+ },"node_modules/set-function-length": {"version": "1.2.2","dev": true,@@ -12036,6 +12287,12 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/which-module": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",+ "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",+ "license": "ISC"+ },"node_modules/which-typed-array": {"version": "1.1.20","dev": true,diff --git a/package.json b/package.jsonindex e70ff4c..375a0d9 100644--- a/package.json+++ b/package.json@@ -74,6 +74,7 @@"nanoid": "^5.1.16","next": "16.3.3","postal-mime": "^2.7.4",+ "qrcode": "^1.5.4","react": "^19.1.7","react-dom": "^19.1.7","tailwind-merge": "^3.6.0",@@ -85,6 +86,7 @@"@tailwindcss/postcss": "^4","@types/bcryptjs": "^2.4.6","@types/node": "^20.19.41",+ "@types/qrcode": "^1.5.6","@types/react": "^19.1.7","@types/react-dom": "^19.1.7","drizzle-kit": "^0.31.10",diff --git a/src/app/(admin)/accounts/[id]/page.tsx b/src/app/(admin)/accounts/[id]/page.tsxindex b53ae1a..375618b 100644--- a/src/app/(admin)/accounts/[id]/page.tsx+++ b/src/app/(admin)/accounts/[id]/page.tsx@@ -33,7 +33,8 @@ export default function AccountDetailsPage() {setMessage(null);try {await saveManagedAccount(account);- setMessage("Account details updated");+ setAccount({ ...account, newPassword: "" });+ setMessage(account.newPassword ? "Account details updated and password reset" : "Account details updated");} catch (error) {setMessage(error instanceof Error ? error.message : "Unable to update account");} finally {@@ -97,6 +98,21 @@ export default function AccountDetailsPage() {Incoming mail will also be sent to this verified Cloudflare Email Routing destination.</p></div>}+ <div className="space-y-2">+ <Label htmlFor="account-new-password">Reset password (optional)</Label>+ <Input+ id="account-new-password"+ type="password"+ autoComplete="new-password"+ minLength={8}+ value={account.newPassword ?? ""}+ onChange={(event) => setAccount({ ...account, newPassword: event.target.value })}+ placeholder="Leave blank to keep the current password"+ />+ <p className="text-xs leading-5 text-neutral-500">+ Setting a password signs this account out everywhere. Share it with the user through another channel.+ </p>+ </div><label className="flex items-center gap-3 text-sm"><Checkbox checked={!account.disabled} onChange={(event) => setAccount({ ...account, disabled: !event.target.checked })} />Account enableddiff --git a/src/app/(admin)/accounts/[id]/types.d.ts b/src/app/(admin)/accounts/[id]/types.d.tsindex bf00d0a..78b42dc 100644--- a/src/app/(admin)/accounts/[id]/types.d.ts+++ b/src/app/(admin)/accounts/[id]/types.d.ts@@ -8,6 +8,8 @@ export type ManagedAccount = {forwardingEmail: string | null;canForwardEmail: boolean;hasAvatar: boolean;+ /** Only ever set client-side when an admin types a new password; never returned by the API. */+ newPassword?: string;};export type ManagedMailbox = {diff --git a/src/app/(admin)/accounts/[id]/utils.ts b/src/app/(admin)/accounts/[id]/utils.tsindex 9ac0f8f..2ff3752 100644--- a/src/app/(admin)/accounts/[id]/utils.ts+++ b/src/app/(admin)/accounts/[id]/utils.ts@@ -119,6 +119,7 @@ export async function saveManagedAccount(account: ManagedAccount): Promise<void>disabled: account.disabled,canManageMailboxes: account.canManageMailboxes,forwardingEmail: account.forwardingEmail,+ password: account.newPassword || undefined,}),});const data = (await response.json()) as { error?: string };diff --git a/src/app/(auth)/forgot-password/forgot-password-client.tsx b/src/app/(auth)/forgot-password/forgot-password-client.tsxnew file mode 100644index 0000000..33eb38b--- /dev/null+++ b/src/app/(auth)/forgot-password/forgot-password-client.tsx@@ -0,0 +1,71 @@+"use client";++import Link from "next/link";+import { useState } from "react";+import { KeyRound } from "lucide-react";+import { AuthShell } from "@/components/auth/auth-shell";+import { TurnstileField } from "@/components/auth/turnstile";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { requestPasswordReset } from "./utils";++export function ForgotPasswordClient() {+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(false);+ const [sent, setSent] = useState(false);+ const [turnstileReset, setTurnstileReset] = useState(0);++ async function onSubmit(event: React.FormEvent<HTMLFormElement>) {+ event.preventDefault();+ setLoading(true);+ setError(null);+ try {+ const result = await requestPasswordReset(new FormData(event.currentTarget));+ if (!result.ok) {+ setError(result.error ?? "Something went wrong. Please try again.");+ setTurnstileReset((value) => value + 1);+ return;+ }+ setSent(true);+ } catch {+ setError("Unable to reach the server. Please try again.");+ setTurnstileReset((value) => value + 1);+ } finally {+ setLoading(false);+ }+ }++ return (+ <AuthShell+ icon={KeyRound}+ title="Reset your password"+ description={+ sent+ ? "If that account has a recovery email, a reset link is on its way. It works for 30 minutes."+ : "Enter the address you sign in with. We will send a reset link to the recovery email on the account."+ }+ footer={+ <Link href="/login" className="text-sm text-neutral-500 hover:text-neutral-800">+ Back to sign in+ </Link>+ }+ >+ {!sent && (+ <form onSubmit={onSubmit} className="space-y-5">+ <div className="space-y-2">+ <Label htmlFor="email">Email</Label>+ <Input id="email" name="email" type="email" autoComplete="email" required autoFocus />+ </div>+ {error && (+ <p className="rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700">{error}</p>+ )}+ <TurnstileField resetSignal={turnstileReset} />+ <Button type="submit" className="h-11 w-full rounded-full px-6 active:scale-[0.98]" disabled={loading}>+ {loading ? "Sending..." : "Send reset link"}+ </Button>+ </form>+ )}+ </AuthShell>+ );+}diff --git a/src/app/(auth)/forgot-password/page.tsx b/src/app/(auth)/forgot-password/page.tsxnew file mode 100644index 0000000..96d2e28--- /dev/null+++ b/src/app/(auth)/forgot-password/page.tsx@@ -0,0 +1,12 @@+import { AuthGuard } from "@/components/auth/auth-guard";+import { ForgotPasswordClient } from "./forgot-password-client";++export const dynamic = "force-dynamic";++export default function ForgotPasswordPage() {+ return (+ <AuthGuard mode="public">+ <ForgotPasswordClient />+ </AuthGuard>+ );+}diff --git a/src/app/(auth)/forgot-password/utils.ts b/src/app/(auth)/forgot-password/utils.tsnew file mode 100644index 0000000..f2f5f71--- /dev/null+++ b/src/app/(auth)/forgot-password/utils.ts@@ -0,0 +1,10 @@+export async function requestPasswordReset(form: FormData): Promise<{ ok: boolean; error?: string }> {+ const res = await fetch("/api/auth/password-reset/request", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ signal: AbortSignal.timeout(20_000),+ body: JSON.stringify({ email: form.get("email"), turnstileToken: form.get("turnstileToken") }),+ });+ const data = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string };+ return { ok: res.ok, error: typeof data.error === "string" ? data.error : undefined };+}diff --git a/src/app/(auth)/login/login-client.tsx b/src/app/(auth)/login/login-client.tsxindex 05a922f..36fcd83 100644--- a/src/app/(auth)/login/login-client.tsx+++ b/src/app/(auth)/login/login-client.tsx@@ -1,20 +1,29 @@"use client";+import Link from "next/link";import { useRouter } from "next/navigation";import { useState } from "react";-import { Mail } from "lucide-react";+import { Mail, ShieldCheck } from "lucide-react";import { AuthShell } from "@/components/auth/auth-shell";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { TurnstileField } from "@/components/auth/turnstile";-import { submitLogin } from "./utils";+import { submitLogin, submitMfaCode } from "./utils";export function LoginClient() {const router = useRouter();const [error, setError] = useState<string | null>(null);const [loading, setLoading] = useState(false);const [turnstileReset, setTurnstileReset] = useState(0);+ // Set once the password is accepted for an account with a second factor.+ const [challengeToken, setChallengeToken] = useState<string | null>(null);+ const [code, setCode] = useState("");++ function finish(redirect?: string) {+ router.replace(redirect ?? "/inbox");+ router.refresh();+ }async function onSubmit(e: React.FormEvent<HTMLFormElement>) {e.preventDefault();@@ -28,8 +37,11 @@ export function LoginClient() {setTurnstileReset((value) => value + 1);return;}- router.replace(data.redirect ?? "/inbox");- router.refresh();+ if (data.mfaRequired && data.challengeToken) {+ setChallengeToken(data.challengeToken);+ return;+ }+ finish(data.redirect);} catch (error) {setError(error instanceof DOMException && error.name === "TimeoutError"@@ -42,6 +54,76 @@ export function LoginClient() {}}+ async function onSubmitCode(e: React.FormEvent<HTMLFormElement>) {+ e.preventDefault();+ if (!challengeToken) return;+ setLoading(true);+ setError(null);+ try {+ const { ok, data } = await submitMfaCode(challengeToken, code);+ if (!ok) {+ setError(data.error ?? "That code did not match");+ // An expired challenge sends the user back to the password step.+ if (data.error?.includes("expired")) {+ setChallengeToken(null);+ setCode("");+ }+ return;+ }+ finish(data.redirect);+ } catch {+ setError("Unable to reach the login service. Please try again.");+ } finally {+ setLoading(false);+ }+ }++ if (challengeToken) {+ return (+ <AuthShell+ icon={ShieldCheck}+ title="Two-factor authentication"+ description="Enter the 6-digit code from your authenticator app, or one of your recovery codes."+ >+ <form onSubmit={onSubmitCode} className="space-y-5">+ <div className="space-y-2">+ <Label htmlFor="code">Code</Label>+ <Input+ id="code"+ name="code"+ value={code}+ onChange={(event) => setCode(event.target.value)}+ inputMode="numeric"+ autoComplete="one-time-code"+ autoFocus+ placeholder="123 456"+ required+ />+ </div>+ {error && (+ <p className="rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700">+ {error}+ </p>+ )}+ <Button type="submit" className="h-11 w-full rounded-full px-6 active:scale-[0.98]" disabled={loading}>+ {loading ? "Verifying..." : "Verify"}+ </Button>+ <button+ type="button"+ className="w-full text-center text-sm text-neutral-500 hover:text-neutral-800"+ onClick={() => {+ setChallengeToken(null);+ setCode("");+ setError(null);+ }}+ >+ Back to sign in+ </button>+ </form>+ </AuthShell>+ );+ }+return (<AuthShellicon={Mail}@@ -60,7 +142,12 @@ export function LoginClient() {/></div><div className="space-y-2">- <Label htmlFor="password">Password</Label>+ <div className="flex items-center justify-between">+ <Label htmlFor="password">Password</Label>+ <Link href="/forgot-password" className="text-xs font-medium text-blue-600 hover:underline">+ Forgot password?+ </Link>+ </div><Inputid="password"name="password"diff --git a/src/app/(auth)/login/types.d.ts b/src/app/(auth)/login/types.d.tsindex b0f1b7b..28a041e 100644--- a/src/app/(auth)/login/types.d.ts+++ b/src/app/(auth)/login/types.d.ts@@ -2,4 +2,7 @@ export type LoginResult = {token?: string;redirect?: string;error?: string;+ /** Password accepted; a code from the authenticator is still needed. */+ mfaRequired?: boolean;+ challengeToken?: string;};diff --git a/src/app/(auth)/login/utils.ts b/src/app/(auth)/login/utils.tsindex 848ccc1..1f75df2 100644--- a/src/app/(auth)/login/utils.ts+++ b/src/app/(auth)/login/utils.ts@@ -18,3 +18,14 @@ export async function submitLogin(form: FormData): Promise<{ ok: boolean; data:data: (await persistAuthSession(res)) as LoginResult,};}++/** Second step: the challenge from the password step plus a TOTP or recovery code. */+export async function submitMfaCode(challengeToken: string, code: string): Promise<{ ok: boolean; data: LoginResult }> {+ const res = await fetch("/api/auth/mfa/verify", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ signal: AbortSignal.timeout(20_000),+ body: JSON.stringify({ challengeToken, code }),+ });+ return { ok: res.ok, data: (await persistAuthSession(res)) as LoginResult };+}diff --git a/src/app/(auth)/reset-password/page.tsx b/src/app/(auth)/reset-password/page.tsxnew file mode 100644index 0000000..630ab45--- /dev/null+++ b/src/app/(auth)/reset-password/page.tsx@@ -0,0 +1,15 @@+import { Suspense } from "react";+import { AuthGuard } from "@/components/auth/auth-guard";+import { ResetPasswordClient } from "./reset-password-client";++export const dynamic = "force-dynamic";++export default function ResetPasswordPage() {+ return (+ <AuthGuard mode="public">+ <Suspense>+ <ResetPasswordClient />+ </Suspense>+ </AuthGuard>+ );+}diff --git a/src/app/(auth)/reset-password/reset-password-client.tsx b/src/app/(auth)/reset-password/reset-password-client.tsxnew file mode 100644index 0000000..31378d3--- /dev/null+++ b/src/app/(auth)/reset-password/reset-password-client.tsx@@ -0,0 +1,107 @@+"use client";++import Link from "next/link";+import { useSearchParams } from "next/navigation";+import { useState } from "react";+import { LockKeyhole } from "lucide-react";+import { AuthShell } from "@/components/auth/auth-shell";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { confirmPasswordReset } from "./utils";++export function ResetPasswordClient() {+ const token = useSearchParams().get("token") ?? "";+ const [password, setPassword] = useState("");+ const [confirm, setConfirm] = useState("");+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(false);+ const [done, setDone] = useState(false);++ async function onSubmit(event: React.FormEvent<HTMLFormElement>) {+ event.preventDefault();+ if (password !== confirm) {+ setError("Passwords do not match");+ return;+ }+ setLoading(true);+ setError(null);+ try {+ const result = await confirmPasswordReset(token, password);+ if (!result.ok) {+ setError(result.error ?? "Could not reset the password");+ return;+ }+ setDone(true);+ } catch {+ setError("Unable to reach the server. Please try again.");+ } finally {+ setLoading(false);+ }+ }++ if (!token) {+ return (+ <AuthShell icon={LockKeyhole} title="Reset link missing" description="Open the link from the reset email to choose a new password.">+ <Link href="/forgot-password" className="text-sm text-blue-600 hover:underline">+ Request a new link+ </Link>+ </AuthShell>+ );+ }++ return (+ <AuthShell+ icon={LockKeyhole}+ title={done ? "Password updated" : "Choose a new password"}+ description={+ done+ ? "You have been signed out everywhere. Sign in with your new password to continue."+ : "Use at least 8 characters. Every other session for this account will be signed out."+ }+ footer={+ done ? (+ <Link href="/login" className="text-sm font-medium text-blue-600 hover:underline">+ Go to sign in+ </Link>+ ) : undefined+ }+ >+ {!done && (+ <form onSubmit={onSubmit} className="space-y-5">+ <div className="space-y-2">+ <Label htmlFor="password">New password</Label>+ <Input+ id="password"+ type="password"+ autoComplete="new-password"+ value={password}+ onChange={(event) => setPassword(event.target.value)}+ minLength={8}+ required+ autoFocus+ />+ </div>+ <div className="space-y-2">+ <Label htmlFor="confirm">Confirm new password</Label>+ <Input+ id="confirm"+ type="password"+ autoComplete="new-password"+ value={confirm}+ onChange={(event) => setConfirm(event.target.value)}+ minLength={8}+ required+ />+ </div>+ {error && (+ <p className="rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700">{error}</p>+ )}+ <Button type="submit" className="h-11 w-full rounded-full px-6 active:scale-[0.98]" disabled={loading}>+ {loading ? "Saving..." : "Set new password"}+ </Button>+ </form>+ )}+ </AuthShell>+ );+}diff --git a/src/app/(auth)/reset-password/utils.ts b/src/app/(auth)/reset-password/utils.tsnew file mode 100644index 0000000..7f9f934--- /dev/null+++ b/src/app/(auth)/reset-password/utils.ts@@ -0,0 +1,10 @@+export async function confirmPasswordReset(token: string, password: string): Promise<{ ok: boolean; error?: string }> {+ const res = await fetch("/api/auth/password-reset/confirm", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ signal: AbortSignal.timeout(20_000),+ body: JSON.stringify({ token, password }),+ });+ const data = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string };+ return { ok: res.ok, error: typeof data.error === "string" ? data.error : undefined };+}diff --git a/src/app/api/accounts/[id]/route.ts b/src/app/api/accounts/[id]/route.tsindex fd2c311..25ded44 100644--- a/src/app/api/accounts/[id]/route.ts+++ b/src/app/api/accounts/[id]/route.ts@@ -7,6 +7,7 @@ import { requireTeamAdmin } from "../utils";import { getLicenseEntitlements } from "@/lib/licenses/service";import type { AccountRouteParams } from "./types";import { selectAccountById, updateAccountCredentials } from "./utils";+import { deleteUserSessions } from "@/lib/auth/session";export async function GET(request: Request, { params }: AccountRouteParams) {const access = await requireTeamAdmin(request);@@ -46,7 +47,9 @@ export async function PATCH(request: Request, { params }: AccountRouteParams) {if (!canForwardEmail && parsed.data.forwardingEmail && parsed.data.forwardingEmail !== account.forwardingEmail) {return NextResponse.json({ error: "A Pro or Team license is required for email forwarding" }, { status: 403 });}- await updateAccountCredentials(db, id, { name: parsed.data.name, password: null });+ await updateAccountCredentials(db, id, { name: parsed.data.name, password: parsed.data.password ?? null });+ // A password set by an admin is a reset: whoever held the old one is signed out.+ if (parsed.data.password) await deleteUserSessions(access.env, id);await db.update(users).set({role: parsed.data.role,disabled: parsed.data.disabled,diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.tsindex a5faf50..51661f1 100644--- a/src/app/api/auth/login/route.ts+++ b/src/app/api/auth/login/route.ts@@ -11,6 +11,7 @@ import { verifyTurnstileToken } from "@/lib/auth/turnstile";import { readJsonBody } from "@/lib/http/request";import { RequestBodyTooLargeError } from "@/lib/http/errors";import { recordAuthActivity } from "@/lib/auth/activity";+import { createLoginChallenge } from "@/lib/auth/login-challenge";export async function POST(request: Request) {const env = getEnv();@@ -44,6 +45,15 @@ export async function POST(request: Request) {return NextResponse.json({ error: "Account disabled" }, { status: 403 });}+ // The password is right but a second factor is on: hand back a short-lived+ // challenge instead of a session and let /api/auth/mfa/verify finish.+ if (user.totpEnabled && user.totpSecret) {+ const challengeToken = await createLoginChallenge(env, user.id);+ const pending = NextResponse.json({ ok: true, mfaRequired: true, challengeToken });+ pending.headers.set("Cache-Control", "no-store");+ return pending;+ }+const token = await createSession(env, user.id);await recordAuthActivity(env, { action: "auth.login", userId: user.id, request });const response = NextResponse.json({diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.tsindex 6e68ac8..88ec37c 100644--- a/src/app/api/auth/me/route.ts+++ b/src/app/api/auth/me/route.ts@@ -35,6 +35,7 @@ export async function GET(request: Request) {keyboardShortcutsEnabled: user.keyboardShortcutsEnabled,spamProtectionEnabled: user.spamProtectionEnabled,hasAvatar: !!user.avatarKey,+ mfaEnabled: user.totpEnabled,},hasMailboxes,isSetup,diff --git a/src/app/api/auth/mfa/verify/route.ts b/src/app/api/auth/mfa/verify/route.tsnew file mode 100644index 0000000..959baa8--- /dev/null+++ b/src/app/api/auth/mfa/verify/route.ts@@ -0,0 +1,62 @@+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 { createSession, SESSION_COOKIE } from "@/lib/auth/session";+import { mfaVerifySchema } from "@/lib/validators";+import { allowLoginAttempt } 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, getLoginChallengeUserId } from "@/lib/auth/login-challenge";+import { verifySecondFactor } from "@/lib/auth/mfa";++/** Second step of a login: trade a challenge plus a TOTP or recovery code for a session. */+export async function POST(request: Request) {+ const env = getEnv();+ let body: unknown;+ try {+ body = await readJsonBody(request, 16 * 1024);+ } catch (error) {+ const status = error instanceof RequestBodyTooLargeError ? 413 : 400;+ return NextResponse.json({ error: "Invalid request" }, { status });+ }+ const parsed = mfaVerifySchema.safeParse(body);+ if (!parsed.success) {+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });+ }+ // Codes are six digits; the login limiter is what stops brute force.+ if (!(await allowLoginAttempt(env, request))) {+ return NextResponse.json({ error: "Too many attempts. Try again shortly." }, { status: 429, headers: { "Retry-After": "60" } });+ }++ const userId = await getLoginChallengeUserId(env, parsed.data.challengeToken);+ if (!userId) {+ return NextResponse.json({ error: "This sign-in attempt has expired. Start again." }, { status: 401 });+ }+ const db = getDb(env);+ const [user] = await db.select().from(users).where(eq(users.id, userId)).limit(1);+ if (!user || user.disabled) {+ return NextResponse.json({ error: "Account disabled" }, { status: 403 });+ }+ const method = await verifySecondFactor(env, user, parsed.data.code);+ if (!method) {+ return NextResponse.json({ error: "That code did not match" }, { status: 401 });+ }++ await consumeLoginChallenge(env, parsed.data.challengeToken);+ const token = await createSession(env, user.id);+ await recordAuthActivity(env, { action: "auth.login", userId: user.id, request });+ await recordAuthActivity(env, { action: "auth.mfa_verified", userId: user.id, request });+ const response = NextResponse.json({ ok: true, token, redirect: "/inbox", method });+ response.headers.set("Cache-Control", "no-store");+ response.cookies.set(SESSION_COOKIE, token, {+ httpOnly: true,+ secure: process.env.NODE_ENV === "production",+ sameSite: "lax",+ path: "/",+ maxAge: 60 * 60 * 24 * 30,+ });+ return response;+}diff --git a/src/app/api/auth/password-reset/confirm/route.ts b/src/app/api/auth/password-reset/confirm/route.tsnew file mode 100644index 0000000..6501ca8--- /dev/null+++ b/src/app/api/auth/password-reset/confirm/route.ts@@ -0,0 +1,29 @@+import { NextResponse } from "next/server";+import { getEnv } from "@/lib/cloudflare";+import { passwordResetConfirmSchema } from "@/lib/validators";+import { allowLoginAttempt } from "@/lib/auth/rate-limit";+import { readJsonBody } from "@/lib/http/request";+import { RequestBodyTooLargeError } from "@/lib/http/errors";+import { completePasswordReset } from "@/lib/auth/password-reset";++export async function POST(request: Request) {+ const env = getEnv();+ let body: unknown;+ try {+ body = await readJsonBody(request, 16 * 1024);+ } catch (error) {+ const status = error instanceof RequestBodyTooLargeError ? 413 : 400;+ return NextResponse.json({ error: "Invalid request" }, { status });+ }+ const parsed = passwordResetConfirmSchema.safeParse(body);+ if (!parsed.success) {+ return NextResponse.json({ error: "Choose a password of at least 8 characters" }, { status: 400 });+ }+ if (!(await allowLoginAttempt(env, request))) {+ return NextResponse.json({ error: "Too many attempts. Try again shortly." }, { status: 429, headers: { "Retry-After": "60" } });+ }++ const result = await completePasswordReset(env, parsed.data.token, parsed.data.password, request);+ if (!result.ok) return NextResponse.json({ error: result.error }, { status: 400 });+ return NextResponse.json({ ok: true }, { headers: { "Cache-Control": "no-store" } });+}diff --git a/src/app/api/auth/password-reset/request/route.ts b/src/app/api/auth/password-reset/request/route.tsnew file mode 100644index 0000000..d693292--- /dev/null+++ b/src/app/api/auth/password-reset/request/route.ts@@ -0,0 +1,42 @@+import { NextResponse } from "next/server";+import { getEnv } from "@/lib/cloudflare";+import { passwordResetRequestSchema } from "@/lib/validators";+import { allowLoginAttempt } from "@/lib/auth/rate-limit";+import { verifyTurnstileToken } from "@/lib/auth/turnstile";+import { readJsonBody } from "@/lib/http/request";+import { RequestBodyTooLargeError } from "@/lib/http/errors";+import { requestPasswordReset } from "@/lib/auth/password-reset";++/**+ * Always answers 200 once the input is well-formed, whether or not the+ * account exists or has a recovery address, so the form reveals nothing.+ */+export async function POST(request: Request) {+ const env = getEnv();+ let body: unknown;+ try {+ body = await readJsonBody(request, 16 * 1024);+ } catch (error) {+ const status = error instanceof RequestBodyTooLargeError ? 413 : 400;+ return NextResponse.json({ error: "Invalid request" }, { status });+ }+ const parsed = passwordResetRequestSchema.safeParse(body);+ if (!parsed.success) {+ return NextResponse.json({ error: "Enter the email address you sign in with" }, { status: 400 });+ }+ if (!(await allowLoginAttempt(env, request))) {+ return NextResponse.json({ error: "Too many attempts. Try again shortly." }, { status: 429, headers: { "Retry-After": "60" } });+ }+ if (!(await verifyTurnstileToken(env, request, (body as Record<string, unknown>).turnstileToken))) {+ return NextResponse.json({ error: "Verification failed. Please try again." }, { status: 400 });+ }++ const origin = new URL(request.url).origin;+ try {+ await requestPasswordReset(env, parsed.data.email, origin);+ } catch (error) {+ // Delivery problems are logged, never surfaced: the answer stays uniform.+ console.error("Password reset request failed", error);+ }+ return NextResponse.json({ ok: true }, { headers: { "Cache-Control": "no-store" } });+}diff --git a/src/app/api/settings/mfa/confirm/route.ts b/src/app/api/settings/mfa/confirm/route.tsnew file mode 100644index 0000000..2d84c25--- /dev/null+++ b/src/app/api/settings/mfa/confirm/route.ts@@ -0,0 +1,19 @@+import { NextResponse } from "next/server";+import { getEnv } from "@/lib/cloudflare";+import { requireSessionUser } from "@/lib/api/auth";+import { readJsonBody } from "@/lib/http/request";+import { getSessionTokenFromRequestHeaders } from "@/lib/auth/session";+import { confirmMfaEnrollment } from "@/lib/auth/mfa";+import { mfaConfirmSchema } from "@/lib/validators";++/** Proves the authenticator has the secret; turns MFA on and returns recovery codes once. */+export async function POST(request: Request) {+ const env = getEnv();+ const auth = await requireSessionUser(env, request);+ if (auth.error) return auth.error;+ const parsed = mfaConfirmSchema.safeParse(await readJsonBody(request, 16 * 1024).catch(() => null));+ if (!parsed.success) return NextResponse.json({ error: "Enter the 6-digit code" }, { status: 400 });+ const result = await confirmMfaEnrollment(env, auth.user, parsed.data.code, getSessionTokenFromRequestHeaders(request));+ if (!result.ok) return NextResponse.json({ error: result.error }, { status: 400 });+ return NextResponse.json({ ok: true, recoveryCodes: result.recoveryCodes }, { headers: { "Cache-Control": "no-store" } });+}diff --git a/src/app/api/settings/mfa/disable/route.ts b/src/app/api/settings/mfa/disable/route.tsnew file mode 100644index 0000000..dbf3909--- /dev/null+++ b/src/app/api/settings/mfa/disable/route.ts@@ -0,0 +1,24 @@+import { NextResponse } from "next/server";+import { getEnv } from "@/lib/cloudflare";+import { requireSessionUser } from "@/lib/api/auth";+import { readJsonBody } from "@/lib/http/request";+import { verifyPassword } from "@/lib/auth/password";+import { disableMfa, verifySecondFactor } from "@/lib/auth/mfa";+import { mfaDisableSchema } from "@/lib/validators";++/** Turning MFA off needs both factors, so a stolen session alone cannot do it. */+export async function POST(request: Request) {+ const env = getEnv();+ const auth = await requireSessionUser(env, request);+ if (auth.error) return auth.error;+ const parsed = mfaDisableSchema.safeParse(await readJsonBody(request, 16 * 1024).catch(() => null));+ if (!parsed.success) return NextResponse.json({ error: "Enter your password and a code" }, { status: 400 });+ if (!verifyPassword(parsed.data.password, auth.user.passwordHash)) {+ return NextResponse.json({ error: "Password is incorrect" }, { status: 400 });+ }+ if (!(await verifySecondFactor(env, auth.user, parsed.data.code))) {+ return NextResponse.json({ error: "That code did not match" }, { status: 400 });+ }+ await disableMfa(env, auth.user.id);+ return NextResponse.json({ ok: true });+}diff --git a/src/app/api/settings/mfa/enroll/route.ts b/src/app/api/settings/mfa/enroll/route.tsnew file mode 100644index 0000000..cde8f92--- /dev/null+++ b/src/app/api/settings/mfa/enroll/route.ts@@ -0,0 +1,23 @@+import { NextResponse } from "next/server";+import { getEnv } from "@/lib/cloudflare";+import { requireSessionUser } from "@/lib/api/auth";+import { readJsonBody } from "@/lib/http/request";+import { verifyPassword } from "@/lib/auth/password";+import { beginMfaEnrollment } from "@/lib/auth/mfa";+import { mfaEnrollSchema } from "@/lib/validators";++/** Re-checks the password, then returns a new secret with its QR code. */+export async function POST(request: Request) {+ const env = getEnv();+ const auth = await requireSessionUser(env, request);+ if (auth.error) return auth.error;+ const parsed = mfaEnrollSchema.safeParse(await readJsonBody(request, 16 * 1024).catch(() => null));+ if (!parsed.success) return NextResponse.json({ error: "Enter your password" }, { status: 400 });+ if (!verifyPassword(parsed.data.password, auth.user.passwordHash)) {+ return NextResponse.json({ error: "Password is incorrect" }, { status: 400 });+ }+ if (auth.user.totpEnabled) {+ return NextResponse.json({ error: "Two-factor authentication is already on" }, { status: 400 });+ }+ return NextResponse.json(await beginMfaEnrollment(env, auth.user), { headers: { "Cache-Control": "no-store" } });+}diff --git a/src/app/api/settings/mfa/recovery-codes/route.ts b/src/app/api/settings/mfa/recovery-codes/route.tsnew file mode 100644index 0000000..571526d--- /dev/null+++ b/src/app/api/settings/mfa/recovery-codes/route.ts@@ -0,0 +1,23 @@+import { NextResponse } from "next/server";+import { getEnv } from "@/lib/cloudflare";+import { requireSessionUser } from "@/lib/api/auth";+import { readJsonBody } from "@/lib/http/request";+import { verifyPassword } from "@/lib/auth/password";+import { issueRecoveryCodes } from "@/lib/auth/recovery-codes";+import { mfaEnrollSchema } from "@/lib/validators";++/** Replace the recovery codes; the old ones stop working immediately. */+export async function POST(request: Request) {+ const env = getEnv();+ const auth = await requireSessionUser(env, request);+ if (auth.error) return auth.error;+ const parsed = mfaEnrollSchema.safeParse(await readJsonBody(request, 16 * 1024).catch(() => null));+ if (!parsed.success) return NextResponse.json({ error: "Enter your password" }, { status: 400 });+ if (!verifyPassword(parsed.data.password, auth.user.passwordHash)) {+ return NextResponse.json({ error: "Password is incorrect" }, { status: 400 });+ }+ if (!auth.user.totpEnabled) {+ return NextResponse.json({ error: "Two-factor authentication is off" }, { status: 400 });+ }+ return NextResponse.json({ recoveryCodes: await issueRecoveryCodes(env, auth.user.id) }, { headers: { "Cache-Control": "no-store" } });+}diff --git a/src/app/api/settings/mfa/route.ts b/src/app/api/settings/mfa/route.tsnew file mode 100644index 0000000..a88713b--- /dev/null+++ b/src/app/api/settings/mfa/route.ts@@ -0,0 +1,11 @@+import { NextResponse } from "next/server";+import { getEnv } from "@/lib/cloudflare";+import { requireSessionUser } from "@/lib/api/auth";+import { getMfaStatus } from "@/lib/auth/mfa";++export async function GET(request: Request) {+ const env = getEnv();+ const auth = await requireSessionUser(env, request);+ if (auth.error) return auth.error;+ return NextResponse.json(await getMfaStatus(env, auth.user));+}diff --git a/src/app/api/settings/password/route.ts b/src/app/api/settings/password/route.tsindex b65c03f..9a3f7f3 100644--- a/src/app/api/settings/password/route.ts+++ b/src/app/api/settings/password/route.ts@@ -4,6 +4,7 @@ import { ZodError } from "zod";import { getDb } from "@/db";import { users } from "@/db/schema";import { requireUser } from "@/lib/auth/cookies";+import { deleteUserSessions, getSessionTokenFromRequestHeaders } from "@/lib/auth/session";import { hashPassword, verifyPassword } from "@/lib/auth/password";import { getEnv } from "@/lib/cloudflare";import type { ChangePasswordInput } from "./types";@@ -36,6 +37,8 @@ export async function PATCH(request: Request) {.update(users).set({ passwordHash: hashPassword(parsed.newPassword) }).where(eq(users.id, user.id));+ // Anyone else holding a session for this account is signed out; this one stays.+ await deleteUserSessions(env, user.id, getSessionTokenFromRequestHeaders(request));return NextResponse.json({ ok: true });}diff --git a/src/components/settings/account-settings.tsx b/src/components/settings/account-settings.tsxindex 79b1e46..fdf3ccf 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 { MfaSettings } from "./mfa-settings";import { ForwardingEmailForm } from "./forwarding-email-form";import { MailboxSignatureForm } from "./mailbox-signature-form";import { ProfileForm } from "./profile-form";@@ -93,6 +94,13 @@ 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></div>);diff --git a/src/components/settings/mfa-settings-types.d.ts b/src/components/settings/mfa-settings-types.d.tsnew file mode 100644index 0000000..cec2de3--- /dev/null+++ b/src/components/settings/mfa-settings-types.d.ts@@ -0,0 +1 @@+export type MfaDialogStep = "password" | "scan" | "codes";diff --git a/src/components/settings/mfa-settings.tsx b/src/components/settings/mfa-settings.tsxnew file mode 100644index 0000000..54d8dd6--- /dev/null+++ b/src/components/settings/mfa-settings.tsx@@ -0,0 +1,314 @@+"use client";++import { useEffect, useState } from "react";+import { Copy, ShieldCheck, ShieldOff } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import type { MfaStatusResponse } from "./types";+import type { MfaDialogStep } from "./mfa-settings-types";+import { beginMfaEnrollment, confirmMfaEnrollment, disableMfa, loadMfaStatus, regenerateRecoveryCodes } from "./utils";++/**+ * Settings > Account > Security card for TOTP. Enrolment is a three-step+ * dialog (password, scan and confirm, save recovery codes); turning it off+ * asks for both factors again.+ */+export function MfaSettings() {+ const [status, setStatus] = useState<MfaStatusResponse | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [enrollOpen, setEnrollOpen] = useState(false);+ const [disableOpen, setDisableOpen] = useState(false);+ const [codesOpen, setCodesOpen] = useState(false);++ useEffect(() => {+ loadMfaStatus().then(setStatus).catch((err) => setError(err instanceof Error ? err.message : "Failed to load"));+ }, []);++ async function refresh() {+ setStatus(await loadMfaStatus());+ }++ if (!status) return <p className="text-sm text-neutral-500">{error ?? "Loading two-factor settings..."}</p>;++ return (+ <div className="space-y-4">+ <div className="flex items-start gap-3 rounded-2xl bg-neutral-50 p-4">+ {status.enabled ? (+ <ShieldCheck className="mt-0.5 h-5 w-5 shrink-0 text-green-600" />+ ) : (+ <ShieldOff className="mt-0.5 h-5 w-5 shrink-0 text-neutral-400" />+ )}+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-neutral-900">+ {status.enabled ? "Two-factor authentication is on" : "Two-factor authentication is off"}+ </p>+ <p className="mt-1 text-sm text-neutral-500">+ {status.enabled+ ? `Signing in asks for a code from your authenticator app. ${status.recoveryCodesLeft} recovery code${status.recoveryCodesLeft === 1 ? "" : "s"} left.`+ : "Add a second step at sign-in using an authenticator app such as 1Password, Google Authenticator or Authy."}+ </p>+ </div>+ </div>+ <div className="flex flex-wrap gap-3">+ {status.enabled ? (+ <>+ <Button variant="outline" onClick={() => setCodesOpen(true)}>+ New recovery codes+ </Button>+ <Button variant="outline" onClick={() => setDisableOpen(true)}>+ Turn off+ </Button>+ </>+ ) : (+ <Button onClick={() => setEnrollOpen(true)}>Turn on two-factor</Button>+ )}+ </div>++ <EnrollDialog open={enrollOpen} onOpenChange={setEnrollOpen} onDone={refresh} />+ <DisableDialog open={disableOpen} onOpenChange={setDisableOpen} onDone={refresh} />+ <RecoveryCodesDialog open={codesOpen} onOpenChange={setCodesOpen} onDone={refresh} />+ </div>+ );+}++function RecoveryCodesList({ codes }: { codes: string[] }) {+ const [copied, setCopied] = useState(false);+ return (+ <div className="space-y-3">+ <ul className="grid grid-cols-2 gap-2 rounded-xl bg-neutral-50 p-4 font-mono text-sm text-neutral-800">+ {codes.map((code) => (+ <li key={code}>{code}</li>+ ))}+ </ul>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => {+ void navigator.clipboard.writeText(codes.join("\n")).then(() => setCopied(true));+ }}+ >+ <Copy className="h-4 w-4" />+ {copied ? "Copied" : "Copy codes"}+ </Button>+ <p className="text-xs text-neutral-500">+ Each code works once. Keep them somewhere safe; they are the only way in if you lose your authenticator.+ </p>+ </div>+ );+}++function EnrollDialog({ open, onOpenChange, onDone }: { open: boolean; onOpenChange: (open: boolean) => void; onDone: () => Promise<void> }) {+ const [step, setStep] = useState<MfaDialogStep>("password");+ const [password, setPassword] = useState("");+ const [code, setCode] = useState("");+ const [qrSvg, setQrSvg] = useState("");+ const [secret, setSecret] = useState("");+ const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ function reset() {+ setStep("password");+ setPassword("");+ setCode("");+ setQrSvg("");+ setSecret("");+ setRecoveryCodes([]);+ setError(null);+ }++ async function start(event: React.FormEvent) {+ event.preventDefault();+ setBusy(true);+ setError(null);+ try {+ const enrollment = await beginMfaEnrollment(password);+ setQrSvg(enrollment.qrSvg);+ setSecret(enrollment.secret);+ setStep("scan");+ } catch (err) {+ setError(err instanceof Error ? err.message : "Could not start");+ } finally {+ setBusy(false);+ }+ }++ async function confirm(event: React.FormEvent) {+ event.preventDefault();+ setBusy(true);+ setError(null);+ try {+ setRecoveryCodes(await confirmMfaEnrollment(code));+ setStep("codes");+ await onDone();+ } catch (err) {+ setError(err instanceof Error ? err.message : "Could not confirm");+ } finally {+ setBusy(false);+ }+ }++ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ onOpenChange(next);+ if (!next) reset();+ }}+ >+ <DialogContent className="max-h-[calc(100vh-4rem)] overflow-y-auto sm:max-w-[480px]">+ {step === "password" && (+ <form onSubmit={start} className="space-y-4">+ <DialogHeader>+ <DialogTitle>Turn on two-factor authentication</DialogTitle>+ <DialogDescription>Confirm your password to begin.</DialogDescription>+ </DialogHeader>+ <div className="space-y-2">+ <Label htmlFor="mfa-password">Password</Label>+ <Input id="mfa-password" type="password" autoComplete="current-password" value={password} onChange={(e) => setPassword(e.target.value)} required autoFocus />+ </div>+ {error && <p className="text-sm text-red-600">{error}</p>}+ <Button type="submit" disabled={busy}>{busy ? "Please wait..." : "Continue"}</Button>+ </form>+ )}+ {step === "scan" && (+ <form onSubmit={confirm} className="space-y-4">+ <DialogHeader>+ <DialogTitle>Scan the code</DialogTitle>+ <DialogDescription>Open your authenticator app, add an account by scanning this code, then enter the 6-digit code it shows.</DialogDescription>+ </DialogHeader>+ <div className="mx-auto w-48 rounded-xl border border-neutral-200 bg-white p-2" dangerouslySetInnerHTML={{ __html: qrSvg }} />+ <details className="text-xs text-neutral-500">+ <summary className="cursor-pointer">Can't scan? Enter the key manually</summary>+ <code className="mt-2 block break-all rounded-md bg-neutral-50 p-2 font-mono text-neutral-800">{secret}</code>+ </details>+ <div className="space-y-2">+ <Label htmlFor="mfa-code">6-digit code</Label>+ <Input id="mfa-code" inputMode="numeric" autoComplete="one-time-code" value={code} onChange={(e) => setCode(e.target.value)} placeholder="123 456" required autoFocus />+ </div>+ {error && <p className="text-sm text-red-600">{error}</p>}+ <Button type="submit" disabled={busy}>{busy ? "Checking..." : "Verify and turn on"}</Button>+ </form>+ )}+ {step === "codes" && (+ <div className="space-y-4">+ <DialogHeader>+ <DialogTitle>Save your recovery codes</DialogTitle>+ <DialogDescription>Two-factor authentication is on. Other sessions have been signed out.</DialogDescription>+ </DialogHeader>+ <RecoveryCodesList codes={recoveryCodes} />+ <Button type="button" onClick={() => onOpenChange(false)}>Done</Button>+ </div>+ )}+ </DialogContent>+ </Dialog>+ );+}++function DisableDialog({ open, onOpenChange, onDone }: { open: boolean; onOpenChange: (open: boolean) => void; onDone: () => Promise<void> }) {+ const [password, setPassword] = useState("");+ const [code, setCode] = useState("");+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ async function submit(event: React.FormEvent) {+ event.preventDefault();+ setBusy(true);+ setError(null);+ try {+ await disableMfa(password, code);+ await onDone();+ onOpenChange(false);+ setPassword("");+ setCode("");+ } catch (err) {+ setError(err instanceof Error ? err.message : "Could not turn off");+ } finally {+ setBusy(false);+ }+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-h-[calc(100vh-4rem)] overflow-y-auto sm:max-w-[480px]">+ <form onSubmit={submit} className="space-y-4">+ <DialogHeader>+ <DialogTitle>Turn off two-factor authentication</DialogTitle>+ <DialogDescription>Confirm your password and a current code or recovery code.</DialogDescription>+ </DialogHeader>+ <div className="space-y-2">+ <Label htmlFor="mfa-off-password">Password</Label>+ <Input id="mfa-off-password" type="password" autoComplete="current-password" value={password} onChange={(e) => setPassword(e.target.value)} required />+ </div>+ <div className="space-y-2">+ <Label htmlFor="mfa-off-code">Code</Label>+ <Input id="mfa-off-code" inputMode="numeric" autoComplete="one-time-code" value={code} onChange={(e) => setCode(e.target.value)} required />+ </div>+ {error && <p className="text-sm text-red-600">{error}</p>}+ <Button type="submit" variant="destructive" disabled={busy}>{busy ? "Please wait..." : "Turn off"}</Button>+ </form>+ </DialogContent>+ </Dialog>+ );+}++function RecoveryCodesDialog({ open, onOpenChange, onDone }: { open: boolean; onOpenChange: (open: boolean) => void; onDone: () => Promise<void> }) {+ const [password, setPassword] = useState("");+ const [codes, setCodes] = useState<string[] | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ async function submit(event: React.FormEvent) {+ event.preventDefault();+ setBusy(true);+ setError(null);+ try {+ setCodes(await regenerateRecoveryCodes(password));+ setPassword("");+ await onDone();+ } catch (err) {+ setError(err instanceof Error ? err.message : "Could not generate codes");+ } finally {+ setBusy(false);+ }+ }++ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ onOpenChange(next);+ if (!next) setCodes(null);+ }}+ >+ <DialogContent className="max-h-[calc(100vh-4rem)] overflow-y-auto sm:max-w-[480px]">+ {codes ? (+ <div className="space-y-4">+ <DialogHeader>+ <DialogTitle>Your new recovery codes</DialogTitle>+ <DialogDescription>The previous codes no longer work.</DialogDescription>+ </DialogHeader>+ <RecoveryCodesList codes={codes} />+ <Button type="button" onClick={() => onOpenChange(false)}>Done</Button>+ </div>+ ) : (+ <form onSubmit={submit} className="space-y-4">+ <DialogHeader>+ <DialogTitle>Generate new recovery codes</DialogTitle>+ <DialogDescription>This replaces every existing code. Confirm your password to continue.</DialogDescription>+ </DialogHeader>+ <div className="space-y-2">+ <Label htmlFor="rc-password">Password</Label>+ <Input id="rc-password" type="password" autoComplete="current-password" value={password} onChange={(e) => setPassword(e.target.value)} required autoFocus />+ </div>+ {error && <p className="text-sm text-red-600">{error}</p>}+ <Button type="submit" disabled={busy}>{busy ? "Please wait..." : "Generate"}</Button>+ </form>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/settings/types.d.ts b/src/components/settings/types.d.tsindex e7e5af1..8edac95 100644--- a/src/components/settings/types.d.ts+++ b/src/components/settings/types.d.ts@@ -25,6 +25,25 @@ export type AccountSettingsResponse = {error?: unknown;};+export type MfaStatusResponse = {+ enabled: boolean;+ confirmedAt: string | null;+ recoveryCodesLeft: number;+ error?: unknown;+};++export type MfaEnrollmentResponse = {+ secret?: string;+ otpauthUrl?: string;+ qrSvg?: string;+ error?: unknown;+};++export type MfaRecoveryCodesResponse = {+ recoveryCodes?: string[];+ error?: unknown;+};+export type ForwardingEmailFormProps = {initialForwardingEmail: string;};diff --git a/src/components/settings/utils.ts b/src/components/settings/utils.tsindex 734c3b8..e832669 100644--- a/src/components/settings/utils.ts+++ b/src/components/settings/utils.ts@@ -8,7 +8,13 @@ import type {MailboxAutoReplySettings,MailboxSignatureResponse,} from "./types";-import type { AccountSettingsResponse, ChangePasswordResponse } from "./types";+import type {+ AccountSettingsResponse,+ ChangePasswordResponse,+ MfaEnrollmentResponse,+ MfaRecoveryCodesResponse,+ MfaStatusResponse,+} from "./types";export function getMailboxAddress(mailbox: Pick<MailboxOption, "localPart" | "hostname">): string {return `${mailbox.localPart}@${mailbox.hostname}`;@@ -112,3 +118,57 @@ export async function updatePassword(currentPassword: string, newPassword: strinthrow new Error(typeof data.error === "string" ? data.error : "Failed to change password");}}++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;+}diff --git a/src/db/schema/index.ts b/src/db/schema/index.tsindex 83c45d3..ab39902 100644--- a/src/db/schema/index.ts+++ b/src/db/schema/index.ts@@ -14,6 +14,11 @@ export const users = sqliteTable("users", {canManageMailboxes: integer("can_manage_mailboxes", { mode: "boolean" }).notNull().default(false),keyboardShortcutsEnabled: integer("keyboard_shortcuts_enabled", { mode: "boolean" }).notNull().default(true),spamProtectionEnabled: integer("spam_protection_enabled", { mode: "boolean" }).notNull().default(true),+ // TOTP second factor. The secret is written at enrolment and only counts+ // once the user has proven a code from their authenticator.+ totpSecret: text("totp_secret"),+ totpEnabled: integer("totp_enabled", { mode: "boolean" }).notNull().default(false),+ totpConfirmedAt: integer("totp_confirmed_at", { mode: "timestamp" }),createdByUserId: text("created_by_user_id").references((): AnySQLiteColumn => users.id, { onDelete: "set null" }),createdAt: integer("created_at", { mode: "timestamp" }).notNull()@@ -471,6 +476,58 @@ export const sessions = sqliteTable("sessions", {.$defaultFn(() => new Date()),});+/** Single-use links mailed to a user's recovery address. Only the hash is stored. */+export const passwordResetTokens = sqliteTable(+ "password_reset_tokens",+ {+ id: text("id").primaryKey(),+ userId: text("user_id")+ .notNull()+ .references(() => users.id, { onDelete: "cascade" }),+ tokenHash: text("token_hash").notNull().unique(),+ expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),+ usedAt: integer("used_at", { mode: "timestamp" }),+ createdAt: integer("created_at", { mode: "timestamp" })+ .notNull()+ .$defaultFn(() => new Date()),+ },+ (t) => [index("password_reset_tokens_user_idx").on(t.userId)],+);++/** One-time backup codes for accounts with TOTP, hashed like session tokens. */+export const mfaRecoveryCodes = sqliteTable(+ "mfa_recovery_codes",+ {+ id: text("id").primaryKey(),+ userId: text("user_id")+ .notNull()+ .references(() => users.id, { onDelete: "cascade" }),+ codeHash: text("code_hash").notNull().unique(),+ usedAt: integer("used_at", { mode: "timestamp" }),+ createdAt: integer("created_at", { mode: "timestamp" })+ .notNull()+ .$defaultFn(() => new Date()),+ },+ (t) => [index("mfa_recovery_codes_user_idx").on(t.userId)],+);++/**+ * A password that checked out but still needs a second factor. The challenge+ * token stands in for the password on the follow-up request, so the password+ * is never held client-side between the two steps.+ */+export const loginChallenges = sqliteTable("login_challenges", {+ id: text("id").primaryKey(),+ userId: text("user_id")+ .notNull()+ .references(() => users.id, { onDelete: "cascade" }),+ tokenHash: text("token_hash").notNull().unique(),+ expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),+ createdAt: integer("created_at", { mode: "timestamp" })+ .notNull()+ .$defaultFn(() => new Date()),+});+export const auditLogs = sqliteTable("audit_logs",{diff --git a/src/lib/auth/activity-types.d.ts b/src/lib/auth/activity-types.d.tsindex 8a3b7cc..4f459a2 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";+export type AuthActivityAction = "auth.login" | "auth.logout" | "auth.mfa_verified" | "auth.password_reset";export type AuthActivityMetadata = {ipAddress: string;diff --git a/src/lib/auth/login-challenge.ts b/src/lib/auth/login-challenge.tsnew file mode 100644index 0000000..0cc2dea--- /dev/null+++ b/src/lib/auth/login-challenge.ts@@ -0,0 +1,32 @@+import { and, eq, gt } from "drizzle-orm";+import { getDb } from "@/db";+import { loginChallenges } from "@/db/schema";+import { newId } from "@/lib/ids";+import { hashSessionToken } from "@/lib/auth/session";++const CHALLENGE_MINUTES = 5;++/** Issued once the password is right; the second factor completes it. */+export async function createLoginChallenge(env: CloudflareEnv, userId: string): Promise<string> {+ const db = getDb(env);+ const token = newId("mfa");+ const expiresAt = new Date(Date.now() + CHALLENGE_MINUTES * 60 * 1000);+ await db.insert(loginChallenges).values({ id: newId(), userId, tokenHash: await hashSessionToken(token), expiresAt });+ return token;+}++/** Look a challenge up without consuming it, so a wrong code can be retried within the window. */+export async function getLoginChallengeUserId(env: CloudflareEnv, token: string): Promise<string | null> {+ const db = getDb(env);+ const [row] = await db+ .select({ userId: loginChallenges.userId })+ .from(loginChallenges)+ .where(and(eq(loginChallenges.tokenHash, await hashSessionToken(token)), gt(loginChallenges.expiresAt, new Date())))+ .limit(1);+ return row?.userId ?? null;+}++export async function consumeLoginChallenge(env: CloudflareEnv, token: string): Promise<void> {+ const db = getDb(env);+ await db.delete(loginChallenges).where(eq(loginChallenges.tokenHash, await hashSessionToken(token)));+}diff --git a/src/lib/auth/mfa-types.d.ts b/src/lib/auth/mfa-types.d.tsnew file mode 100644index 0000000..78fca6f--- /dev/null+++ b/src/lib/auth/mfa-types.d.ts@@ -0,0 +1,12 @@+export type MfaStatus = {+ enabled: boolean;+ confirmedAt: string | null;+ recoveryCodesLeft: number;+};++export type MfaEnrollment = {+ secret: string;+ otpauthUrl: string;+ /** Inline SVG of the otpauth URL, for the enrolment dialog. */+ qrSvg: string;+};diff --git a/src/lib/auth/mfa.ts b/src/lib/auth/mfa.tsnew file mode 100644index 0000000..741e5e4--- /dev/null+++ b/src/lib/auth/mfa.ts@@ -0,0 +1,68 @@+import { eq } from "drizzle-orm";+import QRCode from "qrcode";+import { getDb } from "@/db";+import { mfaRecoveryCodes, users } from "@/db/schema";+import { getBranding } from "@/lib/branding/service";+import { consumeRecoveryCode, countUnusedRecoveryCodes, issueRecoveryCodes } from "@/lib/auth/recovery-codes";+import { deleteUserSessions } from "@/lib/auth/session";+import { buildOtpauthUrl, generateTotpSecret, verifyTotp } from "@/lib/auth/totp";+import type { MfaEnrollment, MfaStatus } from "@/lib/auth/mfa-types";++export async function getMfaStatus(env: CloudflareEnv, user: { id: string; totpEnabled: boolean; totpConfirmedAt: Date | null }): Promise<MfaStatus> {+ return {+ enabled: user.totpEnabled,+ confirmedAt: user.totpConfirmedAt?.toISOString() ?? null,+ recoveryCodesLeft: user.totpEnabled ? await countUnusedRecoveryCodes(env, user.id) : 0,+ };+}++/**+ * Start enrolment: a fresh secret is stored but not yet trusted. It only+ * becomes the account's second factor once `confirmMfaEnrollment` sees a+ * code generated from it, which proves the authenticator has it.+ */+export async function beginMfaEnrollment(env: CloudflareEnv, user: { id: string; email: string }): Promise<MfaEnrollment> {+ const db = getDb(env);+ const secret = generateTotpSecret();+ await db.update(users).set({ totpSecret: secret, totpEnabled: false, totpConfirmedAt: null }).where(eq(users.id, user.id));+ const { appName } = await getBranding(env);+ const otpauthUrl = buildOtpauthUrl({ issuer: appName, account: user.email, secret });+ const qrSvg = await QRCode.toString(otpauthUrl, { type: "svg", margin: 1, errorCorrectionLevel: "M" });+ return { secret, otpauthUrl, qrSvg };+}++export async function confirmMfaEnrollment(+ env: CloudflareEnv,+ user: { id: string; totpSecret: string | null; totpEnabled: boolean },+ code: string,+ currentSessionToken?: string,+): Promise<{ ok: true; recoveryCodes: string[] } | { ok: false; error: string }> {+ if (!user.totpSecret) return { ok: false, error: "Start enrolment first" };+ if (user.totpEnabled) return { ok: false, error: "Two-factor authentication is already on" };+ if (!(await verifyTotp(user.totpSecret, code))) return { ok: false, error: "That code did not match. Check the time on your device and try again." };++ const db = getDb(env);+ await db.update(users).set({ totpEnabled: true, totpConfirmedAt: new Date() }).where(eq(users.id, user.id));+ const recoveryCodes = await issueRecoveryCodes(env, user.id);+ // Other sessions predate the second factor; make them sign in again with it.+ await deleteUserSessions(env, user.id, currentSessionToken);+ return { ok: true, recoveryCodes };+}++export async function disableMfa(env: CloudflareEnv, userId: string): Promise<void> {+ const db = getDb(env);+ await db.update(users).set({ totpSecret: null, totpEnabled: false, totpConfirmedAt: null }).where(eq(users.id, userId));+ await db.delete(mfaRecoveryCodes).where(eq(mfaRecoveryCodes.userId, userId));+}++/** A login's second step: a TOTP code, or one of the recovery codes as a fallback. */+export async function verifySecondFactor(+ env: CloudflareEnv,+ user: { id: string; totpSecret: string | null; totpEnabled: boolean },+ code: string,+): Promise<"totp" | "recovery" | null> {+ if (!user.totpEnabled || !user.totpSecret) return null;+ if (await verifyTotp(user.totpSecret, code)) return "totp";+ if (await consumeRecoveryCode(env, user.id, code)) return "recovery";+ return null;+}diff --git a/src/lib/auth/password-reset-utils.ts b/src/lib/auth/password-reset-utils.tsnew file mode 100644index 0000000..aaa7a51--- /dev/null+++ b/src/lib/auth/password-reset-utils.ts@@ -0,0 +1,3 @@+export function escapeHtml(value: string): string {+ return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);+}diff --git a/src/lib/auth/password-reset.ts b/src/lib/auth/password-reset.tsnew file mode 100644index 0000000..3164de9--- /dev/null+++ b/src/lib/auth/password-reset.ts@@ -0,0 +1,81 @@+import { and, eq, gt, isNull } from "drizzle-orm";+import { getDb } from "@/db";+import { passwordResetTokens, users } from "@/db/schema";+import { newId } from "@/lib/ids";+import { hashPassword } from "@/lib/auth/password";+import { deleteUserSessions, hashSessionToken } from "@/lib/auth/session";+import { getBranding } from "@/lib/branding/service";+import { sendSystemEmail } from "@/lib/email/system-mail";+import { createAuditLog } from "@/lib/mailboxes/audit";+import { escapeHtml } from "@/lib/auth/password-reset-utils";++const TOKEN_MINUTES = 30;++/**+ * Mail a reset link to the account's recovery address. Silent about whether+ * the account exists or has one: the caller always answers the same way, so+ * the form cannot be used to probe for addresses.+ */+export async function requestPasswordReset(env: CloudflareEnv, email: string, origin: string): Promise<void> {+ const db = getDb(env);+ const [user] = await db.select().from(users).where(eq(users.email, email.trim().toLowerCase())).limit(1);+ if (!user || user.disabled || !user.resetEmail) return;++ const token = newId("prt");+ await db.insert(passwordResetTokens).values({+ id: newId(),+ userId: user.id,+ tokenHash: await hashSessionToken(token),+ expiresAt: new Date(Date.now() + TOKEN_MINUTES * 60 * 1000),+ });++ const link = `${origin}/reset-password?token=${encodeURIComponent(token)}`;+ const { appName } = await getBranding(env);+ const sent = await sendSystemEmail(env, {+ to: user.resetEmail,+ subject: `Reset your ${appName} password`,+ text: [+ `Someone asked to reset the password for ${user.email} on ${appName}.`,+ "",+ `Open this link within ${TOKEN_MINUTES} minutes to choose a new password:`,+ link,+ "",+ "If that was not you, you can ignore this message; the password stays as it is.",+ ].join("\n"),+ html: `<p>Someone asked to reset the password for <b>${escapeHtml(user.email)}</b> on ${escapeHtml(appName)}.</p><p>Open this link within ${TOKEN_MINUTES} minutes to choose a new password:</p><p><a href="${escapeHtml(link)}">${escapeHtml(link)}</a></p><p>If that was not you, you can ignore this message; the password stays as it is.</p>`,+ });+ if (!sent) console.warn("Password reset requested but no domain can send mail; link not delivered");+}++/** Redeem a link: sets the password, burns the token, and signs the user out everywhere. */+export async function completePasswordReset(+ env: CloudflareEnv,+ token: string,+ newPassword: string,+ request: Request,+): Promise<{ ok: true } | { ok: false; error: string }> {+ const db = getDb(env);+ const [row] = await db+ .select({ id: passwordResetTokens.id, userId: passwordResetTokens.userId })+ .from(passwordResetTokens)+ .where(+ and(+ eq(passwordResetTokens.tokenHash, await hashSessionToken(token)),+ gt(passwordResetTokens.expiresAt, new Date()),+ isNull(passwordResetTokens.usedAt),+ ),+ )+ .limit(1);+ if (!row) return { ok: false, error: "This reset link is invalid or has expired. Request a new one." };++ await db.update(users).set({ passwordHash: hashPassword(newPassword) }).where(eq(users.id, row.userId));+ await db.update(passwordResetTokens).set({ usedAt: new Date() }).where(eq(passwordResetTokens.id, row.id));+ await deleteUserSessions(env, row.userId);+ await createAuditLog(env, {+ actorUserId: row.userId,+ targetUserId: row.userId,+ action: "auth.password_reset",+ metadata: { ipAddress: request.headers.get("cf-connecting-ip") ?? "unknown" },+ });+ return { ok: true };+}diff --git a/src/lib/auth/recovery-codes.ts b/src/lib/auth/recovery-codes.tsnew file mode 100644index 0000000..9748aa2--- /dev/null+++ b/src/lib/auth/recovery-codes.ts@@ -0,0 +1,56 @@+import { and, eq, isNull } from "drizzle-orm";+import { getDb } from "@/db";+import { mfaRecoveryCodes } from "@/db/schema";+import { newId } from "@/lib/ids";+import { hashSessionToken } from "@/lib/auth/session";++const CODE_COUNT = 8;+/** No 0/O/1/I/L, so a code read off paper cannot be mistyped. */+const CODE_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";++function generateCode(): string {+ const bytes = new Uint8Array(10);+ crypto.getRandomValues(bytes);+ const chars = Array.from(bytes, (byte) => CODE_ALPHABET[byte % CODE_ALPHABET.length]);+ return `${chars.slice(0, 5).join("")}-${chars.slice(5).join("")}`;+}++export function normalizeRecoveryCode(code: string): string {+ return code.toLowerCase().replace(/[^a-z0-9]/g, "");+}++/** Replace the user's codes with a fresh set and return them in the clear, once. */+export async function issueRecoveryCodes(env: CloudflareEnv, userId: string): Promise<string[]> {+ const db = getDb(env);+ const codes = Array.from({ length: CODE_COUNT }, generateCode);+ await db.delete(mfaRecoveryCodes).where(eq(mfaRecoveryCodes.userId, userId));+ await db.insert(mfaRecoveryCodes).values(+ await Promise.all(+ codes.map(async (code) => ({ id: newId("rc"), userId, codeHash: await hashSessionToken(normalizeRecoveryCode(code)) })),+ ),+ );+ return codes;+}++/** Burn a code if it is one of the user's unused ones. */+export async function consumeRecoveryCode(env: CloudflareEnv, userId: string, code: string): Promise<boolean> {+ const db = getDb(env);+ const codeHash = await hashSessionToken(normalizeRecoveryCode(code));+ const [row] = await db+ .select({ id: mfaRecoveryCodes.id })+ .from(mfaRecoveryCodes)+ .where(and(eq(mfaRecoveryCodes.userId, userId), eq(mfaRecoveryCodes.codeHash, codeHash), isNull(mfaRecoveryCodes.usedAt)))+ .limit(1);+ if (!row) return false;+ await db.update(mfaRecoveryCodes).set({ usedAt: new Date() }).where(eq(mfaRecoveryCodes.id, row.id));+ return true;+}++export async function countUnusedRecoveryCodes(env: CloudflareEnv, userId: string): Promise<number> {+ const db = getDb(env);+ const rows = await db+ .select({ id: mfaRecoveryCodes.id })+ .from(mfaRecoveryCodes)+ .where(and(eq(mfaRecoveryCodes.userId, userId), isNull(mfaRecoveryCodes.usedAt)));+ return rows.length;+}diff --git a/src/lib/auth/session.ts b/src/lib/auth/session.tsindex a795a95..722b8aa 100644--- a/src/lib/auth/session.ts+++ b/src/lib/auth/session.ts@@ -1,4 +1,4 @@-import { and, eq, gt } from "drizzle-orm";+import { and, eq, gt, ne } from "drizzle-orm";import { newId } from "@/lib/ids";import { getDb } from "@/db";import { sessions, users } from "@/db/schema";@@ -56,3 +56,26 @@ export async function deleteSession(env: CloudflareEnv, token: string): Promise<const tokenHash = await hashSessionToken(token);await db.delete(sessions).where(eq(sessions.tokenHash, tokenHash));}++/**+ * 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.+ */+export async function deleteUserSessions(env: CloudflareEnv, userId: string, keepToken?: string): Promise<void> {+ const db = getDb(env);+ if (keepToken) {+ const keepHash = await hashSessionToken(keepToken);+ await db.delete(sessions).where(and(eq(sessions.userId, userId), ne(sessions.tokenHash, keepHash)));+ return;+ }+ await db.delete(sessions).where(eq(sessions.userId, userId));+}++/** The session token a request carries, from the Bearer header or the cookie. */+export function getSessionTokenFromRequestHeaders(request: Request): string | undefined {+ const authorization = request.headers.get("Authorization");+ if (authorization?.startsWith("Bearer ")) return authorization.slice(7).trim() || undefined;+ const cookie = request.headers.get("Cookie") ?? "";+ const match = cookie.match(new RegExp(`(?:^|;\\s*)${SESSION_COOKIE}=([^;]+)`));+ return match ? decodeURIComponent(match[1]) : undefined;+}diff --git a/src/lib/auth/totp.ts b/src/lib/auth/totp.tsnew file mode 100644index 0000000..86ced15--- /dev/null+++ b/src/lib/auth/totp.ts@@ -0,0 +1,108 @@+/**+ * RFC 6238 TOTP over Web Crypto, with no dependency. HMAC-SHA1, 30-second+ * steps, six digits: the profile every authenticator app implements.+ */+const BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";+const STEP_SECONDS = 30;+const DIGITS = 6;++export function base32Encode(bytes: Uint8Array): string {+ let bits = 0;+ let value = 0;+ let output = "";+ for (const byte of bytes) {+ value = (value << 8) | byte;+ bits += 8;+ while (bits >= 5) {+ output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];+ bits -= 5;+ }+ }+ if (bits > 0) output += BASE32_ALPHABET[(value << (5 - bits)) & 31];+ return output;+}++export function base32Decode(input: string): Uint8Array<ArrayBuffer> {+ const clean = input.toUpperCase().replace(/[^A-Z2-7]/g, "");+ const bytes: number[] = [];+ let bits = 0;+ let value = 0;+ for (const char of clean) {+ value = (value << 5) | BASE32_ALPHABET.indexOf(char);+ bits += 5;+ if (bits >= 8) {+ bytes.push((value >>> (bits - 8)) & 255);+ bits -= 8;+ }+ }+ const out = new Uint8Array(new ArrayBuffer(bytes.length));+ out.set(bytes);+ return out;+}++/** 160-bit secret, the size RFC 4226 recommends for HMAC-SHA1. */+export function generateTotpSecret(): string {+ const bytes = new Uint8Array(20);+ crypto.getRandomValues(bytes);+ return base32Encode(bytes);+}++export async function hotp(secret: string, counter: number): Promise<string> {+ const key = await crypto.subtle.importKey("raw", base32Decode(secret), { name: "HMAC", hash: "SHA-1" }, false, ["sign"]);+ const message = new Uint8Array(8);+ // Big-endian 64-bit counter; the high word stays zero for any sane clock.+ let remaining = counter;+ for (let index = 7; index >= 0; index -= 1) {+ message[index] = remaining & 255;+ remaining = Math.floor(remaining / 256);+ }+ const digest = new Uint8Array(await crypto.subtle.sign("HMAC", key, message));+ const offset = digest[digest.length - 1] & 15;+ const binary =+ ((digest[offset] & 127) << 24) | ((digest[offset + 1] & 255) << 16) | ((digest[offset + 2] & 255) << 8) | (digest[offset + 3] & 255);+ return String(binary % 10 ** DIGITS).padStart(DIGITS, "0");+}++export function totpCounter(at: number = Date.now()): number {+ return Math.floor(at / 1000 / STEP_SECONDS);+}++export async function totp(secret: string, at: number = Date.now()): Promise<string> {+ return hotp(secret, totpCounter(at));+}++/**+ * Accept the current step and one on either side, so a phone whose clock is a+ * few seconds off still works. Comparison is constant-time.+ */+export async function verifyTotp(secret: string, code: string, at: number = Date.now()): Promise<boolean> {+ const candidate = code.replace(/\s+/g, "");+ if (!/^\d{6}$/.test(candidate)) return false;+ const counter = totpCounter(at);+ let matched = false;+ for (const delta of [-1, 0, 1]) {+ const expected = await hotp(secret, counter + delta);+ if (timingSafeEqual(expected, candidate)) matched = true;+ }+ return matched;+}++export function timingSafeEqual(a: string, b: string): boolean {+ if (a.length !== b.length) return false;+ let diff = 0;+ for (let index = 0; index < a.length; index += 1) diff |= a.charCodeAt(index) ^ b.charCodeAt(index);+ return diff === 0;+}++/** The URI authenticator apps read from a QR code (Google Authenticator key format). */+export function buildOtpauthUrl(input: { issuer: string; account: string; secret: string }): string {+ const label = `${encodeURIComponent(input.issuer)}:${encodeURIComponent(input.account)}`;+ const params = new URLSearchParams({+ secret: input.secret,+ issuer: input.issuer,+ algorithm: "SHA1",+ digits: String(DIGITS),+ period: String(STEP_SECONDS),+ });+ return `otpauth://totp/${label}?${params.toString()}`;+}diff --git a/src/lib/backups/export.ts b/src/lib/backups/export.tsindex e97ebff..74c15c2 100644--- a/src/lib/backups/export.ts+++ b/src/lib/backups/export.ts@@ -1,7 +1,7 @@import type { DatabaseBackupDocument, DatabaseBackupTable, DatabaseRecord } from "./types";import { mergeLegacyMessageBodies } from "./utils";-const BACKUP_TABLES: DatabaseBackupTable[] = ["users", "domains", "mailboxes", "mailbox_access", "contacts", "folders", "api_keys", "messages", "message_attachments", "outbound_jobs", "routing_rules", "webhooks", "webhook_deliveries", "sessions", "audit_logs", "backup_settings", "backups", "app_settings", "license_settings", "email_templates", "calendar_events", "auto_reply_deliveries", "spam_token_stats", "spam_reputation", "spam_feedback"];+const BACKUP_TABLES: DatabaseBackupTable[] = ["users", "domains", "mailboxes", "mailbox_access", "contacts", "folders", "api_keys", "messages", "message_attachments", "outbound_jobs", "routing_rules", "webhooks", "webhook_deliveries", "sessions", "audit_logs", "backup_settings", "backups", "app_settings", "license_settings", "email_templates", "calendar_events", "auto_reply_deliveries", "spam_token_stats", "spam_reputation", "spam_feedback", "password_reset_tokens", "mfa_recovery_codes", "login_challenges"];/*** Tables every backup document must contain. Tables added to BACKUP_TABLES* after the format shipped are absent from older documents, so they staydiff --git a/src/lib/backups/types.d.ts b/src/lib/backups/types.d.tsindex ac6d5bf..414bdcf 100644--- a/src/lib/backups/types.d.ts+++ b/src/lib/backups/types.d.ts@@ -1,5 +1,5 @@export type BackupScheduleType = "daily" | "weekly" | "monthly";-export type DatabaseBackupTable = "users" | "domains" | "mailboxes" | "mailbox_access" | "contacts" | "folders" | "api_keys" | "messages" | "message_attachments" | "outbound_jobs" | "routing_rules" | "webhooks" | "webhook_deliveries" | "sessions" | "audit_logs" | "backup_settings" | "backups" | "app_settings" | "license_settings" | "email_templates" | "calendar_events" | "auto_reply_deliveries" | "spam_token_stats" | "spam_reputation" | "spam_feedback";+export type DatabaseBackupTable = "users" | "domains" | "mailboxes" | "mailbox_access" | "contacts" | "folders" | "api_keys" | "messages" | "message_attachments" | "outbound_jobs" | "routing_rules" | "webhooks" | "webhook_deliveries" | "sessions" | "audit_logs" | "backup_settings" | "backups" | "app_settings" | "license_settings" | "email_templates" | "calendar_events" | "auto_reply_deliveries" | "spam_token_stats" | "spam_reputation" | "spam_feedback" | "password_reset_tokens" | "mfa_recovery_codes" | "login_challenges";export type DatabaseRecord = Record<string, string | number | null>;export type DatabaseBackupDocument = { format: "mailflare-database-backup"; version: 1; createdAt: string; tables: Record<DatabaseBackupTable, DatabaseRecord[]>; };diff --git a/src/lib/email/system-mail-types.d.ts b/src/lib/email/system-mail-types.d.tsnew file mode 100644index 0000000..4593143--- /dev/null+++ b/src/lib/email/system-mail-types.d.ts@@ -0,0 +1,6 @@+export type SystemMailInput = {+ to: string;+ subject: string;+ text: string;+ html?: string;+};diff --git a/src/lib/email/system-mail.ts b/src/lib/email/system-mail.tsnew file mode 100644index 0000000..0aa6ffa--- /dev/null+++ b/src/lib/email/system-mail.ts@@ -0,0 +1,52 @@+import { and, asc, eq } from "drizzle-orm";+import { getDb } from "@/db";+import { domains, mailboxes, users } from "@/db/schema";+import { formatEmailAddress } from "@/lib/email/address";+import type { SystemMailInput } from "@/lib/email/system-mail-types";++/**+ * Mail the application sends on its own behalf (password resets). It goes+ * straight through the send binding: no Sent copy, no contact upsert, no+ * webhooks, and the auto-generated headers mail systems expect.+ *+ * The From address is the primary mailbox of the first administrator on a+ * domain that can send; if no domain has sending enabled there is nothing to+ * send from, and the caller decides what to tell the user.+ */+export async function sendSystemEmail(env: CloudflareEnv, input: SystemMailInput): Promise<boolean> {+ const sender = await pickSystemSender(env);+ if (!sender) return false;++ await env.EMAIL.send({+ from: formatEmailAddress(sender.address, sender.name),+ to: input.to,+ subject: input.subject,+ text: input.text,+ html: input.html,+ headers: {+ "Auto-Submitted": "auto-generated",+ "X-Auto-Response-Suppress": "All",+ },+ });+ return true;+}++export async function pickSystemSender(env: CloudflareEnv): Promise<{ address: string; name: string } | null> {+ const db = getDb(env);+ const rows = await db+ .select({+ localPart: mailboxes.localPart,+ displayName: mailboxes.displayName,+ hostname: domains.hostname,+ role: users.role,+ })+ .from(mailboxes)+ .innerJoin(domains, eq(mailboxes.domainId, domains.id))+ .innerJoin(users, eq(mailboxes.userId, users.id))+ .where(and(eq(domains.sendingEnabled, true), eq(mailboxes.disabled, false), eq(users.disabled, false)))+ .orderBy(asc(mailboxes.createdAt))+ .limit(50);+ const chosen = rows.find((row) => row.role === "admin") ?? rows[0];+ if (!chosen) return null;+ return { address: `${chosen.localPart}@${chosen.hostname}`, name: chosen.displayName ?? "Mailflare" };+}diff --git a/src/lib/setup/migration.ts b/src/lib/setup/migration.tsindex d91ec72..398d58d 100644--- a/src/lib/setup/migration.ts+++ b/src/lib/setup/migration.ts@@ -29,10 +29,11 @@ const MIGRATION_NAMES = ["0027_add_domain_sending_intent.sql","0028_add_keyboard_shortcuts_setting.sql","0029_add_spam_protection.sql",+ "0031_add_password_reset_and_mfa.sql",];const INITIAL_SCHEMA_SQL = `-CREATE TABLE IF NOT EXISTS users (id text PRIMARY KEY NOT NULL, email text NOT NULL UNIQUE, reset_email text, forwarding_email text, password_hash text NOT NULL, name text NOT NULL, avatar_key text, role text DEFAULT 'user' NOT NULL, disabled integer DEFAULT false NOT NULL, can_manage_mailboxes integer DEFAULT false NOT NULL, keyboard_shortcuts_enabled integer DEFAULT true NOT NULL, spam_protection_enabled integer DEFAULT true NOT NULL, created_by_user_id text REFERENCES users(id) ON DELETE set null, created_at integer NOT NULL);+CREATE TABLE IF NOT EXISTS users (id text PRIMARY KEY NOT NULL, email text NOT NULL UNIQUE, reset_email text, forwarding_email text, password_hash text NOT NULL, name text NOT NULL, avatar_key text, role text DEFAULT 'user' NOT NULL, disabled integer DEFAULT false NOT NULL, can_manage_mailboxes integer DEFAULT false NOT NULL, keyboard_shortcuts_enabled integer DEFAULT true NOT NULL, spam_protection_enabled integer DEFAULT true NOT NULL, totp_secret text, totp_enabled integer DEFAULT false NOT NULL, totp_confirmed_at integer, created_by_user_id text REFERENCES users(id) ON DELETE set null, created_at integer NOT NULL);CREATE INDEX IF NOT EXISTS users_created_by_idx ON users(created_by_user_id);CREATE TABLE IF NOT EXISTS domains (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, hostname text NOT NULL, zone_id text NOT NULL, status text DEFAULT 'pending' NOT NULL, routing_status text, sending_subdomain_tag text, sending_requested integer DEFAULT false NOT NULL, sending_enabled integer DEFAULT false NOT NULL, routing_enabled integer DEFAULT false NOT NULL, created_at integer NOT NULL);CREATE UNIQUE INDEX IF NOT EXISTS domains_hostname_idx ON domains(hostname);@@ -87,6 +88,11 @@ CREATE TABLE IF NOT EXISTS webhooks (id text PRIMARY KEY NOT NULL, user_id textCREATE TABLE IF NOT EXISTS webhook_deliveries (id text PRIMARY KEY NOT NULL, webhook_id text NOT NULL REFERENCES webhooks(id) ON DELETE cascade, event_type text NOT NULL, payload text NOT NULL, status text DEFAULT 'pending' NOT NULL, attempts integer DEFAULT 0 NOT NULL, response_status integer, error text, duration_ms integer, last_attempt_at integer, next_retry_at integer, created_at integer NOT NULL);CREATE INDEX IF NOT EXISTS webhook_deliveries_webhook_idx ON webhook_deliveries(webhook_id, created_at);CREATE INDEX IF NOT EXISTS webhook_deliveries_status_idx ON webhook_deliveries(status);+CREATE TABLE IF NOT EXISTS password_reset_tokens (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, token_hash text NOT NULL UNIQUE, expires_at integer NOT NULL, used_at integer, created_at integer NOT NULL);+CREATE INDEX IF NOT EXISTS password_reset_tokens_user_idx ON password_reset_tokens(user_id);+CREATE TABLE IF NOT EXISTS mfa_recovery_codes (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, code_hash text NOT NULL UNIQUE, used_at integer, created_at integer NOT NULL);+CREATE INDEX IF NOT EXISTS mfa_recovery_codes_user_idx ON mfa_recovery_codes(user_id);+CREATE TABLE IF NOT EXISTS login_challenges (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, token_hash text NOT NULL UNIQUE, expires_at integer NOT NULL, created_at integer NOT NULL);CREATE TABLE IF NOT EXISTS sessions (id text PRIMARY KEY NOT NULL, user_id text NOT NULL REFERENCES users(id) ON DELETE cascade, token_hash text NOT NULL UNIQUE, expires_at integer NOT NULL, created_at integer NOT NULL);CREATE TABLE IF NOT EXISTS audit_logs (id text PRIMARY KEY NOT NULL, actor_user_id text REFERENCES users(id) ON DELETE set null, target_user_id text REFERENCES users(id) ON DELETE set null, mailbox_id text REFERENCES mailboxes(id) ON DELETE set null, message_id text REFERENCES messages(id) ON DELETE set null, action text NOT NULL, metadata text, created_at integer NOT NULL);CREATE INDEX IF NOT EXISTS audit_logs_actor_idx ON audit_logs(actor_user_id);diff --git a/src/lib/validators.ts b/src/lib/validators.tsindex a507d32..23da7c8 100644--- a/src/lib/validators.ts+++ b/src/lib/validators.ts@@ -77,6 +77,33 @@ export const loginSchema = z.object({password: z.string().min(1),});+export const passwordResetRequestSchema = z.object({+ email: z.string().trim().email(),+});++export const passwordResetConfirmSchema = z.object({+ token: z.string().min(8).max(200),+ password: z.string().min(8).max(128),+});++export const mfaVerifySchema = z.object({+ challengeToken: z.string().min(8).max(200),+ code: z.string().trim().min(6).max(32),+});++export const mfaEnrollSchema = z.object({+ password: z.string().min(1),+});++export const mfaConfirmSchema = z.object({+ code: z.string().trim().min(6).max(12),+});++export const mfaDisableSchema = z.object({+ password: z.string().min(1),+ code: z.string().trim().min(6).max(32),+});+export const domainSchema = z.object({hostname: z.string().min(3),});@@ -98,6 +125,11 @@ export const updateManagedAccountSchema = z.object({(value) => (typeof value === "string" ? value.trim() : value),z.string().email().or(z.literal("")).optional().transform((value) => value === undefined ? undefined : value || null),),+ /** Set a new password for the account; every session of that user is revoked. */+ password: z.preprocess(+ (value) => (typeof value === "string" ? value.trim() : value),+ z.string().min(8).max(128).or(z.literal("")).optional().transform((value) => value || null),+ ),});export const createAccountSchema = z.object({