From 851c22b80eabf3f33218cb8abeeb051c9f031e65 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:34:44 +0800 Subject: [PATCH] =?UTF-8?q?feat(worker):=20=E6=9C=AA=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=8F=91=E4=BB=B6=E5=AE=88=E5=8D=AB=E2=80=94=E2=80=94email=5Fc?= =?UTF-8?q?onfigured=20=E5=8D=95=E4=B8=80=E7=9C=9F=E6=BA=90=20+=202FA/?= =?UTF-8?q?=E6=89=BE=E5=9B=9E=E5=AF=86=E7=A0=81=20fail-closed=20(ONE-461)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - email.ts 新增 isEmailConfigured(env) 作为全仓唯一发件能力判断(provider none / resend 缺 api_key / smtp 缺 host / 配置损坏 / 未知 provider 一律 false,不抛错) - GET /api/system/info 新增 email_configured: boolean;catch 分支 fail-closed 回 false - POST /auth/login 过滤 email_otp;唯一方式被过滤清空时 403 2FA_METHOD_UNAVAILABLE, 不发 tempToken、不签 token(不再静默降级为仅密码);/auth/refresh 的 needs2faSetup 用同一过滤口径 - /auth/2fa/otp/send、/auth/2fa/verify(email_otp) 未配置 503 EMAIL_NOT_CONFIGURED, 前者在生成验证码之前拒绝,不写 KV、不发信 - /auth/password/forgot 在冷却与用户查询之前统一 503,注册/未注册邮箱同响应, 不写 pwd_reset:*、不设冷却;已配置语义逐字不变 - /auth/2fa/email-otp/send-verify 与 /enable 未配置直接拒绝,删除「未配置可免验证码 直接启用」分支;/disable 永远放行 - 新增 worker/test/email-not-configured.test.ts(25 例),覆盖父单 §6 第 1–7 条 --- worker/src/index.ts | 4 + worker/src/routes/auth.ts | 43 +- worker/src/routes/auth2fa.ts | 64 ++- worker/src/services/email.ts | 59 +++ worker/src/services/twofa.ts | 15 +- worker/test/email-not-configured.test.ts | 648 +++++++++++++++++++++++ 6 files changed, 819 insertions(+), 14 deletions(-) create mode 100644 worker/test/email-not-configured.test.ts diff --git a/worker/src/index.ts b/worker/src/index.ts index f43220c..6e65ae5 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -15,6 +15,7 @@ import { notifyRoutes } from "./routes/notify"; import { setupRoutes } from "./routes/setup"; import { handleScheduled } from "./services/scheduler"; import { getAllSettings } from "./db/queries/settings"; +import { isEmailConfigured } from "./services/email"; const app = new Hono(); @@ -85,12 +86,15 @@ app.get("/api/system/info", async (c) => { app_name: settings.app_name || "eNotify", version: typeof APP_VERSION !== "undefined" ? APP_VERSION : "0.0.0", registration_enabled: settings.registration_enabled !== "false", + email_configured: await isEmailConfigured(c.env), }); } catch { + // Fail closed: never advertise an email entry point we cannot serve. return c.json({ app_name: "eNotify", version: typeof APP_VERSION !== "undefined" ? APP_VERSION : "0.0.0", registration_enabled: true, + email_configured: false, }); } }); diff --git a/worker/src/routes/auth.ts b/worker/src/routes/auth.ts index f928dc6..dead4a8 100644 --- a/worker/src/routes/auth.ts +++ b/worker/src/routes/auth.ts @@ -20,7 +20,7 @@ import { upsertNotificationConfig } from "../db/queries/notifications"; import { getSetting } from "../db/queries/settings"; import { get2FAConfig } from "../db/queries/twofa"; import { getAvailable2FAMethods } from "../services/twofa"; -import { sendEmail } from "../services/email"; +import { isEmailConfigured, sendEmail } from "../services/email"; import { rateLimit } from "../middleware/ratelimit"; export const authRoutes = new Hono(); @@ -171,7 +171,12 @@ authRoutes.post("/login", async (c) => { const require2FA = await getSetting(c.env.DB, prefix, "require_2fa"); const twoFAConfig = await get2FAConfig(c.env.DB, prefix, user.id); - const methods = getAvailable2FAMethods(twoFAConfig); + // What the user actually enabled, and what we may offer right now: an + // unconfigured instance can never deliver an email code, so email_otp is + // filtered out of the offer (the switches themselves stay untouched). + const enabledMethods = getAvailable2FAMethods(twoFAConfig); + const emailConfigured = await isEmailConfigured(c.env); + const methods = getAvailable2FAMethods(twoFAConfig, { emailConfigured }); if (methods.length > 0) { const tempToken = generateId(); @@ -183,6 +188,21 @@ authRoutes.post("/login", async (c) => { }); } + // Fail closed: the user has 2FA enabled, but every method they enabled is + // unavailable right now (only email_otp, and email delivery is off). Never + // silently downgrade to password-only — that would let an admin switch off + // email sending and thereby switch off the user's second factor. + if (enabledMethods.length > 0) { + return c.json( + { + error: + "Your enabled two-factor method is currently unavailable (email delivery is not configured on this site). Please contact an administrator.", + code: "2FA_METHOD_UNAVAILABLE", + }, + 403, + ); + } + if (require2FA === "true") { await issueTokens(c, user.id, user.role, true); return c.json({ @@ -267,7 +287,9 @@ authRoutes.post("/refresh", async (c) => { let needs2faSetup = false; if (require2FA === "true") { const twoFAConfig = await get2FAConfig(c.env.DB, prefix, user.id); - needs2faSetup = getAvailable2FAMethods(twoFAConfig).length === 0; + const emailConfigured = await isEmailConfigured(c.env); + needs2faSetup = + getAvailable2FAMethods(twoFAConfig, { emailConfigured }).length === 0; } await issueTokens(c, user.id, user.role, needs2faSetup, payload.sid); @@ -316,6 +338,21 @@ authRoutes.post("/password/forgot", async (c) => { const { email } = await c.req.json<{ email: string }>(); if (!email) return c.json({ error: "Email required" }, 400); + // Site-level, already-public fact (see /api/system/info): when email + // delivery is not configured, no reset code can ever reach anyone. Answer + // identically for registered and unregistered addresses, before the + // cooldown and the user lookup, and write nothing to KV. + if (!(await isEmailConfigured(c.env))) { + return c.json( + { + error: + "Email delivery is not configured on this site, so password recovery by email is unavailable. Please contact an administrator to reset your password.", + code: "EMAIL_NOT_CONFIGURED", + }, + 503, + ); + } + // Per-email cooldown: 60s between resend // Check & set cooldown before user lookup to avoid email enumeration const cooldownKey = `pwd_reset_cd:${email}`; diff --git a/worker/src/routes/auth2fa.ts b/worker/src/routes/auth2fa.ts index 7e96b57..80b53db 100644 --- a/worker/src/routes/auth2fa.ts +++ b/worker/src/routes/auth2fa.ts @@ -17,7 +17,7 @@ import { verifyEmailOTP, sendOTPEmail, } from "../services/twofa"; -import { getSetting } from "../db/queries/settings"; +import { isEmailConfigured } from "../services/email"; import { signJWT, generateId, generateJti, verifyPassword } from "../core/auth"; import { addSessionIndex } from "./auth"; import { setCookie } from "hono/cookie"; @@ -78,6 +78,19 @@ auth2faRoutes.post("/verify", async (c) => { return c.json({ error: "2FA not configured" }, 400); } + // Defence in depth: an old tempToken must not let anyone try email codes on + // an instance that cannot deliver them. + if (method === "email_otp" && !(await isEmailConfigured(c.env))) { + return c.json( + { + error: + "Email delivery is not configured on this site. Please contact an administrator.", + code: "EMAIL_NOT_CONFIGURED", + }, + 503, + ); + } + let verified = false; if (method === "totp" && config.totp_enabled && config.totp_secret) { @@ -181,6 +194,18 @@ auth2faRoutes.post("/otp/send", async (c) => { const { tempToken } = await c.req.json<{ tempToken: string }>(); if (!tempToken) return c.json({ error: "tempToken required" }, 400); + // Checked before the code is generated: no KV write, no send attempt. + if (!(await isEmailConfigured(c.env))) { + return c.json( + { + error: + "Email delivery is not configured on this site. Please contact an administrator.", + code: "EMAIL_NOT_CONFIGURED", + }, + 503, + ); + } + const userId = await c.env.KV.get(`2fa:${tempToken}`); if (!userId) return c.json({ error: "Invalid session" }, 401); @@ -280,6 +305,18 @@ auth2faRoutes.post("/email-otp/send-verify", async (c) => { const userId = c.get("userId"); const prefix = getTablePrefix(c.env); + // Checked before the code is generated: no KV write, no send attempt. + if (!(await isEmailConfigured(c.env))) { + return c.json( + { + error: + "Email delivery is not configured on this site. Please contact an administrator.", + code: "EMAIL_NOT_CONFIGURED", + }, + 503, + ); + } + const user = await findUserById(c.env.DB, prefix, userId); if (!user) return c.json({ error: "User not found" }, 404); @@ -289,7 +326,9 @@ auth2faRoutes.post("/email-otp/send-verify", async (c) => { return c.json({ success: true }); }); -// Email OTP enable — requires verification code if email provider is configured +// Email OTP enable — requires the verification code, and email delivery must +// actually work. (An unconfigured instance used to let this through without a +// code, which is how users ended up with a method that can never log them in.) auth2faRoutes.post("/email-otp/enable", async (c) => { const userId = c.get("userId"); const prefix = getTablePrefix(c.env); @@ -298,15 +337,22 @@ auth2faRoutes.post("/email-otp/enable", async (c) => { .catch(() => ({ code: undefined })); const code = body?.code; - const provider = await getSetting(c.env.DB, prefix, "email_provider"); - - if (provider && provider !== "none") { - if (!code) return c.json({ error: "Verification code required" }, 400); - const valid = await verifyEmailOTP(c.env, userId, code, "email_otp_setup"); - if (!valid) - return c.json({ error: "Invalid or expired verification code" }, 400); + if (!(await isEmailConfigured(c.env))) { + return c.json( + { + error: + "Email delivery is not configured on this site. Please contact an administrator.", + code: "EMAIL_NOT_CONFIGURED", + }, + 503, + ); } + if (!code) return c.json({ error: "Verification code required" }, 400); + const valid = await verifyEmailOTP(c.env, userId, code, "email_otp_setup"); + if (!valid) + return c.json({ error: "Invalid or expired verification code" }, 400); + await upsert2FAConfig(c.env.DB, prefix, userId, { email_otp_enabled: 1 }); return c.json({ success: true }); }); diff --git a/worker/src/services/email.ts b/worker/src/services/email.ts index 40793e2..9e8a553 100644 --- a/worker/src/services/email.ts +++ b/worker/src/services/email.ts @@ -34,6 +34,65 @@ interface ResendConfig { from_name: string; } +/** + * Single source of truth for "can this instance actually deliver email?". + * + * Every place that needs to know whether email sending is available must call + * this instead of reading `email_provider` / the provider config itself. + * + * The verdict mirrors the points where `sendEmail()` is guaranteed to fail: + * - provider unset or "none" → false + * - `resend` → `resend_config` must parse and carry a non-empty `api_key` + * - `smtp` → `smtp_config` must parse and carry a non-empty `host` + * - unparsable config or unknown provider → false + * + * Never throws: a broken setting must not break login / password recovery. + */ +export async function isEmailConfigured(env: Env): Promise { + try { + const prefix = getTablePrefix(env); + const provider = await getSetting(env.DB, prefix, "email_provider"); + + if (!provider || provider === "none") return false; + + if (provider === "resend") { + const config = await readJsonSetting( + env, + prefix, + "resend_config", + ); + return Boolean(config?.api_key); + } + + if (provider === "smtp") { + const config = await readJsonSetting( + env, + prefix, + "smtp_config", + ); + return Boolean(config?.host); + } + + return false; + } catch { + return false; + } +} + +async function readJsonSetting( + env: Env, + prefix: string, + key: string, +): Promise { + const raw = await getSetting(env.DB, prefix, key); + if (!raw) return null; + try { + return JSON.parse(raw) as T; + } catch { + return null; + } +} + export async function sendEmail( env: Env, options: EmailOptions, diff --git a/worker/src/services/twofa.ts b/worker/src/services/twofa.ts index ddd94e5..5f4283c 100644 --- a/worker/src/services/twofa.ts +++ b/worker/src/services/twofa.ts @@ -106,12 +106,23 @@ export async function sendOTPEmail( await sendEmail(env, { to: email, subject, html }); } -export function getAvailable2FAMethods(config: User2FA | null): string[] { +/** + * Projects the user's 2FA switches onto the methods login may offer. + * + * `emailConfigured` comes from `isEmailConfigured()`; pass it `false` and + * `email_otp` is dropped, because an unconfigured instance can never deliver + * the code. Leaving the option out keeps the raw switch view (no filtering). + */ +export function getAvailable2FAMethods( + config: User2FA | null, + options: { emailConfigured?: boolean } = {}, +): string[] { if (!config) return []; const methods: string[] = []; if (config.totp_enabled) methods.push("totp"); if (config.passkey_enabled) methods.push("passkey"); - if (config.email_otp_enabled) methods.push("email_otp"); + if (config.email_otp_enabled && options.emailConfigured !== false) + methods.push("email_otp"); return methods; } diff --git a/worker/test/email-not-configured.test.ts b/worker/test/email-not-configured.test.ts new file mode 100644 index 0000000..9b16d4e --- /dev/null +++ b/worker/test/email-not-configured.test.ts @@ -0,0 +1,648 @@ +/** + * ONE-461 / ONE-466 — email delivery not configured. + * + * Covers the single source of truth (`isEmailConfigured`), the public signal on + * `/api/system/info`, the 2FA login filtering + fail-closed guard, the OTP + * send/verify guards, the forgot-password guard, and the settings-side guards. + * + * Runs against the real worker app (`src/index.ts`) on a real in-memory SQLite + * database seeded from `src/db/schema.sql`, so the SQL under test is the SQL + * that ships. + */ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { hashPassword } from "../src/core/auth"; +import { isEmailConfigured } from "../src/services/email"; +import type { Env } from "../src/types"; +import { type MockKV, makeToken } from "./helpers"; +import { + type BackupResponse, + type BackupTestEnv, + SqliteD1, + callWorker, + jsonPost, + makeBackupEnv, +} from "./support/backup"; + +const NOW = "2026-10-26T10:00:00.000Z"; +const PASSWORD = "correct-horse-battery"; + +// ─── helpers ───────────────────────────────────────────────────────────────── + +let ipSeq = 0; + +/** Fresh budget per request: the rate limiter keys on the client IP. */ +function nextIp(): string { + ipSeq += 1; + return `10.${Math.floor(ipSeq / 250)}.0.${ipSeq % 250}`; +} + +function makeDb(settings: Record = {}): SqliteD1 { + const db = new SqliteD1(); + for (const [key, value] of Object.entries(settings)) { + db.insert("system_settings", { key, value, updated_at: NOW }); + } + return db; +} + +const EMAIL_UNCONFIGURED = { email_provider: "none" }; +const EMAIL_CONFIGURED = { + email_provider: "resend", + resend_config: JSON.stringify({ api_key: "re_test_key" }), +}; + +interface SeedUserOptions { + id: string; + email: string; + totp?: boolean; + passkey?: boolean; + emailOtp?: boolean; +} + +async function seedUser( + db: SqliteD1, + opts: SeedUserOptions, +): Promise<{ passwordHash: string }> { + const passwordHash = await hashPassword(PASSWORD); + db.insert("users", { + id: opts.id, + email: opts.email, + password_hash: passwordHash, + role: "user", + is_active: 1, + email_verified: 1, + language: "en", + created_at: NOW, + updated_at: NOW, + }); + if (opts.totp || opts.passkey || opts.emailOtp) { + db.insert("user_2fa", { + user_id: opts.id, + totp_secret: opts.totp ? "JBSWY3DPEHPK3PXP" : null, + totp_enabled: opts.totp ? 1 : 0, + passkey_credentials: null, + passkey_enabled: opts.passkey ? 1 : 0, + email_otp_enabled: opts.emailOtp ? 1 : 0, + preferred_method: null, + updated_at: NOW, + }); + } + return { passwordHash }; +} + +function kvOf(env: BackupTestEnv): MockKV { + return env.KV as MockKV; +} + +function kvKeysWith(env: BackupTestEnv, prefix: string): string[] { + return [...kvOf(env).store.keys()].filter((key) => key.startsWith(prefix)); +} + +function emailOtpEnabled(db: SqliteD1, userId: string): number | null { + const rows = db.select<{ email_otp_enabled: number }>( + "SELECT email_otp_enabled FROM user_2fa WHERE user_id = ?", + userId, + ); + return rows.length > 0 ? rows[0].email_otp_enabled : null; +} + +/** `Headers.getSetCookie()` is available on Node 22+; fall back to the raw value. */ +function setCookies(res: BackupResponse): string[] { + const headers = res.headers as Headers & { getSetCookie?: () => string[] }; + if (typeof headers.getSetCookie === "function") return headers.getSetCookie(); + const raw = res.headers.get("set-cookie"); + return raw ? [raw] : []; +} + +function post( + env: BackupTestEnv, + path: string, + body: unknown, + headers: Record = {}, +): Promise { + return callWorker( + env, + path, + jsonPost(body, { "cf-connecting-ip": nextIp(), ...headers }), + ); +} + +function authedPost( + env: BackupTestEnv, + path: string, + token: string, + body: unknown, +): Promise { + return post(env, path, body, { Cookie: `access_token=${token}` }); +} + +async function authedToken( + env: BackupTestEnv, + userId: string, + sid = "session-test-1", +): Promise { + kvOf(env).store.set(`ss:${sid}`, userId); + return makeToken("user", { sub: userId, sid }); +} + +/** Resend is the configured provider in the positive cases; never hit the network. */ +function stubOutboundEmail(): void { + vi.stubGlobal( + "fetch", + vi.fn( + async () => + new Response(JSON.stringify({ id: "email-1" }), { status: 200 }), + ), + ); +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +// ─── §2 single source of truth ─────────────────────────────────────────────── + +describe("isEmailConfigured (§2)", () => { + async function configured( + settings: Record, + ): Promise { + const env = makeBackupEnv(makeDb(settings)); + return isEmailConfigured(env as unknown as Env); + } + + it("is false when email_provider is unset", async () => { + expect(await configured({})).toBe(false); + }); + + it("is false when email_provider is none", async () => { + expect(await configured({ email_provider: "none" })).toBe(false); + }); + + it("resend without resend_config / api_key is false", async () => { + expect(await configured({ email_provider: "resend" })).toBe(false); + expect( + await configured({ email_provider: "resend", resend_config: "{}" }), + ).toBe(false); + expect( + await configured({ + email_provider: "resend", + resend_config: JSON.stringify({ api_key: "" }), + }), + ).toBe(false); + }); + + it("resend with an api_key is true", async () => { + expect( + await configured({ + email_provider: "resend", + resend_config: JSON.stringify({ api_key: "re_live" }), + }), + ).toBe(true); + }); + + it("smtp without smtp_config / host is false", async () => { + expect(await configured({ email_provider: "smtp" })).toBe(false); + expect( + await configured({ email_provider: "smtp", smtp_config: "{}" }), + ).toBe(false); + expect( + await configured({ + email_provider: "smtp", + smtp_config: JSON.stringify({ host: "" }), + }), + ).toBe(false); + }); + + it("smtp with a host is true", async () => { + expect( + await configured({ + email_provider: "smtp", + smtp_config: JSON.stringify({ host: "smtp.example.com", port: 587 }), + }), + ).toBe(true); + }); + + it("is false (and does not throw) for broken config JSON", async () => { + expect( + await configured({ + email_provider: "resend", + resend_config: '{"api_key": ', + }), + ).toBe(false); + expect( + await configured({ + email_provider: "smtp", + smtp_config: "not json at all", + }), + ).toBe(false); + }); + + it("is false for an unknown provider", async () => { + expect( + await configured({ + email_provider: "postmark", + resend_config: JSON.stringify({ api_key: "re_live" }), + }), + ).toBe(false); + }); +}); + +// ─── §3.1 public signal ────────────────────────────────────────────────────── + +describe("GET /api/system/info (§3.1)", () => { + it("reports email_configured: true when email delivery works", async () => { + const env = makeBackupEnv(makeDb(EMAIL_CONFIGURED)); + const res = await callWorker(env, "/api/system/info"); + + expect(res.status).toBe(200); + expect(res.body.email_configured).toBe(true); + }); + + it("reports email_configured: false and leaks no provider/config detail", async () => { + const env = makeBackupEnv(makeDb(EMAIL_UNCONFIGURED)); + const res = await callWorker(env, "/api/system/info"); + + expect(res.status).toBe(200); + expect(res.body.email_configured).toBe(false); + expect(Object.keys(res.body).sort()).toEqual([ + "app_name", + "email_configured", + "registration_enabled", + "version", + ]); + expect(res.text).not.toMatch(/provider|smtp|resend|api_key/i); + }); + + it("fails closed when the settings read throws", async () => { + const env = makeBackupEnv(makeDb(EMAIL_CONFIGURED), { + DB: { + prepare() { + throw new Error("D1 unavailable"); + }, + }, + }); + const res = await callWorker(env, "/api/system/info"); + + expect(res.status).toBe(200); + expect(res.body.email_configured).toBe(false); + }); +}); + +// ─── §3.2 login filtering ──────────────────────────────────────────────────── + +describe("POST /auth/login 2FA filtering (§3.2)", () => { + it("drops email_otp from availableMethods when email is not configured", async () => { + const db = makeDb(EMAIL_UNCONFIGURED); + await seedUser(db, { + id: "u-both", + email: "both@example.com", + totp: true, + emailOtp: true, + }); + const env = makeBackupEnv(db); + + const res = await post(env, "/api/auth/login", { + email: "both@example.com", + password: PASSWORD, + }); + + expect(res.status).toBe(200); + expect(res.body.requires2fa).toBe(true); + expect(res.body.availableMethods).toEqual(["totp"]); + expect(kvKeysWith(env, "2fa:")).toEqual([`2fa:${res.body.tempToken}`]); + }); + + it("offers both methods when email is configured", async () => { + const db = makeDb(EMAIL_CONFIGURED); + await seedUser(db, { + id: "u-both", + email: "both@example.com", + totp: true, + emailOtp: true, + }); + const env = makeBackupEnv(db); + + const res = await post(env, "/api/auth/login", { + email: "both@example.com", + password: PASSWORD, + }); + + expect(res.status).toBe(200); + expect(res.body.requires2fa).toBe(true); + expect(res.body.availableMethods).toEqual(["totp", "email_otp"]); + }); +}); + +// ─── §3.3 fail closed when the only enabled method is unavailable ──────────── + +describe("POST /auth/login fail-closed (§3.3)", () => { + it("rejects with 403 2FA_METHOD_UNAVAILABLE and issues no token", async () => { + const db = makeDb(EMAIL_UNCONFIGURED); + await seedUser(db, { + id: "u-emailonly", + email: "emailonly@example.com", + emailOtp: true, + }); + const env = makeBackupEnv(db); + + const res = await post(env, "/api/auth/login", { + email: "emailonly@example.com", + password: PASSWORD, + }); + + expect(res.status).toBe(403); + expect(res.body.code).toBe("2FA_METHOD_UNAVAILABLE"); + expect(res.body.error).toMatch(/two-factor/i); + expect(res.body.tempToken).toBeUndefined(); + expect(res.body.token).toBeUndefined(); + expect(res.body.success).toBeUndefined(); + + const cookies = setCookies(res); + expect(cookies.filter((c) => /access_token|refresh_token/.test(c))).toEqual( + [], + ); + + // Nothing was opened: no tempToken, no session. + expect(kvKeysWith(env, "2fa:")).toEqual([]); + expect(kvKeysWith(env, "ss:")).toEqual([]); + expect(kvKeysWith(env, "rt:")).toEqual([]); + }); + + it("still walks requires2fa when email is configured", async () => { + const db = makeDb(EMAIL_CONFIGURED); + await seedUser(db, { + id: "u-emailonly", + email: "emailonly@example.com", + emailOtp: true, + }); + const env = makeBackupEnv(db); + + const res = await post(env, "/api/auth/login", { + email: "emailonly@example.com", + password: PASSWORD, + }); + + expect(res.status).toBe(200); + expect(res.body.requires2fa).toBe(true); + expect(res.body.availableMethods).toEqual(["email_otp"]); + expect(kvOf(env).store.get(`2fa:${res.body.tempToken}`)).toBe( + "u-emailonly", + ); + }); + + it("leaves the needs2faSetup flow of never-enrolled users untouched", async () => { + const db = makeDb({ ...EMAIL_UNCONFIGURED, require_2fa: "true" }); + await seedUser(db, { id: "u-fresh", email: "fresh@example.com" }); + const env = makeBackupEnv(db); + + const res = await post(env, "/api/auth/login", { + email: "fresh@example.com", + password: PASSWORD, + }); + + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + expect(res.body.needs2faSetup).toBe(true); + }); +}); + +// ─── §3.4 OTP send / verify guards ─────────────────────────────────────────── + +describe("2FA email OTP endpoints (§3.4)", () => { + it("POST /auth/2fa/otp/send is refused before generating a code", async () => { + const db = makeDb(EMAIL_UNCONFIGURED); + await seedUser(db, { + id: "u-2fa", + email: "2fa@example.com", + totp: true, + emailOtp: true, + }); + const env = makeBackupEnv(db); + kvOf(env).store.set("2fa:temp-1", "u-2fa"); + + const res = await post(env, "/api/auth/2fa/otp/send", { + tempToken: "temp-1", + }); + + expect(res.status).toBe(503); + expect(res.body.code).toBe("EMAIL_NOT_CONFIGURED"); + expect(kvKeysWith(env, "otp:")).toEqual([]); + }); + + it("POST /auth/2fa/verify rejects email_otp when email is not configured", async () => { + const db = makeDb(EMAIL_UNCONFIGURED); + await seedUser(db, { + id: "u-2fa", + email: "2fa@example.com", + totp: true, + emailOtp: true, + }); + const env = makeBackupEnv(db); + kvOf(env).store.set("2fa:temp-1", "u-2fa"); + + const res = await post(env, "/api/auth/2fa/verify", { + tempToken: "temp-1", + method: "email_otp", + code: "123456", + }); + + expect(res.status).toBe(503); + expect(res.body.code).toBe("EMAIL_NOT_CONFIGURED"); + // The temp session was not consumed and no session was created. + expect(kvOf(env).store.get("2fa:temp-1")).toBe("u-2fa"); + expect(kvKeysWith(env, "ss:")).toEqual([]); + }); + + it("POST /auth/2fa/verify leaves totp unguarded", async () => { + const db = makeDb(EMAIL_UNCONFIGURED); + await seedUser(db, { + id: "u-2fa", + email: "2fa@example.com", + totp: true, + }); + const env = makeBackupEnv(db); + kvOf(env).store.set("2fa:temp-1", "u-2fa"); + + const res = await post(env, "/api/auth/2fa/verify", { + tempToken: "temp-1", + method: "totp", + code: "000000", + }); + + // Wrong code, but the email guard did not fire: the totp path still runs. + expect(res.status).toBe(401); + expect(res.body.code).toBeUndefined(); + }); + + it("still sends and verifies email codes when email is configured", async () => { + stubOutboundEmail(); + const db = makeDb(EMAIL_CONFIGURED); + await seedUser(db, { + id: "u-2fa", + email: "2fa@example.com", + emailOtp: true, + }); + const env = makeBackupEnv(db); + kvOf(env).store.set("2fa:temp-1", "u-2fa"); + + const sent = await post(env, "/api/auth/2fa/otp/send", { + tempToken: "temp-1", + }); + expect(sent.status).toBe(200); + + const code = kvOf(env).store.get("otp:u-2fa:temp-1"); + expect(code).toMatch(/^\d{6}$/); + + const verified = await post(env, "/api/auth/2fa/verify", { + tempToken: "temp-1", + method: "email_otp", + code, + }); + expect(verified.status).toBe(200); + expect(verified.body.success).toBe(true); + }); +}); + +// ─── §3.5 forgot password ──────────────────────────────────────────────────── + +describe("POST /auth/password/forgot (§3.5)", () => { + it("answers identically for registered and unknown emails, writing nothing", async () => { + const db = makeDb(EMAIL_UNCONFIGURED); + await seedUser(db, { id: "u-known", email: "known@example.com" }); + const env = makeBackupEnv(db); + + const known = await post(env, "/api/auth/password/forgot", { + email: "known@example.com", + }); + const unknown = await post(env, "/api/auth/password/forgot", { + email: "nobody@example.com", + }); + + expect(known.status).toBe(503); + expect(unknown.status).toBe(503); + expect(known.body).toEqual(unknown.body); + expect(known.body.code).toBe("EMAIL_NOT_CONFIGURED"); + expect(known.body.error).toMatch(/not configured/i); + + // No reset code, no cooldown, no failure counter — nothing at all. + expect(kvKeysWith(env, "pwd_reset")).toEqual([]); + expect(kvKeysWith(env, "otp:")).toEqual([]); + }); + + it("keeps the existing anti-enumeration behaviour when email is configured", async () => { + stubOutboundEmail(); + const db = makeDb(EMAIL_CONFIGURED); + await seedUser(db, { id: "u-known", email: "known@example.com" }); + const env = makeBackupEnv(db); + + const known = await post(env, "/api/auth/password/forgot", { + email: "known@example.com", + }); + const unknown = await post(env, "/api/auth/password/forgot", { + email: "nobody@example.com", + }); + + expect(known.status).toBe(200); + expect(known.body).toEqual({ success: true }); + expect(unknown.status).toBe(200); + expect(unknown.body).toEqual({ success: true }); + expect(kvOf(env).store.get("pwd_reset:u-known")).toMatch(/^\d{6}$/); + expect(kvKeysWith(env, "pwd_reset:u-")).toEqual(["pwd_reset:u-known"]); + }); +}); + +// ─── §3.6 settings-side guards ─────────────────────────────────────────────── + +describe("email OTP settings endpoints (§3.6)", () => { + it("refuses send-verify and enable when email is not configured", async () => { + const db = makeDb(EMAIL_UNCONFIGURED); + await seedUser(db, { + id: "u-settings", + email: "settings@example.com", + totp: true, + }); + const env = makeBackupEnv(db); + const token = await authedToken(env, "u-settings"); + + const send = await authedPost( + env, + "/api/auth/2fa/email-otp/send-verify", + token, + {}, + ); + expect(send.status).toBe(503); + expect(send.body.code).toBe("EMAIL_NOT_CONFIGURED"); + expect(kvKeysWith(env, "otp:")).toEqual([]); + + // Neither with nor without a code: the old "skip verification when no + // provider" branch is gone. + const withoutCode = await authedPost( + env, + "/api/auth/2fa/email-otp/enable", + token, + {}, + ); + expect(withoutCode.status).toBe(503); + expect(withoutCode.body.code).toBe("EMAIL_NOT_CONFIGURED"); + + const withCode = await authedPost( + env, + "/api/auth/2fa/email-otp/enable", + token, + { code: "123456" }, + ); + expect(withCode.status).toBe(503); + expect(withCode.body.code).toBe("EMAIL_NOT_CONFIGURED"); + + expect(emailOtpEnabled(db, "u-settings")).toBe(0); + }); + + it("always allows disabling, even when email is not configured", async () => { + const db = makeDb(EMAIL_UNCONFIGURED); + await seedUser(db, { + id: "u-settings", + email: "settings@example.com", + emailOtp: true, + }); + const env = makeBackupEnv(db); + const token = await authedToken(env, "u-settings"); + expect(emailOtpEnabled(db, "u-settings")).toBe(1); + + const res = await authedPost( + env, + "/api/auth/2fa/email-otp/disable", + token, + { password: PASSWORD }, + ); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ success: true }); + expect(emailOtpEnabled(db, "u-settings")).toBe(0); + }); + + it("still enables with a valid code when email is configured", async () => { + stubOutboundEmail(); + const db = makeDb(EMAIL_CONFIGURED); + await seedUser(db, { id: "u-settings", email: "settings@example.com" }); + const env = makeBackupEnv(db); + const token = await authedToken(env, "u-settings"); + + const send = await authedPost( + env, + "/api/auth/2fa/email-otp/send-verify", + token, + {}, + ); + expect(send.status).toBe(200); + + const code = kvOf(env).store.get("otp:u-settings:email_otp_setup"); + const enable = await authedPost( + env, + "/api/auth/2fa/email-otp/enable", + token, + { code }, + ); + + expect(enable.status).toBe(200); + expect(emailOtpEnabled(db, "u-settings")).toBe(1); + }); +});