From b8a1d8db4c5c14cb06600a6cc4131e1ffbf4380e Mon Sep 17 00:00:00 2001 From: Brendan Asselstine Date: Tue, 24 Nov 2026 11:48:47 -0700 Subject: [PATCH] Add optional per-user authenticator two-factor authentication --- package-lock.json | 7 + packages/api-client/src/schema.d.ts | 364 ++++++++++++++++ packages/api/.dev.vars.example | 3 + packages/api/migrations/0105_totp.sql | 38 ++ packages/api/src/api-contract.ts | 8 +- packages/api/src/auth-api.ts | 107 ++++- packages/api/src/google-sign-in.ts | 39 +- packages/api/src/postgres/schema.ts | 28 +- packages/api/src/static-app.ts | 2 +- packages/api/src/totp.ts | 251 +++++++++++ packages/api/src/types.ts | 1 + packages/api/src/worker.ts | 2 + packages/api/test/auth-api.test.ts | 1 + .../api/test/google-sign-in.postgres.test.ts | 47 +- packages/api/test/totp.postgres.test.ts | 162 +++++++ packages/app/package.json | 1 + packages/app/src/features/auth/routes.tsx | 2 +- packages/app/src/features/auth/two-factor.tsx | 163 +++++++ .../app/src/features/settings/navigation.tsx | 1 + packages/app/src/features/settings/routes.tsx | 1 + packages/app/test/functional/auth.spec.mjs | 2 +- .../app/test/functional/two-factor.spec.mjs | 58 +++ packages/docs/llms-full.txt | 21 + packages/docs/openapi.yaml | 402 ++++++++++++++++++ packages/docs/self-hosting/configuration.mdx | 21 + 25 files changed, 1707 insertions(+), 25 deletions(-) create mode 100644 packages/api/migrations/0105_totp.sql create mode 100644 packages/api/src/totp.ts create mode 100644 packages/api/test/totp.postgres.test.ts create mode 100644 packages/app/src/features/auth/two-factor.tsx create mode 100644 packages/app/test/functional/two-factor.spec.mjs diff --git a/package-lock.json b/package-lock.json index fd7bc647..f6365125 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7638,6 +7638,12 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/qrcode-generator": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-2.0.4.tgz", + "integrity": "sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==", + "license": "MIT" + }, "node_modules/react": { "version": "19.3.0", "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz", @@ -10089,6 +10095,7 @@ "@tanstack/react-router": "1.170.41", "@tanstack/react-virtual": "^3.14.14", "factorize-api-client": "0.1.0", + "qrcode-generator": "2.0.4", "react": "19.3.0", "react-dom": "19.3.0", "react-markdown": "^10.1.0" diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 74e6152d..442837c2 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -456,6 +456,126 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/auth/two-factor": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Read your two-factor settings + * @description Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + */ + get: operations["get_api_v1_auth_two_factor"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/two-factor/google": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Confirm a linked Google account for a two-factor settings change + * @description Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + */ + post: operations["post_api_v1_auth_two_factor_google"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/two-factor/enrollment": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Create a short-lived authenticator setup secret + * @description Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + */ + post: operations["post_api_v1_auth_two_factor_enrollment"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/two-factor/enable": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Enable two-factor authentication and show recovery codes once + * @description Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + */ + post: operations["post_api_v1_auth_two_factor_enable"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/two-factor/disable": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Disable two-factor authentication using primary and second factors + * @description Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + */ + post: operations["post_api_v1_auth_two_factor_disable"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/two-factor/challenge": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Finish a browser sign-in using a fresh authenticator or recovery code + * @description Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + */ + post: operations["post_api_v1_auth_two_factor_challenge"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/auth/login": { parameters: { query?: never; @@ -3603,6 +3723,250 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_auth_two_factor: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Success */ + 200: { + headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; + /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ + "X-Factorize-Contract"?: "gen-2157-static-v1"; + [name: string]: unknown; + }; + content: { + "application/json": { + enabled: boolean; + available: boolean; + /** @enum {string} */ + method: "password" | "google" | "unavailable"; + googleVerified: boolean; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_auth_two_factor_google: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Success */ + 200: { + headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; + /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ + "X-Factorize-Contract"?: "gen-2157-static-v1"; + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uri */ + authorizationUrl: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_auth_two_factor_enrollment: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + password?: string; + }; + }; + }; + responses: { + /** @description Success */ + 200: { + headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; + /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ + "X-Factorize-Contract"?: "gen-2157-static-v1"; + [name: string]: unknown; + }; + content: { + "application/json": { + secret: string; + uri: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_auth_two_factor_enable: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + code: string; + }; + }; + }; + responses: { + /** @description Success */ + 200: { + headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; + /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ + "X-Factorize-Contract"?: "gen-2157-static-v1"; + [name: string]: unknown; + }; + content: { + "application/json": { + /** @constant */ + ok: true; + recoveryCodes: string[]; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_auth_two_factor_disable: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + password?: string; + code: string; + }; + }; + }; + responses: { + /** @description Success */ + 200: { + headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; + /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ + "X-Factorize-Contract"?: "gen-2157-static-v1"; + [name: string]: unknown; + }; + content: { + "application/json": { + /** @constant */ + ok: true; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_auth_two_factor_challenge: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + code: string; + }; + }; + }; + responses: { + /** @description Success */ + 200: { + headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; + /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ + "X-Factorize-Contract"?: "gen-2157-static-v1"; + [name: string]: unknown; + }; + content: { + "application/json": { + /** @constant */ + ok: true; + returnTo: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; post_api_v1_auth_login: { parameters: { query?: never; diff --git a/packages/api/.dev.vars.example b/packages/api/.dev.vars.example index 82788e95..458e2778 100644 --- a/packages/api/.dev.vars.example +++ b/packages/api/.dev.vars.example @@ -19,3 +19,6 @@ POSTMARK_MESSAGE_STREAM=outbound # Register /oauth/google/sign-in/callback with Google. GOOGLE_SIGN_IN_CLIENT_ID= GOOGLE_SIGN_IN_CLIENT_SECRET= + +# Optional TOTP secret encryption. Use a separate 32-byte base64 key. +TOTP_ENCRYPTION_KEY= diff --git a/packages/api/migrations/0105_totp.sql b/packages/api/migrations/0105_totp.sql new file mode 100644 index 00000000..057b17a4 --- /dev/null +++ b/packages/api/migrations/0105_totp.sql @@ -0,0 +1,38 @@ +CREATE TABLE app.auth_totp ( + user_id uuid PRIMARY KEY REFERENCES app.auth_users(id) ON DELETE CASCADE, + encrypted_secret text NOT NULL, + last_counter bigint NOT NULL, + enabled_at timestamptz NOT NULL DEFAULT now() +); +CREATE TABLE app.auth_totp_recovery_codes ( + user_id uuid NOT NULL REFERENCES app.auth_totp(user_id) ON DELETE CASCADE, + digest text NOT NULL, + PRIMARY KEY(user_id,digest) +); +CREATE TABLE app.auth_totp_enrollments ( + user_id uuid PRIMARY KEY REFERENCES app.auth_users(id) ON DELETE CASCADE, + browser_digest text NOT NULL, + session_version integer NOT NULL, + encrypted_secret text NOT NULL, + expires_at timestamptz NOT NULL +); +CREATE INDEX auth_totp_enrollments_expiry ON app.auth_totp_enrollments(expires_at); +CREATE TABLE app.auth_totp_challenges ( + digest text PRIMARY KEY, + tenant_id uuid NOT NULL, + user_id uuid NOT NULL, + session_version integer NOT NULL, + return_to text NOT NULL, + expires_at timestamptz NOT NULL, + FOREIGN KEY(tenant_id,user_id) REFERENCES app.members(tenant_id,user_id) ON DELETE CASCADE +); +CREATE INDEX auth_totp_challenges_expiry ON app.auth_totp_challenges(expires_at); +CREATE TABLE app.auth_totp_limits ( + user_id uuid NOT NULL REFERENCES app.auth_users(id) ON DELETE CASCADE, + kind text NOT NULL CHECK (kind IN ('code','settings','challenge')), + attempts integer NOT NULL, + expires_at timestamptz NOT NULL, + PRIMARY KEY(user_id,kind) +); +CREATE INDEX auth_totp_limits_expiry ON app.auth_totp_limits(expires_at); +ALTER TABLE app.google_sign_in_attempts ADD COLUMN totp_settings_version integer; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 3c8452ae..0848b848 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -20,7 +20,7 @@ import { import { X_OAUTH_SCOPES } from "./x-oauth"; import document from "./api-document.json"; -import { authInputs, authSuccess, continuationSuccess, connectionStartInput, connectionStartSuccess, connectionResumeInput, loginSuccess, sessionResponse, googleAvailability, googleStartResult, googlePendingResult, googleUsernameResult, type AuthAction } from "./auth-api"; +import { authInputs, authSuccess, continuationSuccess, connectionStartInput, connectionStartSuccess, connectionResumeInput, loginSuccess, sessionResponse, googleAvailability, googleStartResult, googlePendingResult, googleUsernameResult, totpStatusResponse, totpSetupResponse, totpEnabledResponse, type AuthAction } from "./auth-api"; import { flyConnectionInput, flyConnectionMetadata } from "./fly-account-client"; import { eventDefinitionInput, eventDefinitionUpdate, eventDefinitionResponse, eventDefinitionList, eventOccurrenceQuery, eventOccurrencePage } from "./event-contracts"; import { vmGrantInput, vmGrantList, vmGrantRef, vmGrantResult, vmRevokeResult } from "./vm-grant-contracts"; @@ -241,6 +241,12 @@ export const API_ROUTES: RouteContract[] = [ authRoute("POST", "/api/v1/auth/google/password/complete", "google-password-complete", "Set the Factorize password with fresh Google proof and email confirmation", loginSuccess, authInputs.reset), authRoute("POST", "/api/v1/auth/google/finish", "google-finish", "Choose a username or confirm your existing Factorize password", loginSuccess, authInputs.googleFinish), {...authRoute("POST", "/api/v1/auth/password/set-request", "password-set-request", "Start fresh Google verification before setting or recovering a password", googleStartResult),ownerSession:true}, + {...authRoute("GET", "/api/v1/auth/two-factor", "totp-status", "Read your two-factor settings", totpStatusResponse), ownerSession:true}, + {...authRoute("POST", "/api/v1/auth/two-factor/google", "totp-google", "Confirm a linked Google account for a two-factor settings change", googleStartResult), ownerSession:true}, + {...authRoute("POST", "/api/v1/auth/two-factor/enrollment", "totp-begin", "Create a short-lived authenticator setup secret", totpSetupResponse, authInputs.totpBegin), ownerSession:true}, + {...authRoute("POST", "/api/v1/auth/two-factor/enable", "totp-enable", "Enable two-factor authentication and show recovery codes once", totpEnabledResponse, authInputs.totpEnroll), ownerSession:true}, + {...authRoute("POST", "/api/v1/auth/two-factor/disable", "totp-disable", "Disable two-factor authentication using primary and second factors", authSuccess, authInputs.totpDisable), ownerSession:true}, + authRoute("POST", "/api/v1/auth/two-factor/challenge", "totp-challenge", "Finish a browser sign-in using a fresh authenticator or recovery code", loginSuccess, authInputs.totpCode), authRoute("POST", "/api/v1/auth/login", "login", "Sign in", loginSuccess, authInputs.login), authRoute("POST", "/api/v1/auth/signup", "signup", "Request signup; existing accounts return the same accepted response", authSuccess, authInputs.signup, 202), authRoute("POST", "/api/v1/auth/email-verification/request", "verification-request", "Request email verification", authSuccess, authInputs.request), diff --git a/packages/api/src/auth-api.ts b/packages/api/src/auth-api.ts index 2d9d5d17..246eea03 100644 --- a/packages/api/src/auth-api.ts +++ b/packages/api/src/auth-api.ts @@ -1,3 +1,4 @@ +import { beginTotpEnrollment, beginTotpLogin, clearTotpEnrollCookie, clearTotpLoginCookie, disableTotp, enableTotp, finishTotpLogin, totpStatus } from "./totp"; import { clearGoogleCookie, finishGooglePassword, finishGoogleSignIn, googleEnabled, googlePending, googleUsernameAvailable, redeemGoogleCallback, requestGoogleEmail, startGoogleSignIn, verifyGoogleEmail, type GoogleIdentity } from "./google-sign-in"; import { usernameSchema } from "./usernames"; import { integrationConsentLabels } from "./agent-api"; @@ -27,6 +28,10 @@ export const authInputs = { googleStart: z.object({ returnTo: z.string().max(8192).optional(), connection }).strict(), googleFinish: z.union([z.object({ username: usernameSchema }).strict(), z.object({ password }).strict()]), googleUsername: z.object({ username: usernameSchema }).strict(), + totpBegin: z.object({ password: password.optional() }).strict(), + totpEnroll: z.object({ code: z.string().trim().regex(/^\d{6}$/) }).strict(), + totpCode: z.object({ code: z.string().trim().min(1).max(64) }).strict(), + totpDisable: z.object({ password: password.optional(), code: z.string().trim().min(1).max(64) }).strict(), change: z.object({ currentPassword: password, password }).strict(), }; export const sessionResponse = z.discriminatedUnion("authenticated", [ @@ -52,13 +57,17 @@ export const googlePendingResult = z.object({ email: z.email(), mode: z.enum(["l export const googleUsernameResult = z.object({ available: z.boolean() }); export const loginSuccess = authSuccess.extend({ returnTo: z.string() }); +export const totpStatusResponse = z.object({ enabled: z.boolean(), available: z.boolean(), method: z.enum(["password", "google", "unavailable"]), googleVerified: z.boolean() }); +export const totpSetupResponse = z.object({ secret: z.string(), uri: z.string() }); +export const totpEnabledResponse = authSuccess.extend({ recoveryCodes: z.array(z.string()).length(10) }); + /** Only local application/protocol destinations; never trust a return cookie or form field. */ export function safeReturnTo(value: string | undefined): string { if (!value || !value.startsWith("/") || value.startsWith("//") || /[\\\x00-\x20]/.test(value)) return "/integrations"; try { const url = new URL(value, "https://local.invalid"); if (url.origin !== "https://local.invalid") return "/integrations"; - if (!/^\/(?:authorize|device|integrations|events|vms|app-consent|clients(?:\/[^/]+)?|apps(?:\/registered)?|workloads(?:\/[^/]+)?|triggers(?:\/[^/]+(?:\/(?:edit|settings(?:\/(?:general|context|events))?))?)?|settings(?:\/(?:profile|permissions|apps|integrations|api-keys(?:\/new)?|authorized-clients|password))?)$/.test(url.pathname)) return "/integrations"; + if (!/^\/(?:authorize|device|integrations|events|vms|app-consent|clients(?:\/[^/]+)?|apps(?:\/registered)?|workloads(?:\/[^/]+)?|triggers(?:\/[^/]+(?:\/(?:edit|settings(?:\/(?:general|context|events))?))?)?|settings(?:\/(?:two-factor|profile|permissions|apps|integrations|api-keys(?:\/new)?|authorized-clients|password))?)$/.test(url.pathname)) return "/integrations"; return url.pathname + url.search + url.hash; } catch { return "/integrations"; } } @@ -88,12 +97,63 @@ async function currentSession(request: Request, env: Env): Promise = {}): Promise { // These operations use browser cookies only. Ignore neither a bad bearer nor a // good bearer and silently fall back to a potentially unrelated browser identity. if (request.headers.has("Authorization")) return failure(403, "An interactive browser session is required."); + if (action === "totp-challenge") { + const result = await finishTotpLogin(request, env, authInputs.totpCode.parse(input).code); + if ("status" in result) return failure(result.status, result.message); + let returnTo = result.returnTo; + const next = new URL(returnTo, env.APP_ORIGIN); + const connectionId = ["/authorize", "/device"].includes(next.pathname) ? next.searchParams.get("connection") : null; + if (connectionId) { + const pending = await connectionFor(env, connectionId); + const sameBrowser = pending ? await originalBrowser(request, env, pending) : false; + if (!pending || (pending.user_id && pending.user_id !== result.identity.userId) || + (!sameBrowser && (pending.kind !== "device" || pending.user_id !== result.identity.userId))) { + returnTo = "/auth/login?expired=1"; + } else if (sameBrowser && !await bindInteractiveConnection(env, pending.id, result.identity.userId)) { + returnTo = "/auth/login?expired=1"; + } + } + const response = await issueSession(env, result.identity, { ok: true, returnTo }); + response.headers.append("Set-Cookie", clearTotpLoginCookie(env)); + return response; + } + if (action.startsWith("totp-")) { + const session = await currentSession(request, env); + if (!session) return failure(401, "Sign in to manage two-factor authentication."); + if (action === "totp-status") return authJson(await totpStatus(request, env, session)); + if (action === "totp-google") { + const status = await totpStatus(request, env, session); + if (status.method !== "google") return failure(403, "Confirm your current Factorize password instead."); + const limited = await limitGoogleStart(request, env); + if (limited) return limited; + const { cookie, authorizationUrl } = await startGoogleSignIn(env, "/settings/two-factor", undefined, session.userId, session.sessionVersion); + const response = authJson({ authorizationUrl }); + response.headers.append("Set-Cookie", cookie); + return response; + } + if (action === "totp-begin") { + const result = await beginTotpEnrollment(request, env, session, authInputs.totpBegin.parse(input).password); + if ("status" in result) return failure(result.status, result.message); + const response = authJson({ secret: result.secret, uri: result.uri }); + response.headers.append("Set-Cookie", result.cookie); + return response; + } + if (action === "totp-enable" || action === "totp-disable") { + const result = action === "totp-enable" ? await enableTotp(request, env, session, authInputs.totpEnroll.parse(input).code) + : await disableTotp(request, env, session, authInputs.totpDisable.parse(input)); + if ("status" in result) return failure(result.status, result.message); + // The user proved every required factor in this already signed-in browser. + const response = await issueSession(env, result.identity, "recoveryCodes" in result ? { ok: true, recoveryCodes: result.recoveryCodes } : { ok: true }); + response.headers.append("Set-Cookie", clearTotpEnrollCookie(env)); + return response; + } + } if (action === "google-available") return authJson({ enabled: googleEnabled(env) }); if (action.startsWith("google-")) { if (!googleEnabled(env)) return failure(404, "Google sign-in is not available."); @@ -176,9 +236,13 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env } const member = (await databaseFor(env).pool.query<{ tenant_id: string; session_version: number; email: string }>("SELECT m.tenant_id,m.session_version,u.email FROM app.members m JOIN app.auth_users u ON u.id=m.user_id WHERE m.user_id=$1 AND m.role='owner' AND u.email_verified ORDER BY m.created_at,m.tenant_id LIMIT 1", [pending.user_id])).rows[0]; if (!member || member.session_version !== pending.ready_version) return failure(403, "This verification session was revoked. Sign in again to continue."); + const identity = { userId: pending.user_id, email: member.email, tenantId: member.tenant_id, sessionVersion: member.session_version }; + const handoff = { ok: true, returnTo: connectionDestination(pending) }; + const challenge = await challengeFor(env, identity, handoff.returnTo); + if (challenge) return challenge; const resumed = await databaseFor(env).pool.query("UPDATE app.oauth_connections SET ready=false WHERE id=$1 AND ready=true AND expires_at>now() AND used_at IS NULL RETURNING id", [pending.id]); if (!resumed.rows.length) return authJson({ ok: true, pending: true, clientName: pending.client_name, expiresAt: pending.expires_at.toISOString() }); - return signedIn(env, { userId: pending.user_id, email: member.email, tenantId: member.tenant_id, sessionVersion: member.session_version }, { ok: true, returnTo: connectionDestination(pending) }); + return issueSession(env, identity, handoff); } if (input.connection && ["login", "signup", "verification-request", "reset-request"].includes(action)) { const pending = await connectionFor(env, String(input.connection)); @@ -228,6 +292,7 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env if (action === "logout") { if (session) await new IdentityRepository(databaseFor(env), session.tenantId).revoke(session.userId); const response = authJson({ ok: true }); + response.headers.append("Set-Cookie", clearTotpLoginCookie(env)); response.headers.append("Set-Cookie", sessionCookie(env, "", 0)); return response; } @@ -258,11 +323,13 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env if (member?.role !== "owner" || member.sessionVersion !== identity.sessionVersion) return failure(403, "This account cannot access the workspace."); const pending = identity.connection ? await connectionFor(env, identity.connection) : null; const sameBrowser = pending ? await originalBrowser(request, env, pending) : false; - if (pending && sameBrowser) await databaseFor(env).pool.query("UPDATE app.oauth_connections SET ready=false WHERE id=$1", [pending.id]); const continuation = pending ? pending.kind === "device" || sameBrowser ? { returnTo: connectionDestination(pending) } : { crossBrowser: true } : { returnTo: identity.connection ? "/auth/login?expired=1" : "/integrations" }; - return signedIn(env, identity, { ok: true, ...continuation }); + const challenge = await challengeFor(env, identity, continuation.returnTo ?? "/integrations"); + if (challenge) return challenge; + if (pending && sameBrowser) await databaseFor(env).pool.query("UPDATE app.oauth_connections SET ready=false WHERE id=$1", [pending.id]); + return issueSession(env, identity, { ok: true, ...continuation }); } if ((action === "verification" || action === "reset") && result.status === 200 && "userId" in result.body && result.body.userId && !result.body.tenantId) return failure(403, "This account needs a workspace owner invitation."); // The new public signup contract intentionally does not enumerate accounts. @@ -271,14 +338,21 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env return result.status < 300 ? authJson({ ok: true }) : failure(result.status, "error" in result.body ? result.body.error ?? "Request failed." : "Request failed."); } +async function bindInteractiveConnection(env: Env, id: string, userId: string) { + return !!(await databaseFor(env).pool.query(`UPDATE app.oauth_connections SET user_id=$2,ready=false + WHERE id=$1 AND (user_id IS NULL OR user_id=$2) AND expires_at>now() AND used_at IS NULL RETURNING id`, [id, userId])).rows.length; +} + async function completeInteractiveSignIn(request: Request, env: Env, identity: GoogleIdentity, returnTo: string, connection?: string) { if (connection) { const pending = await connectionFor(env, connection); if (!pending || !await originalBrowser(request, env, pending)) return failure(400, "This connection expired. Restart from your MCP client."); if (pending.user_id && pending.user_id !== identity.userId) return failure(403, "Sign in with the account used for this connection."); - const bound = await databaseFor(env).pool.query("UPDATE app.oauth_connections SET user_id=$2,ready=false WHERE id=$1 AND (user_id IS NULL OR user_id=$2) AND expires_at>now() AND used_at IS NULL RETURNING id", [pending.id, identity.userId]); - if (!bound.rows.length) return failure(400, "This connection expired or belongs to another account. Restart from your MCP client."); returnTo = connectionDestination(pending); + const challenge = await challengeFor(env, identity, returnTo); + if (challenge) return challenge; + if (!await bindInteractiveConnection(env, pending.id, identity.userId)) return failure(400, "This connection expired or belongs to another account. Restart from your MCP client."); + return issueSession(env, identity, { ok: true, returnTo }); } return signedIn(env, identity, { ok: true, returnTo }); } @@ -292,12 +366,13 @@ export async function googleSignInCallback(request: Request, env: Env) { try { const result = await redeemGoogleCallback(request, env); if ("status" in result) return redirect(result.status === 409 ? "/auth/login?google=collision" : result.status === 403 ? "/auth/login?google=account" : "/auth/login?google=failed"); + if ("totpSettings" in result) return redirect("/settings/two-factor"); if ("pending" in result) return redirect("/auth/google"); const signed = await completeInteractiveSignIn(request, env, result.identity, result.returnTo, result.connection); if (!signed.ok) return redirect("/auth/login?google=connection"); const { returnTo } = loginSuccess.parse(await signed.json()); const response = redirect(returnTo); - response.headers.append("Set-Cookie", signed.headers.get("Set-Cookie")!); + for (const value of signed.headers.getSetCookie()) response.headers.append("Set-Cookie", value); response.headers.append("Set-Cookie", clearGoogleCookie(env)); return response; } catch { @@ -306,7 +381,21 @@ export async function googleSignInCallback(request: Request, env: Env) { } } -async function signedIn(env: Env, identity: { tenantId: string; userId: string; email: string; sessionVersion: number }, body: unknown) { +async function challengeFor(env: Env, identity: GoogleIdentity, returnTo: string) { + const challenge = await beginTotpLogin(env, identity, returnTo); + if (challenge === null) return null; + if (challenge === false) return failure(429, "Too many two-factor requests. Wait five minutes and try again."); + const response = authJson({ ok: true, returnTo: "/auth/two-factor" }); + response.headers.append("Set-Cookie", sessionCookie(env, "", 0)); + response.headers.append("Set-Cookie", challenge); + return response; +} + +async function signedIn(env: Env, identity: GoogleIdentity, body: { ok?: boolean; returnTo?: string; crossBrowser?: boolean }) { + return await challengeFor(env, identity, body.returnTo ?? "/integrations") ?? issueSession(env, identity, body); +} + +async function issueSession(env: Env, identity: GoogleIdentity, body: unknown) { const lifetime = 7 * 24 * 60 * 60; const response = authJson(body); response.headers.append("Set-Cookie", sessionCookie(env, await signSession({ tenantId: identity.tenantId, userId: identity.userId, email: identity.email, sessionVersion: identity.sessionVersion, exp: Math.floor(Date.now() / 1000) + lifetime }, env.SESSION_SIGNING_SECRET), lifetime)); diff --git a/packages/api/src/google-sign-in.ts b/packages/api/src/google-sign-in.ts index 9e9b5cde..ee90f7b0 100644 --- a/packages/api/src/google-sign-in.ts +++ b/packages/api/src/google-sign-in.ts @@ -2,7 +2,7 @@ import { serialize } from "hono/utils/cookie"; import { z } from "zod"; import { hashPassword, normalizeEmail, tokenDigest, verifyPassword } from "./auth"; import { sendAuthEmail } from "./auth-email"; -import { requestCookie } from "./session"; +import { requestCookie, type Session } from "./session"; import { databaseFor, type DatabaseClient } from "./postgres/database"; import { AuthRepository } from "./postgres/auth-repository"; import { createJwksResolver } from "./vm-oidc"; @@ -27,7 +27,7 @@ const redirectUri = (env: Env) => new URL(googleCallbackPath, env.APP_ORIGIN).hr type Attempt = { id: string; browser_digest: string; verifier: string | null; nonce: string; return_to: string; connection_id: string | null; google_subject: string | null; email: string | null; existing_user_id: string | null; email_confirmed: boolean; password_attempts: number; - password_user_id: string | null; recovery_revision: number | null; provider_managed_email: boolean; provider_observed_at: number; + password_user_id: string | null; recovery_revision: number | null; provider_managed_email: boolean; provider_observed_at: number; totp_settings_version: number | null; }; export type GoogleIdentity = { userId: string; tenantId: string; email: string; sessionVersion: number }; const fail = (status: number, message: string) => ({ status, message } as const); @@ -38,13 +38,13 @@ async function digestFor(request: Request, env: Env) { return browser && /^[A-Za-z0-9_-]{43}$/.test(browser) ? tokenDigest(browser, env.SESSION_SIGNING_SECRET) : null; } -export async function startGoogleSignIn(env: Env, returnTo: string, connectionId?: string, passwordUserId?: string) { +export async function startGoogleSignIn(env: Env, returnTo: string, connectionId?: string, passwordUserId?: string, totpSettingsVersion?: number) { const db = databaseFor(env); const id = crypto.randomUUID(), browser = random(), verifier = random(), nonce = random(); await db.pool.query(`INSERT INTO app.google_sign_in_attempts - (id,browser_digest,verifier,nonce,return_to,connection_id,password_user_id,expires_at) - VALUES($1,$2,$3,$4,$5,$6,$7,now()+interval '10 minutes')`, - [id, await tokenDigest(browser, env.SESSION_SIGNING_SECRET), verifier, nonce, returnTo, connectionId ?? null, passwordUserId ?? null]); + (id,browser_digest,verifier,nonce,return_to,connection_id,password_user_id,totp_settings_version,expires_at) + VALUES($1,$2,$3,$4,$5,$6,$7,$8,now()+interval '10 minutes')`, + [id, await tokenDigest(browser, env.SESSION_SIGNING_SECRET), verifier, nonce, returnTo, connectionId ?? null, passwordUserId ?? null, totpSettingsVersion ?? null]); const target = new URL(authorizationUrl); target.search = new URLSearchParams({ client_id: env.GOOGLE_SIGN_IN_CLIENT_ID!, redirect_uri: redirectUri(env), response_type: "code", scope: "openid email", @@ -54,6 +54,17 @@ export async function startGoogleSignIn(env: Env, returnTo: string, connectionId return { authorizationUrl: target.href, cookie: secureCookie(env, browser, maxAge) }; } +export async function googleTotpProof(sql: DatabaseClient, request: Request, env: Env, session: Session, consume = false) { + const digest = await digestFor(request, env); + if (!digest) return false; + const where = `WHERE browser_digest=$1 AND password_user_id=$2 AND totp_settings_version=$3 + AND google_subject IS NOT NULL AND verifier IS NULL AND expires_at>clock_timestamp()`; + const result = await sql.query(consume + ? `DELETE FROM app.google_sign_in_attempts ${where} RETURNING id` + : `SELECT id FROM app.google_sign_in_attempts ${where}`, [digest, session.userId, session.sessionVersion]); + return !!result.rows.length; +} + export async function clearExpiredGoogleSignIns(sql: DatabaseClient) { await sql.query(`DELETE FROM app.google_sign_in_attempts WHERE id IN (SELECT id FROM app.google_sign_in_attempts WHERE expires_at(`SELECT user_id FROM app.auth_accounts WHERE provider='google' AND provider_account_id=$1`, [google.subject])).rows[0]; if (attempt.password_user_id && linked?.user_id !== attempt.password_user_id) return fail(403, "Use the Google account linked to your Factorize account."); + if (linked && attempt.totp_settings_version !== null) { + return db.transaction(async sql => { + // Use the same user-before-proof lock order as security settings. + await sql.query("SELECT id FROM app.auth_users WHERE id=$1 FOR UPDATE", [linked.user_id]); + await syncGoogleRecovery(sql, linked.user_id, google); + const verified = await sql.query(`UPDATE app.google_sign_in_attempts SET google_subject=$2 + WHERE id=$1 AND expires_at>clock_timestamp() AND EXISTS (SELECT 1 FROM app.members + WHERE user_id=$3 AND session_version=$4 AND role='owner') RETURNING id`, + [attempt.id, google.subject, linked.user_id, attempt.totp_settings_version]); + return verified.rowCount ? { totpSettings: true as const } : expired(); + }); + } if (linked) { return db.transaction(async sql => { // Lock attempt before user, consistent with both password setup and linking. @@ -213,7 +236,7 @@ export async function redeemGoogleCallback(request: Request, env: Env) { async function pendingAttempt(db: DatabaseClient, digest: string, lock = false) { return (await db.query(`SELECT * FROM app.google_sign_in_attempts - WHERE browser_digest=$1 AND google_subject IS NOT NULL AND expires_at>clock_timestamp() + WHERE browser_digest=$1 AND totp_settings_version IS NULL AND google_subject IS NOT NULL AND expires_at>clock_timestamp() AND (password_user_id IS NULL OR EXISTS (SELECT 1 FROM app.auth_users WHERE id=password_user_id AND google_recovery_revision=recovery_revision))${lock ? " FOR UPDATE" : ""}`, [digest])).rows[0]; } export async function googlePending(request: Request, env: Env) { @@ -228,7 +251,7 @@ export async function requestGoogleEmail(request: Request, env: Env) { const token = random(), digest = await tokenDigest(token, env.SESSION_SIGNING_SECRET); const attempt = (await db.pool.query<{ email: string; password_user_id: string | null }>(`UPDATE app.google_sign_in_attempts SET email_token_digest=$2,email_sent_at=clock_timestamp() - WHERE browser_digest=$1 AND google_subject IS NOT NULL AND existing_user_id IS NULL AND NOT email_confirmed + WHERE browser_digest=$1 AND totp_settings_version IS NULL AND google_subject IS NOT NULL AND existing_user_id IS NULL AND NOT email_confirmed AND (password_user_id IS NULL OR EXISTS (SELECT 1 FROM app.auth_users WHERE id=password_user_id AND google_recovery_revision=recovery_revision)) AND expires_at>clock_timestamp() AND (email_sent_at IS NULL OR email_sent_at oauthConnections.id, { onDelete: "cascade" }), googleSubject: text("google_subject"), email: text("email"), existingUserId: uuid("existing_user_id").references(() => authUsers.id, { onDelete: "cascade" }), emailConfirmed: boolean("email_confirmed").notNull().default(false), emailTokenDigest: text("email_token_digest"), emailSentAt: timestamp("email_sent_at", { withTimezone: true }), - passwordUserId: uuid("password_user_id").references(() => authUsers.id, { onDelete: "cascade" }), recoveryRevision: integer("recovery_revision"), providerObservedAt: integer("provider_observed_at").notNull().default(0), providerManagedEmail: boolean("provider_managed_email").notNull().default(false), + passwordUserId: uuid("password_user_id").references(() => authUsers.id, { onDelete: "cascade" }), totpSettingsVersion: integer("totp_settings_version"), recoveryRevision: integer("recovery_revision"), providerObservedAt: integer("provider_observed_at").notNull().default(0), providerManagedEmail: boolean("provider_managed_email").notNull().default(false), passwordAttempts: integer("password_attempts").notNull().default(0), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), }, t => [index("google_sign_in_attempts_expiry").on(t.expiresAt)]); export const oauthConsentPreviews = app.table("oauth_consent_previews", { id: uuid("id").primaryKey(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), usedAt: timestamp("used_at", { withTimezone: true }) }, t => [index("oauth_consent_previews_expires").on(t.expiresAt)]); @@ -45,6 +45,30 @@ export const oauthDeviceAuthorizations = app.table("oauth_device_authorizations" export const members = app.table("members", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), userId: uuid("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), email: text("email").notNull(), role: text("role").$type<"owner" | "member">().notNull(), sessionVersion: integer("session_version").notNull().default(1), createdAt: createdAt(), }, t => [primaryKey({ columns: [t.tenantId, t.userId] }), check("members_role_check", sql`${t.role} in ('owner','member')`), check("members_session_version_check", sql`${t.sessionVersion} > 0`)]); +export const authTotp = app.table("auth_totp", { + userId: uuid("user_id").primaryKey().references(() => authUsers.id, { onDelete: "cascade" }), encryptedSecret: text("encrypted_secret").notNull(), + lastCounter: bigint("last_counter", { mode: "bigint" }).notNull(), enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(), +}); +export const authTotpRecoveryCodes = app.table("auth_totp_recovery_codes", { + userId: uuid("user_id").notNull().references(() => authTotp.userId, { onDelete: "cascade" }), digest: text("digest").notNull(), +}, t => [primaryKey({ columns: [t.userId, t.digest] })]); +export const authTotpEnrollments = app.table("auth_totp_enrollments", { + userId: uuid("user_id").primaryKey().references(() => authUsers.id, { onDelete: "cascade" }), browserDigest: text("browser_digest").notNull(), + sessionVersion: integer("session_version").notNull(), encryptedSecret: text("encrypted_secret").notNull(), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), +}, t => [index("auth_totp_enrollments_expiry").on(t.expiresAt)]); +export const authTotpChallenges = app.table("auth_totp_challenges", { + digest: text("digest").primaryKey(), tenantId: uuid("tenant_id").notNull(), userId: uuid("user_id").notNull(), + sessionVersion: integer("session_version").notNull(), returnTo: text("return_to").notNull(), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), +}, t => [foreignKey({ columns: [t.tenantId, t.userId], foreignColumns: [members.tenantId, members.userId] }).onDelete("cascade"), + index("auth_totp_challenges_expiry").on(t.expiresAt)]); +export const authTotpLimits = app.table("auth_totp_limits", { + userId: uuid("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), + kind: text("kind").$type<"code" | "settings" | "challenge">().notNull(), attempts: integer("attempts").notNull(), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), +}, t => [primaryKey({ columns: [t.userId, t.kind] }), check("auth_totp_limits_kind_check", sql`${t.kind} IN ('code','settings','challenge')`), + index("auth_totp_limits_expiry").on(t.expiresAt)]); export const accessTokens = app.table("access_tokens", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), name: text("name").notNull(), digest: text("digest").notNull().unique(), userId: uuid("user_id").notNull(), sessionVersion: integer("session_version").notNull(), scopes: jsonb("scopes").$type().notNull().default([]), createdAt: createdAt(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), lastUsedAt: timestamp("last_used_at", { withTimezone: true }), revokedAt: timestamp("revoked_at", { withTimezone: true }), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), foreignKey({ columns: [t.tenantId, t.userId], foreignColumns: [members.tenantId, members.userId] }).onDelete("cascade"), index("access_tokens_expiration").on(t.expiresAt,t.tenantId,t.id)]); @@ -192,7 +216,7 @@ export const triggerSourceRelations = relations(triggerSources, ({ one }) => ({ })); export const databaseSchema = { - teamSettings, schemaMigrations, tenants, oauthConnections, googleSignInAttempts, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, + teamSettings, schemaMigrations, tenants, oauthConnections, googleSignInAttempts, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, authTotp, authTotpRecoveryCodes, authTotpEnrollments, authTotpChallenges, authTotpLimits, accessTokens, connections, agentIntegrations, agentIdentities, agentProxyResponses, integrationCollections, integrationRecords, integrationChanges, linearWorkspaces, githubInstallations, githubSetupStates, eventDefinitions, eventDefinitionRevisions, eventOccurrences, mcpEventSubscriptions, mcpEventDeliveries, triggerMatches, triggers, triggerSources, webhookConditionsCutover, scheduleState, triggerEditDeliveries, triggerEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, tenantRelations, triggerRelations, triggerSourceRelations, diff --git a/packages/api/src/static-app.ts b/packages/api/src/static-app.ts index c9c9920f..e31ca623 100644 --- a/packages/api/src/static-app.ts +++ b/packages/api/src/static-app.ts @@ -2,7 +2,7 @@ import type { Env } from "./types"; export const STATIC_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'"; // Browser auth screens share /auth with backend callbacks and form handlers. -const authPages = new Set(["/auth/login", "/auth/google", "/auth/signup", "/auth/password-reset", "/auth/verify", "/auth/verify/request"]); +const authPages = new Set(["/auth/login", "/auth/google", "/auth/two-factor", "/auth/signup", "/auth/password-reset", "/auth/verify", "/auth/verify/request"]); const backendNamespaces = ["/api", "/healthz", "/auth", "/oauth", "/webhooks", "/internal", "/mcp", "/.well-known"]; function isBackendNamespace(path: string) { return backendNamespaces.some(namespace => path === namespace || path.startsWith(`${namespace}/`)); diff --git a/packages/api/src/totp.ts b/packages/api/src/totp.ts new file mode 100644 index 00000000..e2407d16 --- /dev/null +++ b/packages/api/src/totp.ts @@ -0,0 +1,251 @@ +import { serialize } from "hono/utils/cookie"; +import { tokenDigest, verifyPassword } from "./auth"; +import { decrypt, encrypt } from "./crypto"; +import { requestCookie, type Session } from "./session"; +import { databaseFor, type DatabaseClient } from "./postgres/database"; +import { googleEnabled, googleTotpProof } from "./google-sign-in"; +import type { Env } from "./types"; + +const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; +const encoder = new TextEncoder(); +const ttlSeconds = 300; +const token = () => binaryBase32(crypto.getRandomValues(new Uint8Array(32))); +const codePattern = /^\d{6}$/; +const recoveryPattern = /^[A-Z2-7]{26}$/; +const fail = (status: number, message: string) => ({ status, message } as const); +const expired = () => fail(400, "This two-factor request expired. Start again."); +const incorrect = () => fail(401, "The code is incorrect or has already been used."); +const throttled = () => fail(429, "Too many attempts. Wait five minutes and try again."); + +function binaryBase32(bytes: Uint8Array) { + let value = 0, bits = 0, output = ""; + for (const byte of bytes) { + value = (value << 8) | byte; + bits += 8; + while (bits >= 5) output += alphabet[(value >> (bits -= 5)) & 31]; + } + if (bits) output += alphabet[(value << (5 - bits)) & 31]; + return output; +} + +function bytesFromBase32(value: string) { + let buffer = 0, bits = 0; + const bytes = new Uint8Array(Math.floor(value.length * 5 / 8)); + let i = 0; + for (const character of value) { + const digit = alphabet.indexOf(character); + if (digit === -1) throw new Error("Invalid TOTP secret"); + buffer = (buffer << 5) | digit; + bits += 5; + if (bits >= 8) bytes[i++] = (buffer >> (bits -= 8)) & 255; + } + return bytes; +} + +export async function totpAt(secret: string, counter: number) { + const key = await crypto.subtle.importKey("raw", bytesFromBase32(secret), { name: "HMAC", hash: "SHA-1" }, false, ["sign"]); + const bytes = new Uint8Array(8); + new DataView(bytes.buffer).setBigUint64(0, BigInt(counter)); + const digest = new Uint8Array(await crypto.subtle.sign("HMAC", key, bytes)); + const offset = digest[digest.length - 1] & 15; + const truncated = new DataView(digest.buffer).getUint32(offset) & 0x7fffffff; + return (truncated % 1_000_000).toString().padStart(6, "0"); +} + +const counterNow = () => Math.floor(Date.now() / 30_000); +async function matchingCounter(secret: string, code: string, lastCounter: number) { + if (!codePattern.test(code)) return null; + const now = counterNow(); + // Prefer the newest match if two adjacent windows happen to share digits. + const counters = [now + 1, now, now - 1]; + const candidates = await Promise.all(counters.map(counter => totpAt(secret, counter))); + return counters.find((counter, index) => counter > lastCounter && candidates[index] === code) ?? null; +} + +export function totpKey(env: Env) { + const value = env.TOTP_ENCRYPTION_KEY?.trim(); + try { + if (!value || atob(value).length !== 32 || (env.CREDENTIAL_ENCRYPTION_KEY && atob(env.CREDENTIAL_ENCRYPTION_KEY) === atob(value))) return null; + return value; + } catch { return null; } +} + +const isHttps = (env: Env) => new URL(env.APP_ORIGIN).protocol === "https:"; +const cookieName = (env: Env, purpose: string) => (isHttps(env) ? "__Host-" : "") + "factorize_totp_" + purpose; +const cookie = (env: Env, purpose: string, value: string, maxAge: number) => serialize(cookieName(env, purpose), value, { + httpOnly: true, secure: isHttps(env), sameSite: "Lax", path: "/", maxAge, +}); +export const clearTotpLoginCookie = (env: Env) => cookie(env, "login", "", 0); +export const clearTotpEnrollCookie = (env: Env) => cookie(env, "enroll", "", 0); +async function browserDigest(request: Request, env: Env, purpose: string) { + const value = requestCookie(request, cookieName(env, purpose)); + return value && /^[A-Z2-7]{52}$/.test(value) ? tokenDigest("totp:" + purpose + ":" + value, env.SESSION_SIGNING_SECRET) : null; +} +const digestNew = (env: Env, purpose: string, value: string) => tokenDigest("totp:" + purpose + ":" + value, env.SESSION_SIGNING_SECRET); +async function recoveryDigest(userId: string, code: string) { + // 128 random bits per code make an offline dictionary impractical without + // tying recovery to the deployment encryption key or its rotation. + const bytes = await crypto.subtle.digest("SHA-256", encoder.encode("totp-recovery:" + userId + ":" + code)); + return binaryBase32(new Uint8Array(bytes)); +} + +type Identity = { userId: string; tenantId: string; sessionVersion: number; email: string }; +type Totp = { encrypted_secret: string; last_counter: string }; +type Challenge = { user_id: string; tenant_id: string; session_version: number; return_to: string }; +const lockUser = (sql: DatabaseClient, userId: string) => sql.query("SELECT id FROM app.auth_users WHERE id=$1 FOR UPDATE", [userId]); +async function member(sql: DatabaseClient, identity: Omit) { + return (await sql.query<{ email: string }>(`SELECT u.email FROM app.members m JOIN app.auth_users u ON u.id=m.user_id + WHERE m.tenant_id=$1 AND m.user_id=$2 AND m.session_version=$3 AND m.role='owner' AND u.email_verified`, + [identity.tenantId, identity.userId, identity.sessionVersion])).rows[0]; +} +async function active(sql: DatabaseClient, id: string) { + return (await sql.query("SELECT encrypted_secret,last_counter FROM app.auth_totp WHERE user_id=$1", [id])).rows[0]; +} +async function takeAttempt(sql: DatabaseClient, userId: string, kind: "code" | "settings" | "challenge") { + const limit = kind === "code" ? 10 : kind === "challenge" ? 15 : 5; + return !!(await sql.query(`INSERT INTO app.auth_totp_limits AS l(user_id,kind,attempts,expires_at) + VALUES($1,$2,1,clock_timestamp()+interval '5 minutes') + ON CONFLICT(user_id,kind) DO UPDATE SET attempts=CASE WHEN l.expires_at<=clock_timestamp() THEN 1 ELSE l.attempts+1 END, + expires_at=CASE WHEN l.expires_at<=clock_timestamp() THEN excluded.expires_at ELSE l.expires_at END + WHERE l.expires_at<=clock_timestamp() OR l.attempts<$3 RETURNING attempts`, [userId, kind, limit])).rowCount; +} + +async function useCode(sql: DatabaseClient, env: Env, userId: string, config: Totp, supplied: string) { + const code = supplied.replace(/[ -]/g, "").toUpperCase(); + if (recoveryPattern.test(code)) { + const result = await sql.query("DELETE FROM app.auth_totp_recovery_codes WHERE user_id=$1 AND digest=$2 RETURNING digest", [userId, await recoveryDigest(userId, code)]); + return result.rowCount === 1; + } + const key = totpKey(env); + if (!key || !codePattern.test(code)) return false; + const match = await matchingCounter(await decrypt(config.encrypted_secret, key), code, Number(config.last_counter)); + if (match === null) return false; + return (await sql.query("UPDATE app.auth_totp SET last_counter=$2 WHERE user_id=$1 AND last_counter<$2 RETURNING user_id", [userId, match])).rowCount === 1; +} + +export async function beginTotpLogin(env: Env, identity: Identity, returnTo: string) { + const db = databaseFor(env); + if (!await active(db.pool, identity.userId)) return null; + if (!await takeAttempt(db.pool, identity.userId, "challenge")) return false; + const value = token(); + await db.pool.query(`INSERT INTO app.auth_totp_challenges(digest,tenant_id,user_id,session_version,return_to,expires_at) + VALUES($1,$2,$3,$4,$5,clock_timestamp()+interval '5 minutes')`, [ + await digestNew(env, "login", value), identity.tenantId, identity.userId, identity.sessionVersion, returnTo, + ]); + return cookie(env, "login", value, ttlSeconds); +} +export async function finishTotpLogin(request: Request, env: Env, code: string) { + const digest = await browserDigest(request, env, "login"); + if (!digest) return expired(); + return databaseFor(env).transaction(async sql => { + const attempt = (await sql.query(`SELECT tenant_id,user_id,session_version,return_to FROM app.auth_totp_challenges + WHERE digest=$1 AND expires_at>clock_timestamp() FOR UPDATE`, [digest])).rows[0]; + if (!attempt) return expired(); + const partial = { userId: attempt.user_id, tenantId: attempt.tenant_id, sessionVersion: attempt.session_version }; + await lockUser(sql, partial.userId); + const owner = await member(sql, partial); + const config = await active(sql, partial.userId); + if (!owner || !config) return expired(); + if (!await takeAttempt(sql, partial.userId, "code")) return throttled(); + if (!await useCode(sql, env, partial.userId, config, code)) return incorrect(); + await sql.query("DELETE FROM app.auth_totp_challenges WHERE digest=$1", [digest]); + return { identity: { ...partial, email: owner.email }, returnTo: attempt.return_to }; + }); +} + +export async function totpStatus(request: Request, env: Env, session: Session) { + const db = databaseFor(env); + const row = (await db.pool.query<{ has_password: boolean; has_google: boolean }>(`SELECT + EXISTS(SELECT 1 FROM app.auth_accounts WHERE user_id=$1 AND provider='credential' AND password_hash IS NOT NULL) has_password, + EXISTS(SELECT 1 FROM app.auth_accounts WHERE user_id=$1 AND provider='google') has_google`, [session.userId])).rows[0]!; + const config = await active(db.pool, session.userId); + const method = row.has_password ? "password" : row.has_google && googleEnabled(env) ? "google" : "unavailable"; + return { enabled: !!config, available: !!totpKey(env), method, googleVerified: method === "google" && await googleTotpProof(db.pool, request, env, session) }; +} + +async function confirmPrimary(sql: DatabaseClient, request: Request, env: Env, session: Session, password?: string) { + const row = (await sql.query<{ password_hash: string }>("SELECT password_hash FROM app.auth_accounts WHERE user_id=$1 AND provider='credential' AND password_hash IS NOT NULL", [session.userId])).rows[0]; + if (row) return !!password && await verifyPassword(password, row.password_hash); + return !password && googleEnabled(env) && await googleTotpProof(sql, request, env, session); +} + +async function advanceSessions(sql: DatabaseClient, session: Session) { + const updated = (await sql.query<{ tenant_id: string; session_version: number }>("UPDATE app.members SET session_version=session_version+1 WHERE user_id=$1 RETURNING tenant_id,session_version", [session.userId])).rows; + await sql.query("UPDATE app.auth_sessions SET revoked_at=clock_timestamp() WHERE user_id=$1 AND revoked_at IS NULL", [session.userId]); + const next = updated.find(row => row.tenant_id === session.tenantId)!; + return { userId: session.userId, tenantId: session.tenantId, email: session.email, sessionVersion: next.session_version }; +} + +export async function beginTotpEnrollment(request: Request, env: Env, session: Session, password?: string) { + const key = totpKey(env); + if (!key) return fail(503, "Two-factor enrollment is not configured."); + return databaseFor(env).transaction(async sql => { + await lockUser(sql, session.userId); + if (!await member(sql, session)) return expired(); + if (await active(sql, session.userId)) return fail(409, "Two-factor authentication is already enabled."); + if (!await takeAttempt(sql, session.userId, "settings")) return throttled(); + if (!await confirmPrimary(sql, request, env, session, password)) return fail(401, "Confirm your current password or your linked Google account."); + if (!password && !await googleTotpProof(sql, request, env, session, true)) return expired(); + const secret = binaryBase32(crypto.getRandomValues(new Uint8Array(20))); + const value = token(); + await sql.query(`INSERT INTO app.auth_totp_enrollments(user_id,browser_digest,session_version,encrypted_secret,expires_at) + VALUES($1,$2,$3,$4,clock_timestamp()+interval '5 minutes') + ON CONFLICT(user_id) DO UPDATE SET browser_digest=excluded.browser_digest,session_version=excluded.session_version, + encrypted_secret=excluded.encrypted_secret,expires_at=excluded.expires_at`, [ + session.userId, await digestNew(env, "enroll", value), session.sessionVersion, await encrypt(secret, key), + ]); + const uri = new URL("otpauth://totp/Factorize:" + encodeURIComponent(session.email)); + uri.search = new URLSearchParams({ secret, issuer: "Factorize", algorithm: "SHA1", digits: "6", period: "30" }).toString(); + return { secret, uri: uri.href, cookie: cookie(env, "enroll", value, ttlSeconds) }; + }); +} + +export async function enableTotp(request: Request, env: Env, session: Session, code: string) { + const key = totpKey(env); + const digest = await browserDigest(request, env, "enroll"); + if (!key || !digest) return expired(); + return databaseFor(env).transaction(async sql => { + await lockUser(sql, session.userId); + if (!await member(sql, session)) return expired(); + const pending = (await sql.query<{ encrypted_secret: string }>(`SELECT encrypted_secret FROM app.auth_totp_enrollments + WHERE user_id=$1 AND browser_digest=$2 AND session_version=$3 AND expires_at>clock_timestamp() FOR UPDATE`, + [session.userId, digest, session.sessionVersion])).rows[0]; + if (!pending || await active(sql, session.userId)) return expired(); + if (!await takeAttempt(sql, session.userId, "code")) return throttled(); + const counter = await matchingCounter(await decrypt(pending.encrypted_secret, key), code, -1); + if (counter === null) return incorrect(); + await sql.query("INSERT INTO app.auth_totp(user_id,encrypted_secret,last_counter) VALUES($1,$2,$3)", [session.userId, pending.encrypted_secret, counter]); + const codes = Array.from({ length: 10 }, () => binaryBase32(crypto.getRandomValues(new Uint8Array(16)))); + const digests = await Promise.all(codes.map(code => recoveryDigest(session.userId, code))); + await sql.query("INSERT INTO app.auth_totp_recovery_codes(user_id,digest) SELECT $1,unnest($2::text[])", [session.userId, digests]); + await sql.query("DELETE FROM app.auth_totp_enrollments WHERE user_id=$1", [session.userId]); + const identity = await advanceSessions(sql, session); + return { identity, recoveryCodes: codes.map(code => code.match(/.{1,5}/g)!.join("-")) }; + }); +} + +export async function disableTotp(request: Request, env: Env, session: Session, input: { password?: string; code: string }) { + return databaseFor(env).transaction(async sql => { + await lockUser(sql, session.userId); + if (!await member(sql, session)) return expired(); + const config = await active(sql, session.userId); + if (!config) return fail(409, "Two-factor authentication is not enabled."); + if (!await takeAttempt(sql, session.userId, "settings")) return throttled(); + if (!await confirmPrimary(sql, request, env, session, input.password)) return fail(401, "Confirm your current password or your linked Google account."); + if (!await takeAttempt(sql, session.userId, "code")) return throttled(); + if (!await useCode(sql, env, session.userId, config, input.code)) return incorrect(); + if (!input.password && !await googleTotpProof(sql, request, env, session, true)) throw new Error("Google verification expired during two-factor change."); + await sql.query("DELETE FROM app.auth_totp WHERE user_id=$1", [session.userId]); + return { identity: await advanceSessions(sql, session) }; + }); +} + +export async function pruneTotp(sql: DatabaseClient) { + await sql.query(`DELETE FROM app.auth_totp_challenges WHERE digest IN + (SELECT digest FROM app.auth_totp_challenges WHERE expires_at { it("creates an HttpOnly Secure Lax cookie, returns a safe destination and never exposes signing/session data", async () => { vi.spyOn(AuthRepository.prototype, "login").mockResolvedValue({ status: 200, body: identity }); vi.spyOn(IdentityRepository.prototype, "member").mockResolvedValue(member); + vi.mocked(env.DATABASE!.pool.query).mockResolvedValueOnce({ rows: [] } as never); const response = await call("/api/v1/auth/login", { email: "owner@test.com", password: "long-test-password", returnTo: "https://evil.test/" }); expect(response.status).toBe(200); expect(response.headers.get("Set-Cookie")).toMatch(/factorize_session=.*HttpOnly/); diff --git a/packages/api/test/google-sign-in.postgres.test.ts b/packages/api/test/google-sign-in.postgres.test.ts index 1cc7e468..5395004c 100644 --- a/packages/api/test/google-sign-in.postgres.test.ts +++ b/packages/api/test/google-sign-in.postgres.test.ts @@ -1,3 +1,4 @@ +import { totpAt } from "../src/totp"; import { expect, it, vi } from "vitest"; import { protectedApiFetch } from "../src/protected-api"; import { googleSignInCallback } from "../src/auth-api"; @@ -225,6 +226,48 @@ it.skipIf(!url)("checks the start limit before allocating a Google sign-in attem } }); +it.skipIf(!url)("lets Google-only owners enroll with fresh linked Google proof and requires a second factor at Google sign-in", async () => { + const f = await loadingFixture(url!); + try { + const h = await harness(f); + f.env.TOTP_ENCRYPTION_KEY = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64"); + const email = "google-totp@gmail.com", subject = "google-totp-subject"; + const initial = await h.google(subject, email); + const created = await h.api("POST", "/auth/google/finish", { username: "google-totp" }, initial.browser); + const owner = h.sessionCookie(created); + const status = () => h.api("GET", "/auth/two-factor", undefined, owner).then(r => r.json()); + expect(await status()).toMatchObject({ enabled: false, method: "google", googleVerified: false }); + expect((await h.api("POST", "/auth/two-factor/enrollment", {}, owner)).status).toBe(401); + const fresh = await h.google(subject, email, owner, true); + expect(fresh.result.headers.get("Location")).toBe(f.env.APP_ORIGIN + "/settings/two-factor"); + expect(fresh.result.headers.getSetCookie()).toEqual([]); + const prepared = await h.api("POST", "/auth/two-factor/enrollment", {}, owner + "; " + fresh.browser); + expect(prepared.status, await prepared.clone().text()).toBe(200); + const { secret } = await prepared.json() as { secret: string }; + const pending = prepared.headers.get("Set-Cookie")!.split(";")[0]; + const enabled = await h.api("POST", "/auth/two-factor/enable", { code: await totpAt(secret, Math.floor(Date.now() / 30_000)) }, owner + "; " + pending); + expect(enabled.status, await enabled.clone().text()).toBe(200); + const { recoveryCodes } = await enabled.json() as { recoveryCodes: string[] }; + const login = await h.google(subject, email); + expect(login.result.headers.get("Location")).toBe(f.env.APP_ORIGIN + "/auth/two-factor"); + expect(h.sessionCookie(login.result)).toBe("factorize_session="); + const challenge = login.result.headers.getSetCookie().find(row => row.startsWith("__Host-factorize_totp_login="))!.split(";")[0]; + const completed = await h.api("POST", "/auth/two-factor/challenge", { code: recoveryCodes[0] }, challenge); + expect(completed.status, await completed.clone().text()).toBe(200); + const authenticated = h.sessionCookie(completed); + expect(await (await h.api("GET", "/session", undefined, authenticated)).json()).toMatchObject({ authenticated: true, user: { email } }); + + const removal = await h.google(subject, email, authenticated, true); + expect(removal.result.headers.get("Location")).toBe(f.env.APP_ORIGIN + "/settings/two-factor"); + const disabled = await h.api("POST", "/auth/two-factor/disable", { code: recoveryCodes[1] }, authenticated + "; " + removal.browser); + expect(disabled.status, await disabled.clone().text()).toBe(200); + expect(await (await h.api("GET", "/auth/two-factor", undefined, h.sessionCookie(disabled))).json()).toMatchObject({ enabled: false }); + } finally { + vi.unstubAllGlobals(); + await f.cleanup(); + } +}); + async function harness(f: Awaited>) { const env = Object.assign(f.env, { GOOGLE_SIGN_IN_CLIENT_ID: "google-fixture", GOOGLE_SIGN_IN_CLIENT_SECRET: "fixture-secret", @@ -255,8 +298,8 @@ async function harness(f: Awaited>) { const api = (method: string, path: string, body?: unknown, cookie = "") => protectedApiFetch(new Request(env.APP_ORIGIN + "/api/v1" + path, { method, headers: { Cookie: cookie, Origin: env.APP_ORIGIN, "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), }), env, null, {} as ExecutionContext); - const google = async (subject: string, email: string, passwordSession?: string) => { - const start = passwordSession ? await api("POST", "/auth/password/set-request", undefined, passwordSession) : await api("POST", "/auth/google/start", { returnTo: "/clients" }); + const google = async (subject: string, email: string, passwordSession?: string, totpSettings = false) => { + const start = passwordSession ? await api("POST", totpSettings ? "/auth/two-factor/google" : "/auth/password/set-request", undefined, passwordSession) : await api("POST", "/auth/google/start", { returnTo: "/clients" }); expect(start.status, await start.clone().text()).toBe(200); const browser = start.headers.get("Set-Cookie")!.split(";")[0]; const authorization = new URL((await start.json() as { authorizationUrl:string }).authorizationUrl); diff --git a/packages/api/test/totp.postgres.test.ts b/packages/api/test/totp.postgres.test.ts new file mode 100644 index 00000000..3f96022f --- /dev/null +++ b/packages/api/test/totp.postgres.test.ts @@ -0,0 +1,162 @@ +import { expect, it, vi } from "vitest"; +import { hashPassword, tokenDigest } from "../src/auth"; +import { protectedApiFetch } from "../src/protected-api"; +import { totpAt } from "../src/totp"; +import { loadingFixture } from "./helpers/loading-fixture"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); + +const url = process.env.AUTH_TEST_DATABASE_URL; +const password = "original fixture password"; +const newPassword = "replacement fixture password"; +const runtimeKey = () => Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64"); +const cookie = (response: Response, prefix: string) => response.headers.getSetCookie().find(value => value.startsWith(prefix))!.split(";")[0]; +const challenge = (response: Response) => cookie(response, "__Host-factorize_totp_login="); +const session = (response: Response) => cookie(response, "factorize_session="); +const currentSlot = () => Math.floor(Date.now() / 30_000); + +it("generates the standard SHA1 authenticator value", async () => { + expect(await totpAt("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", 1)).toBe("287082"); +}); + +it.skipIf(!url)("authenticator settings require the password and keep password and MCP session issuance behind the second factor", async () => { + const f = await loadingFixture(url!); + try { + const h = await harness(f); + const start = h.api("POST", "/auth/two-factor/enrollment", { password }, f.cookie); + const setup = await start; + expect(setup.status, await setup.clone().text()).toBe(200); + const { secret, uri } = await setup.json() as { secret: string; uri: string }; + expect(new URL(uri).searchParams.get("secret")).toBe(secret); + expect((await f.db.pool.query("SELECT encrypted_secret FROM app.auth_totp_enrollments")).rows[0].encrypted_secret).not.toContain(secret); + const setupCookie = cookie(setup, "__Host-factorize_totp_enroll="); + const slot = currentSlot(); + const enabled = await h.api("POST", "/auth/two-factor/enable", { code: await totpAt(secret, slot) }, f.cookie + "; " + setupCookie); + expect(enabled.status, await enabled.clone().text()).toBe(200); + const { recoveryCodes } = await enabled.json() as { recoveryCodes: string[] }; + expect(recoveryCodes).toHaveLength(10); + expect(new Set(recoveryCodes).size).toBe(10); + expect((await f.db.pool.query("SELECT digest FROM app.auth_totp_recovery_codes")).rows.every(row => !recoveryCodes.includes(row.digest))).toBe(true); + expect(await (await h.api("GET", "/session", undefined, f.cookie)).json()).toEqual({ authenticated: false }); + const activeCookie = session(enabled); + const status = await (await h.api("GET", "/auth/two-factor", undefined, activeCookie)).json(); + expect(status).toEqual({ enabled: true, available: true, method: "password", googleVerified: false }); + + const destination = "/authorize?" + new URLSearchParams({ client_id: "mcp-test", redirect_uri: "https://client.test/callback", response_type: "code", state: "fixture", code_challenge: "a-fixture-challenge", code_challenge_method: "S256" }); + const started = await h.api("POST", "/auth/connections", { returnTo: destination }); + expect(started.status).toBe(200); + const { connection } = await started.json() as {connection: string}; + const connectionCookie = cookie(started, "factorize_connection_"); + const login = await h.api("POST", "/auth/login", { email: h.email, password, connection }, connectionCookie); + expect(await login.json()).toEqual({ ok: true, returnTo: "/auth/two-factor" }); + expect(session(login)).toBe("factorize_session="); + expect((await f.db.pool.query("SELECT user_id,used_at FROM app.oauth_connections WHERE id=$1", [connection])).rows[0]).toEqual({ user_id: null, used_at: null }); + const second = challenge(login); + expect(await (await h.api("GET", "/session", undefined, second)).json()).toEqual({ authenticated: false }); + const attemptedConsent = await h.api("POST", "/oauth/consent/preview", { authorizationQuery: destination.split("?")[1] + "&connection=" + connection }, connectionCookie + "; " + second); + expect(attemptedConsent.status).toBe(401); + const verified = await h.api("POST", "/auth/two-factor/challenge", { code: recoveryCodes[0] }, connectionCookie + "; " + second); + expect(verified.status, await verified.clone().text()).toBe(200); + const result = await verified.json() as {returnTo: string}; + expect(result.returnTo).toBe(destination + "&connection=" + connection); + expect((await f.db.pool.query("SELECT user_id,used_at FROM app.oauth_connections WHERE id=$1", [connection])).rows[0]).toEqual({ user_id: f.userId, used_at: null }); + const authenticated = session(verified); + expect(await (await h.api("GET", "/session", undefined, authenticated)).json()).toMatchObject({ user: { id: f.userId }, team: { id: f.tenantId } }); + expect((await h.api("POST", "/oauth/consent/preview", { authorizationQuery: result.returnTo.split("?")[1] }, connectionCookie + "; " + authenticated)).status).toBe(200); + + const another = await h.api("POST", "/auth/login", { email: h.email, password }); + expect((await h.api("POST", "/auth/two-factor/challenge", { code: recoveryCodes[0] }, challenge(another))).status).toBe(401); + const other = await h.api("POST", "/auth/login", { email: h.email, password }); + const pairedResult = await Promise.all([another, other].map(response => + h.api("POST", "/auth/two-factor/challenge", { code: recoveryCodes[1] }, challenge(response)))); + expect(pairedResult.map(response => response.status).sort()).toEqual([200, 401]); + expect((await h.api("POST", "/auth/two-factor/disable", { password: "incorrect fixture password", code: recoveryCodes[2] }, authenticated)).status).toBe(401); + const disabled = await h.api("POST", "/auth/two-factor/disable", { password, code: recoveryCodes[2] }, authenticated); + expect(disabled.status, await disabled.clone().text()).toBe(200); + expect(await (await h.api("GET", "/auth/two-factor", undefined, session(disabled))).json()).toMatchObject({ enabled: false }); + expect((await f.db.pool.query("SELECT 1 FROM app.auth_totp_recovery_codes")).rows).toHaveLength(0); + } finally { + await f.cleanup(); + } +}); + +it.skipIf(!url)("does not accept the same authenticator interval twice and does not bypass 2FA after password reset", async () => { + const f = await loadingFixture(url!); + try { + const h = await harness(f); + const setup = await h.api("POST", "/auth/two-factor/enrollment", { password }, f.cookie); + const { secret } = await setup.json() as {secret: string}; + const fixtureClock = currentSlot() * 30_000 + 5000; + vi.spyOn(Date, "now").mockReturnValue(fixtureClock); + const setupCode = await totpAt(secret, currentSlot()); + const enabled = await h.api("POST", "/auth/two-factor/enable", { code: setupCode }, f.cookie + "; " + cookie(setup, "__Host-factorize_totp_enroll=")); + expect(enabled.status).toBe(200); + const { recoveryCodes } = await enabled.json() as { recoveryCodes: string[] }; + const first = await h.api("POST", "/auth/login", { email: h.email, password }); + expect((await h.api("POST", "/auth/two-factor/challenge", { code: setupCode }, challenge(first))).status).toBe(401); + const second = await h.api("POST", "/auth/login", { email: h.email, password }); + const acceptableCode = await totpAt(secret, currentSlot() + 1); + const exactOnce = await Promise.all([first, second].map(response => + h.api("POST", "/auth/two-factor/challenge", { code: acceptableCode }, challenge(response)))); + expect(exactOnce.map(response => response.status).sort()).toEqual([200, 401]); + vi.restoreAllMocks(); + + // Simulate a previously mailed, ordinary reset link in the disposable DB. + const resetToken = "local-reset-fixture"; + await f.db.pool.query("INSERT INTO app.auth_reset_tokens(digest,user_id,expires_at,purpose) VALUES($1,$2,now()+interval '1 hour','reset')", [ + await tokenDigest(resetToken, f.env.SESSION_SIGNING_SECRET), f.userId, + ]); + const reset = await h.api("POST", "/auth/password-reset/complete", { token: resetToken, password: newPassword }); + expect(await reset.json()).toEqual({ ok: true, returnTo: "/auth/two-factor" }); + expect(session(reset)).toBe("factorize_session="); + const afterReset = await h.api("POST", "/auth/two-factor/challenge", { code: recoveryCodes[0] }, challenge(reset)); + expect(afterReset.status).toBe(200); + expect(await (await h.api("GET", "/auth/two-factor", undefined, session(afterReset))).json()).toMatchObject({ enabled: true }); + } finally { + vi.restoreAllMocks(); + await f.cleanup(); + } +}); + +it.skipIf(!url)("expires pending logins and throttles repeated code checks across browser challenges", async () => { + const f = await loadingFixture(url!); + try { + const h = await harness(f); + const prepared = await h.api("POST", "/auth/two-factor/enrollment", { password }, f.cookie); + const { secret } = await prepared.json() as { secret: string }; + const enabled = await h.api("POST", "/auth/two-factor/enable", { code: await totpAt(secret, currentSlot()) }, f.cookie + "; " + cookie(prepared, "__Host-factorize_totp_enroll=")); + const { recoveryCodes } = await enabled.json() as { recoveryCodes: string[] }; + const login = () => h.api("POST", "/auth/login", { email: h.email, password }); + const expired = await login(); + await f.db.pool.query("UPDATE app.auth_totp_challenges SET expires_at=now()-interval '1 second' WHERE user_id=$1", [f.userId]); + expect((await h.api("POST", "/auth/two-factor/challenge", { code: recoveryCodes[0] }, challenge(expired))).status).toBe(400); + const left = await login(), right = await login(); + await f.db.pool.query("UPDATE app.auth_totp_limits SET attempts=9 WHERE user_id=$1 AND kind='code'", [f.userId]); + expect((await h.api("POST", "/auth/two-factor/challenge", { code: "not-an-authenticator-code" }, challenge(left))).status).toBe(401); + expect((await h.api("POST", "/auth/two-factor/challenge", { code: recoveryCodes[0] }, challenge(right))).status).toBe(429); + await f.db.pool.query("UPDATE app.auth_totp_limits SET expires_at=now()-interval '1 second' WHERE user_id=$1 AND kind='code'", [f.userId]); + expect((await h.api("POST", "/auth/two-factor/challenge", { code: recoveryCodes[0] }, challenge(right))).status).toBe(200); + } finally { + await f.cleanup(); + } +}); + +async function harness(f: Awaited>) { + const email = (await f.db.pool.query<{ email:string }>("SELECT email FROM app.auth_users WHERE id=$1", [f.userId])).rows[0].email; + await f.db.pool.query("INSERT INTO app.auth_accounts(id,user_id,provider,provider_account_id,password_hash) VALUES($1,$2::uuid,'credential',$2::uuid::text,$3)", + [crypto.randomUUID(), f.userId, await hashPassword(password)]); + const oauth = { + listUserGrants: async () => ({ items: [] }), + lookupClient: async () => ({ clientId: "mcp-test", clientName: "MCP fixture", redirectUris: ["https://client.test/callback"], tokenEndpointAuthMethod: "none" }), + parseAuthRequest: async (request: Request) => { + const q = new URL(request.url).searchParams; + return { responseType: "code", clientId: q.get("client_id"), redirectUri: q.get("redirect_uri"), scope: ["team:read"], state: q.get("state"), codeChallenge: q.get("code_challenge"), codeChallengeMethod: q.get("code_challenge_method"), resource: f.env.APP_ORIGIN + "/mcp" }; + }, + }; + Object.assign(f.env, { TOTP_ENCRYPTION_KEY: runtimeKey(), OAUTH_PROVIDER: oauth }); + const api = (method: string, path: string, body?: unknown, cookie = "") => protectedApiFetch(new Request(f.env.APP_ORIGIN + "/api/v1" + path, { + method, headers: { Cookie: cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), + }), f.env, null, {} as ExecutionContext); + return { api, email }; +} diff --git a/packages/app/package.json b/packages/app/package.json index f6ec116f..ec19ddb8 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -16,6 +16,7 @@ "@tanstack/react-router": "1.170.41", "@tanstack/react-virtual": "^3.14.14", "factorize-api-client": "0.1.0", + "qrcode-generator": "2.0.4", "react": "19.3.0", "react-dom": "19.3.0", "react-markdown": "^10.1.0" diff --git a/packages/app/src/features/auth/routes.tsx b/packages/app/src/features/auth/routes.tsx index 2d0fa51b..cb2906fd 100644 --- a/packages/app/src/features/auth/routes.tsx +++ b/packages/app/src/features/auth/routes.tsx @@ -24,5 +24,5 @@ export function authRoutes(rootRoute: AnyRootRoute) { } } : {}), }); } - return [createRoute({ getParentRoute: () => rootRoute, path: "/auth/google", validateSearch: (input: Record) => ({ token: typeof input.token === "string" ? input.token : undefined }), component: lazyRouteComponent(() => import("./google-sign-in"), "GoogleSignInScreen") }), route("/auth/login", "login"), route("/auth/signup", "signup"), route("/auth/password-reset", "reset"), route("/auth/verify", "verify"), route("/auth/verify/request", "verify-request")]; + return [createRoute({ getParentRoute: () => rootRoute, path: "/auth/two-factor", component: lazyRouteComponent(() => import("./two-factor"), "TwoFactorChallenge") }), createRoute({ getParentRoute: () => rootRoute, path: "/auth/google", validateSearch: (input: Record) => ({ token: typeof input.token === "string" ? input.token : undefined }), component: lazyRouteComponent(() => import("./google-sign-in"), "GoogleSignInScreen") }), route("/auth/login", "login"), route("/auth/signup", "signup"), route("/auth/password-reset", "reset"), route("/auth/verify", "verify"), route("/auth/verify/request", "verify-request")]; } diff --git a/packages/app/src/features/auth/two-factor.tsx b/packages/app/src/features/auth/two-factor.tsx new file mode 100644 index 00000000..8970d938 --- /dev/null +++ b/packages/app/src/features/auth/two-factor.tsx @@ -0,0 +1,163 @@ +import { useMemo, useState, type FormEvent } from "react"; +import { Link } from "@tanstack/react-router"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import qrCode from "qrcode-generator"; +import { api } from "factorize-api-client"; +import { Button, Input, Label, Page } from "../../shared/ui"; +import { AccountSettingsLayout } from "../settings/navigation"; +import { messageOf, refreshIdentity } from "./session"; + +function CodeInput({ value, setValue, authenticatorOnly = false }: { value: string; setValue: (value: string) => void; authenticatorOnly?: boolean }) { + return ; +} + +export function TwoFactorChallenge() { + const [code, setCode] = useState(""); + const verify = useMutation({ + retry: false, + mutationFn: async (code: string) => { + const { data, error } = await api.POST("/api/v1/auth/two-factor/challenge", { body: { code } }); + if (!data || error) throw new Error(messageOf(error)); + return data.returnTo; + }, + onSuccess: async target => { + await refreshIdentity(); + window.location.assign(target); + }, + }); + function submit(event: FormEvent) { event.preventDefault(); if (!verify.isPending) verify.mutate(code.trim()); } + return +

Finish signing in

+

Enter a code from your authenticator app or use one of your recovery codes.

+
+ + {verify.error &&

{verify.error.message}

} + + +

Back to sign in

+
; +} + +function SetupQr({ uri }: { uri: string }) { + const { width, path } = useMemo(() => { + const matrix = qrCode(0, "M"); + matrix.addData(uri); + matrix.make(); + const size = matrix.getModuleCount(), dark: string[] = []; + for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) { + if (matrix.isDark(y, x)) dark.push(`M${x + 4} ${y + 4}h1v1h-1z`); + } + return { width: size + 8, path: dark.join("") }; + }, [uri]); + return + + ; +} + +export function TwoFactorSettings() { + const [password, setPassword] = useState(""); + const [code, setCode] = useState(""); + const [setup, setSetup] = useState<{ secret: string; uri: string } | null>(null); + const [codes, setCodes] = useState([]); + const status = useQuery({ + queryKey: ["two-factor-settings"], retry: false, + queryFn: async ({ signal }) => { + const { data, error } = await api.GET("/api/v1/auth/two-factor", { signal }); + if (!data || error) throw new Error(messageOf(error)); + return data; + }, + }); + const google = useMutation({ + retry: false, + mutationFn: async () => { + const { data, error } = await api.POST("/api/v1/auth/two-factor/google"); + if (!data || error) throw new Error(messageOf(error)); + return data.authorizationUrl; + }, onSuccess: url => window.location.assign(url), + }); + const start = useMutation({ + retry: false, gcTime: 0, + mutationFn: async (password: string | undefined) => { + const { data, error } = await api.POST("/api/v1/auth/two-factor/enrollment", { body: { password } }); + if (!data || error) throw new Error(messageOf(error)); + return data; + }, onSuccess: data => { setSetup(data); setPassword(""); }, + }); + const enable = useMutation({ + retry: false, gcTime: 0, + mutationFn: async (code: string) => { + const { data, error } = await api.POST("/api/v1/auth/two-factor/enable", { body: { code } }); + if (!data || error) throw new Error(messageOf(error)); + return data.recoveryCodes; + }, onSuccess: async recovery => { + setCodes(recovery); + setCode(""); + setSetup(null); + await refreshIdentity(); + await status.refetch(); + }, + }); + const disable = useMutation({ + retry: false, + mutationFn: async (body: { password?: string; code: string }) => { + const { data, error } = await api.POST("/api/v1/auth/two-factor/disable", { body }); + if (!data || error) throw new Error(messageOf(error)); + }, onSuccess: async () => { + setPassword(""); + setCode(""); + await refreshIdentity(); + await status.refetch(); + }, + }); + + const state = status.data; + const passwordInput = state?.method === "password"; + const needsGoogle = state?.method === "google" && !state.googleVerified; + const busy = google.isPending || start.isPending || enable.isPending || disable.isPending; + const error = google.error ?? start.error ?? enable.error ?? disable.error; + return + {status.isPending && !codes.length &&

Loading two-factor settings…

} + {status.error &&

{status.error.message}

} + {error &&

{error.message}

} + {codes.length > 0 ?
+

Save your recovery codes

+

Two-factor authentication is on. Store these codes somewhere safe. Each code works once and will not be shown again.

+
    {codes.map(value =>
  • {value}
  • )}
+ +
: setup ?
{ event.preventDefault(); if (!busy) enable.mutate(code.trim()); }}> +

Scan this QR code in an authenticator app, then enter the six-digit code. If you can’t scan, enter the setup key manually.

+ +

Setup key: {setup.secret}

+ +
+
+ : state &&
+

Two-factor authentication is {state.enabled ? "on" : "off"}.

+ {!state.available && !state.enabled ?

Authenticator setup is not available on this deployment.

+ : state.method === "unavailable" ?

A Factorize password or linked Google account is needed to change this setting.

+ : needsGoogle ? <> +

Confirm your linked Google account before changing this setting.

+ + :
{ + event.preventDefault(); + if (busy) return; + const primary = passwordInput ? password : undefined; + if (state.enabled) disable.mutate({ password: primary, code: code.trim() }); + else start.mutate(primary); + }}> + {passwordInput && } + {state.enabled && } + + } +
} +
; +} diff --git a/packages/app/src/features/settings/navigation.tsx b/packages/app/src/features/settings/navigation.tsx index 3ddc6b38..758b7960 100644 --- a/packages/app/src/features/settings/navigation.tsx +++ b/packages/app/src/features/settings/navigation.tsx @@ -37,6 +37,7 @@ export function AccountSettingsLayout({ title, children }: { title: string; chil return Profile API keys + Two-factor authentication {passwordLabel} }>{children}; } diff --git a/packages/app/src/features/settings/routes.tsx b/packages/app/src/features/settings/routes.tsx index 868fb09b..580ec574 100644 --- a/packages/app/src/features/settings/routes.tsx +++ b/packages/app/src/features/settings/routes.tsx @@ -16,5 +16,6 @@ export function settingsRoutes(root: AnyRootRoute) { createRoute({ getParentRoute: () => root, path: "/settings/api-keys", beforeLoad: guard, component: lazyRouteComponent(() => import("./api-keys"), "ApiKeys") }), createRoute({ getParentRoute: () => root, path: "/settings/api-keys/new", beforeLoad: guard, component: lazyRouteComponent(() => import("./api-key-create"), "ApiKeyCreate") }), createRoute({ getParentRoute: () => root, path: "/settings/authorized-clients", beforeLoad: () => { throw redirect({ to: "/clients", replace: true }); } }), + createRoute({ getParentRoute: () => root, path: "/settings/two-factor", beforeLoad: guard, component: lazyRouteComponent(() => import("../auth/two-factor"), "TwoFactorSettings") }), createRoute({ getParentRoute: () => root, path: "/settings/password", beforeLoad: guard, component: () => })]; } diff --git a/packages/app/test/functional/auth.spec.mjs b/packages/app/test/functional/auth.spec.mjs index c85bd1af..3c7571e2 100644 --- a/packages/app/test/functional/auth.spec.mjs +++ b/packages/app/test/functional/auth.spec.mjs @@ -118,7 +118,7 @@ test("Account settings opens from the account menu and keeps account pages toget await page.getByRole("heading", { name: "Profile", exact: true }).waitFor(); const settings = page.getByRole("navigation", { name: "Account settings", exact: true }); - assert.deepEqual(await settings.getByRole("link").allTextContents(), ["Profile", "API keys", "Change password"]); + assert.deepEqual(await settings.getByRole("link").allTextContents(), ["Profile", "API keys", "Two-factor authentication", "Change password"]); const dashboard = page.getByRole("navigation", { name: "Dashboard navigation" }); assert.equal(await dashboard.locator('[aria-current="page"]').count(), 0); assert.equal(await dashboard.locator(".border-factorize-500").count(), 0); diff --git a/packages/app/test/functional/two-factor.spec.mjs b/packages/app/test/functional/two-factor.spec.mjs new file mode 100644 index 00000000..5d200e12 --- /dev/null +++ b/packages/app/test/functional/two-factor.spec.mjs @@ -0,0 +1,58 @@ +import { expect } from "@playwright/test"; +import { test } from "./fixtures.mjs"; + +const apiSession = { authenticated: true, user: { id: "owner", email: "owner@example.test" }, + team: { id: "workspace", name: "Workspace", role: "owner" }, capabilities: [] }; +const recovery = Array.from({ length: 10 }, (_, i) => "saved-recovery-code-" + i); + +test("sets up an authenticator locally, then shows the recovery codes only once", async ({ page, origin }) => { + let enabled = false; + await page.route("**/api/v1/session", route => route.fulfill({ json: apiSession })); + await page.route("**/api/v1/auth/two-factor", route => route.fulfill({ json: { enabled, available: true, method: "password", googleVerified: false } })); + await page.route("**/api/v1/auth/two-factor/enrollment", route => { + expect(route.request().postDataJSON()).toEqual({ password: "existing fixture password" }); + return route.fulfill({ json: { secret: "ABCDEFGHIJKLMNOP", uri: "otpauth://totp/Factorize:owner?secret=ABCDEFGHIJKLMNOP&issuer=Factorize" } }); + }); + await page.route("**/api/v1/auth/two-factor/enable", route => { + expect(route.request().postDataJSON()).toEqual({ code: "123456" }); + enabled = true; + return route.fulfill({ json: { ok: true, recoveryCodes: recovery } }); + }); + await page.goto(origin + "/settings/two-factor"); + await expect(page.getByRole("heading", { name: "Two-factor authentication" })).toBeVisible(); + await page.getByLabel("Current password").fill("existing fixture password"); + await page.getByRole("button", { name: "Set up authenticator" }).click(); + await expect(page.getByRole("img", { name: "Authenticator setup QR code" })).toBeVisible(); + await expect(page.getByText("ABCDEFGHIJKLMNOP")).toBeVisible(); + await page.getByLabel("Authenticator code").fill("123456"); + await page.getByRole("button", { name: "Enable two-factor authentication" }).click(); + await expect(page.getByRole("heading", { name: "Save your recovery codes" })).toBeVisible(); + for (const code of recovery) await expect(page.getByText(code, { exact: true })).toBeVisible(); + await page.getByRole("button", { name: "I saved my codes" }).click(); + await expect(page.getByText(recovery[0])).toHaveCount(0); + await page.reload(); + await expect(page.getByRole("button", { name: "Disable two-factor authentication" })).toBeVisible(); + await expect(page.getByText(recovery[0])).toHaveCount(0); +}); + +test("sign-in prompts for a second factor before reaching the original destination", async ({ page, origin }) => { + let signed = false; + await page.route("**/api/v1/session", route => route.fulfill({ json: signed ? apiSession : { authenticated: false } })); + await page.route("**/api/v1/auth/login", route => route.fulfill({ json: { ok: true, returnTo: "/auth/two-factor" } })); + await page.route("**/api/v1/auth/two-factor/challenge", route => { + expect(route.request().postDataJSON()).toEqual({ code: "fixture-recovery-code" }); + signed = true; + return route.fulfill({ json: { ok: true, returnTo: "/settings/two-factor" } }); + }); + await page.route("**/api/v1/auth/two-factor", route => route.fulfill({ json: { enabled: true, available: true, method: "password", googleVerified: false } })); + await page.goto(origin + "/auth/login"); + await page.getByLabel("Username or email").fill("owner@example.test"); + await page.getByLabel("Password", { exact: true }).fill("existing fixture password"); + await page.getByRole("button", { name: "Sign in", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Finish signing in" })).toBeVisible(); + expect(signed).toBe(false); + await page.getByLabel("Authenticator or recovery code").fill("fixture-recovery-code"); + await page.getByRole("button", { name: "Verify code" }).click(); + await expect(page).toHaveURL(origin + "/settings/two-factor"); + await expect(page.getByText("Two-factor authentication is on.")).toBeVisible(); +}); diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 11cff27b..844e4707 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -548,6 +548,27 @@ Factorize account, password recovery pauses rather than transferring or combinin accounts. Sign-in with the linked Google account still works. Keep Postmark configured for address confirmation and password recovery. +### Optional two-factor authentication + +Two-factor authentication is off by default and configured by each user in +**Account settings → Two-factor authentication**. There is no team enforcement. +Set `TOTP_ENCRYPTION_KEY` as an independent Worker secret before offering +enrollment. Generate 32 cryptographically random bytes encoded as base64 (for +example, using `openssl rand -base64 32`). Do not reuse the credential encryption +key or store the value in the repository. Normal deployment applies migration +0105. Keep the key securely backed up; changing it without re-encrypting +existing TOTP secrets breaks authenticator verification for enrolled users. +Users with a saved recovery code can still sign in. + +Enrollment requires confirmation of the current Factorize password, or fresh +Google confirmation for Google-only users. The setup QR code is generated in +the browser without sending the secret to a QR service. Users confirm a valid +authenticator code to enable 2FA and should immediately save the ten recovery +codes, which are shown once and work once each. Disabling requires primary +confirmation plus an authenticator or recovery code. Password reset does not +disable 2FA. Enable and disable invalidate older sessions and delegated grants +using existing membership session versions. + ### Existing account migration Apply `0008_native_accounts.sql` and `0009_remove_auth_usernames.sql` before deploying this code. They reject ambiguous legacy emails that differ only in case (reconcile those identities before retrying migration), preserve tenant IDs, memberships, triggers and encrypted Linear connections, and backfill explicit Linear organization-to-workspace mappings. Existing Linear-only users choose **Forgot password or previously signed in with Linear?**, receive a reset email at their existing address, and set a password. Email possession is required; signup cannot replace an existing account's credentials. Existing native users keep their passwords and may sign in by email; unverified accounts must verify first. A reset never promotes a member to owner. An account with multiple existing owner memberships currently opens the oldest workspace; no new workspace-switching UI is introduced. diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 09b46091..ff2cc0aa 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -2276,6 +2276,408 @@ paths: - cookieAuth: [] x-browser-auth-operation: password-set-request x-owner-session-required: true + /api/v1/auth/two-factor: + get: + summary: Read your two-factor settings + description: Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + responses: + "200": + description: Success + headers: + X-Factorize-Webhook-Conditions: + description: Conditions-only webhook runtime deployment marker. + schema: + type: string + const: v1 + X-Factorize-Contract: + description: Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. + schema: + type: string + const: gen-2157-static-v1 + content: + application/json: + schema: + type: object + properties: + enabled: + type: boolean + available: + type: boolean + method: + type: string + enum: + - password + - google + - unavailable + googleVerified: + type: boolean + required: + - enabled + - available + - method + - googleVerified + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: get_api_v1_auth_two_factor + tags: + - auth + security: + - cookieAuth: [] + x-browser-auth-operation: totp-status + x-owner-session-required: true + /api/v1/auth/two-factor/google: + post: + summary: Confirm a linked Google account for a two-factor settings change + description: Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + responses: + "200": + description: Success + headers: + X-Factorize-Webhook-Conditions: + description: Conditions-only webhook runtime deployment marker. + schema: + type: string + const: v1 + X-Factorize-Contract: + description: Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. + schema: + type: string + const: gen-2157-static-v1 + content: + application/json: + schema: + type: object + properties: + authorizationUrl: + type: string + format: uri + required: + - authorizationUrl + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_auth_two_factor_google + tags: + - auth + security: + - cookieAuth: [] + x-browser-auth-operation: totp-google + x-owner-session-required: true + /api/v1/auth/two-factor/enrollment: + post: + summary: Create a short-lived authenticator setup secret + description: Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + responses: + "200": + description: Success + headers: + X-Factorize-Webhook-Conditions: + description: Conditions-only webhook runtime deployment marker. + schema: + type: string + const: v1 + X-Factorize-Contract: + description: Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. + schema: + type: string + const: gen-2157-static-v1 + content: + application/json: + schema: + type: object + properties: + secret: + type: string + uri: + type: string + required: + - secret + - uri + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_auth_two_factor_enrollment + tags: + - auth + security: + - cookieAuth: [] + x-browser-auth-operation: totp-begin + x-owner-session-required: true + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + password: + type: string + minLength: 12 + maxLength: 200 + writeOnly: true + additionalProperties: false + /api/v1/auth/two-factor/enable: + post: + summary: Enable two-factor authentication and show recovery codes once + description: Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + responses: + "200": + description: Success + headers: + X-Factorize-Webhook-Conditions: + description: Conditions-only webhook runtime deployment marker. + schema: + type: string + const: v1 + X-Factorize-Contract: + description: Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. + schema: + type: string + const: gen-2157-static-v1 + content: + application/json: + schema: + type: object + properties: + ok: + type: boolean + const: true + recoveryCodes: + minItems: 10 + maxItems: 10 + type: array + items: + type: string + required: + - ok + - recoveryCodes + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_auth_two_factor_enable + tags: + - auth + security: + - cookieAuth: [] + x-browser-auth-operation: totp-enable + x-owner-session-required: true + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + code: + type: string + pattern: ^\d{6}$ + required: + - code + additionalProperties: false + /api/v1/auth/two-factor/disable: + post: + summary: Disable two-factor authentication using primary and second factors + description: Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + responses: + "200": + description: Success + headers: + X-Factorize-Webhook-Conditions: + description: Conditions-only webhook runtime deployment marker. + schema: + type: string + const: v1 + X-Factorize-Contract: + description: Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. + schema: + type: string + const: gen-2157-static-v1 + content: + application/json: + schema: + type: object + properties: + ok: + type: boolean + const: true + required: + - ok + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_auth_two_factor_disable + tags: + - auth + security: + - cookieAuth: [] + x-browser-auth-operation: totp-disable + x-owner-session-required: true + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + password: + type: string + minLength: 12 + maxLength: 200 + writeOnly: true + code: + type: string + minLength: 1 + maxLength: 64 + required: + - code + additionalProperties: false + /api/v1/auth/two-factor/challenge: + post: + summary: Finish a browser sign-in using a fresh authenticator or recovery code + description: Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + responses: + "200": + description: Success + headers: + X-Factorize-Webhook-Conditions: + description: Conditions-only webhook runtime deployment marker. + schema: + type: string + const: v1 + X-Factorize-Contract: + description: Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. + schema: + type: string + const: gen-2157-static-v1 + content: + application/json: + schema: + type: object + properties: + ok: + type: boolean + const: true + returnTo: + type: string + required: + - ok + - returnTo + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_auth_two_factor_challenge + tags: + - auth + security: [] + x-browser-auth-operation: totp-challenge + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + code: + type: string + minLength: 1 + maxLength: 64 + required: + - code + additionalProperties: false /api/v1/auth/login: post: summary: Sign in diff --git a/packages/docs/self-hosting/configuration.mdx b/packages/docs/self-hosting/configuration.mdx index 195de937..89e63a0d 100644 --- a/packages/docs/self-hosting/configuration.mdx +++ b/packages/docs/self-hosting/configuration.mdx @@ -53,6 +53,27 @@ Factorize account, password recovery pauses rather than transferring or combinin accounts. Sign-in with the linked Google account still works. Keep Postmark configured for address confirmation and password recovery. +### Optional two-factor authentication + +Two-factor authentication is off by default and configured by each user in +**Account settings → Two-factor authentication**. There is no team enforcement. +Set `TOTP_ENCRYPTION_KEY` as an independent Worker secret before offering +enrollment. Generate 32 cryptographically random bytes encoded as base64 (for +example, using `openssl rand -base64 32`). Do not reuse the credential encryption +key or store the value in the repository. Normal deployment applies migration +0105. Keep the key securely backed up; changing it without re-encrypting +existing TOTP secrets breaks authenticator verification for enrolled users. +Users with a saved recovery code can still sign in. + +Enrollment requires confirmation of the current Factorize password, or fresh +Google confirmation for Google-only users. The setup QR code is generated in +the browser without sending the secret to a QR service. Users confirm a valid +authenticator code to enable 2FA and should immediately save the ten recovery +codes, which are shown once and work once each. Disabling requires primary +confirmation plus an authenticator or recovery code. Password reset does not +disable 2FA. Enable and disable invalidate older sessions and delegated grants +using existing membership session versions. + ### Existing account migration Apply `0008_native_accounts.sql` and `0009_remove_auth_usernames.sql` before deploying this code. They reject ambiguous legacy emails that differ only in case (reconcile those identities before retrying migration), preserve tenant IDs, memberships, triggers and encrypted Linear connections, and backfill explicit Linear organization-to-workspace mappings. Existing Linear-only users choose **Forgot password or previously signed in with Linear?**, receive a reset email at their existing address, and set a password. Email possession is required; signup cannot replace an existing account's credentials. Existing native users keep their passwords and may sign in by email; unverified accounts must verify first. A reset never promotes a member to owner. An account with multiple existing owner memberships currently opens the oldest workspace; no new workspace-switching UI is introduced.