From 76f52169b22e7318f395c582045677058feab304 Mon Sep 17 00:00:00 2001 From: Brendan Asselstine Date: Tue, 24 Nov 2026 11:14:10 -0700 Subject: [PATCH 1/3] Add Google sign-in with explicit account linking --- packages/api-client/src/schema.d.ts | 474 +++++++++++++++++ packages/api/.dev.vars.example | 5 + .../api/migrations/0104_google_sign_in.sql | 18 + packages/api/src/api-contract.ts | 10 +- packages/api/src/auth-api.ts | 106 +++- packages/api/src/auth-email.ts | 9 +- packages/api/src/google-sign-in.ts | 222 ++++++++ packages/api/src/postgres/auth-repository.ts | 6 +- packages/api/src/postgres/schema.ts | 12 +- packages/api/src/static-app.ts | 4 +- packages/api/src/types.ts | 2 + packages/api/src/worker.ts | 3 + packages/api/test/auth-api.test.ts | 6 +- .../api/test/google-sign-in.postgres.test.ts | 160 ++++++ .../app/src/features/auth/auth-screen.tsx | 23 +- .../app/src/features/auth/google-sign-in.tsx | 124 +++++ packages/app/src/features/auth/routes.tsx | 5 +- .../app/src/features/settings/navigation.tsx | 6 +- .../test/functional/google-sign-in.spec.mjs | 94 ++++ packages/docs/llms-full.txt | 19 + packages/docs/openapi.yaml | 499 ++++++++++++++++++ packages/docs/self-hosting/configuration.mdx | 19 + 22 files changed, 1796 insertions(+), 30 deletions(-) create mode 100644 packages/api/migrations/0104_google_sign_in.sql create mode 100644 packages/api/src/google-sign-in.ts create mode 100644 packages/api/test/google-sign-in.postgres.test.ts create mode 100644 packages/app/src/features/auth/google-sign-in.tsx create mode 100644 packages/app/test/functional/google-sign-in.spec.mjs diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index cecb36ec..3c13e801 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -276,6 +276,166 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/auth/google": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Check whether Google sign-in is configured + * @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_google"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/google/start": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Start browser-bound Google sign-in + * @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_google_start"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/google/pending": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Read Google signup or linking steps for the current browser + * @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_google_pending"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/google/email/request": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Send a verification link for a new Google signup + * @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_google_email_request"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/google/email/verify": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Verify the signup email in the initiating browser + * @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_google_email_verify"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/google/username": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Check username availability during Google signup + * @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_google_username"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/google/finish": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Choose a username or confirm your existing Factorize password + * @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_google_finish"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/password/set-request": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Email a link to set the first password + * @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_password_set_request"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/auth/login": { parameters: { query?: never; @@ -3051,6 +3211,320 @@ export interface operations { capabilities: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "integrations:read" | "integrations:write" | "vms:read" | "vms:edit" | "apps:manage")[]; /** Format: date-time */ expiresAt: string; + hasPassword?: 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"]; + }; + }; + get_api_v1_auth_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": { + enabled: 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_google_start: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + returnTo?: string; + /** Format: uuid */ + connection?: 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": { + /** Format: uri */ + authorizationUrl: 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"]; + }; + }; + get_api_v1_auth_google_pending: { + 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: email */ + email: string; + /** @enum {string} */ + mode: "link" | "signup" | "verify-email"; + }; + }; + }; + 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_google_email_request: { + 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": { + /** @constant */ + ok: true; + }; + }; + }; + 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_google_email_verify: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + token: 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_google_username: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + username: 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": { + available: boolean; + }; + }; + }; + 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_google_finish: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + username: string; + } | { + 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": { + /** @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_password_set_request: { + 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": { + /** @constant */ + ok: true; }; }; }; diff --git a/packages/api/.dev.vars.example b/packages/api/.dev.vars.example index 24ca72de..82788e95 100644 --- a/packages/api/.dev.vars.example +++ b/packages/api/.dev.vars.example @@ -14,3 +14,8 @@ POSTMARK_SERVER_TOKEN= # Must be verified in Postmark (plain email address). POSTMARK_FROM_EMAIL= POSTMARK_MESSAGE_STREAM=outbound + +# Optional Google OAuth web client for Factorize sign-in (separate from MCP OAuth). +# Register /oauth/google/sign-in/callback with Google. +GOOGLE_SIGN_IN_CLIENT_ID= +GOOGLE_SIGN_IN_CLIENT_SECRET= diff --git a/packages/api/migrations/0104_google_sign_in.sql b/packages/api/migrations/0104_google_sign_in.sql new file mode 100644 index 00000000..f59baa53 --- /dev/null +++ b/packages/api/migrations/0104_google_sign_in.sql @@ -0,0 +1,18 @@ +CREATE TABLE app.google_sign_in_attempts ( + id uuid PRIMARY KEY, + browser_digest text NOT NULL UNIQUE, + verifier text, + nonce text NOT NULL, + return_to text NOT NULL, + connection_id uuid REFERENCES app.oauth_connections(id) ON DELETE CASCADE, + google_subject text, + email text, + existing_user_id uuid REFERENCES app.auth_users(id) ON DELETE CASCADE, + email_confirmed boolean NOT NULL DEFAULT false, + email_token_digest text, + email_sent_at timestamptz, + password_attempts integer NOT NULL DEFAULT 0, + expires_at timestamptz NOT NULL +); +CREATE INDEX google_sign_in_attempts_expiry ON app.google_sign_in_attempts(expires_at); +CREATE UNIQUE INDEX auth_accounts_google_user_unique ON app.auth_accounts(user_id) WHERE provider='google'; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index b3e84ef5..02f20796 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, type AuthAction } from "./auth-api"; +import { authInputs, authSuccess, continuationSuccess, connectionStartInput, connectionStartSuccess, connectionResumeInput, loginSuccess, sessionResponse, googleAvailability, googleStartResult, googlePendingResult, googleUsernameResult, 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"; @@ -232,6 +232,14 @@ export const API_ROUTES: RouteContract[] = [ {...authRoute("GET", "/api/v1/profile", "profile", "Read your profile; interactive owner browser session required", profileResponse),ownerSession:true}, {...authRoute("PUT", "/api/v1/profile", "profile-update", "Change your globally unique username; interactive owner browser session required", profileResponse, profileInput),ownerSession:true}, authRoute("GET", "/api/v1/session", "session", "Get current browser session", sessionResponse), + authRoute("GET", "/api/v1/auth/google", "google-available", "Check whether Google sign-in is configured", googleAvailability), + authRoute("POST", "/api/v1/auth/google/start", "google-start", "Start browser-bound Google sign-in", googleStartResult, authInputs.googleStart), + authRoute("GET", "/api/v1/auth/google/pending", "google-pending", "Read Google signup or linking steps for the current browser", googlePendingResult), + authRoute("POST", "/api/v1/auth/google/email/request", "google-email-request", "Send a verification link for a new Google signup", authSuccess), + authRoute("POST", "/api/v1/auth/google/email/verify", "google-email-verify", "Verify the signup email in the initiating browser", authSuccess, authInputs.verify), + authRoute("POST", "/api/v1/auth/google/username", "google-username", "Check username availability during Google signup", googleUsernameResult, authInputs.googleUsername), + 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", "Email a link to set the first password", authSuccess),ownerSession:true}, 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 bd74fd03..b65501d5 100644 --- a/packages/api/src/auth-api.ts +++ b/packages/api/src/auth-api.ts @@ -1,3 +1,4 @@ +import { clearGoogleCookie, finishGoogleSignIn, googleEnabled, googlePending, googleUsernameAvailable, redeemGoogleCallback, requestGoogleEmail, startGoogleSignIn, verifyGoogleEmail, type GoogleIdentity } from "./google-sign-in"; import { usernameSchema } from "./usernames"; import { integrationConsentLabels } from "./agent-api"; import { ACCESS_SCOPES } from "./access-tokens"; @@ -23,6 +24,9 @@ export const authInputs = { request: z.object({ email, connection }).strict(), verify: z.object({ token }).strict(), reset: z.object({ token, password }).strict(), + 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(), change: z.object({ currentPassword: password, password }).strict(), }; export const sessionResponse = z.discriminatedUnion("authenticated", [ @@ -33,6 +37,7 @@ export const sessionResponse = z.discriminatedUnion("authenticated", [ team: z.object({ id: z.string(), name: z.string().nullable(), role: z.literal("owner") }).strict(), capabilities: z.array(z.enum(SESSION_SCOPES)), expiresAt: z.iso.datetime(), + hasPassword: z.boolean().optional(), }).strict(), ]); export const authSuccess = z.object({ ok: z.literal(true) }).strict(); @@ -40,6 +45,10 @@ export const continuationSuccess = authSuccess.extend({ returnTo: z.string().opt export const connectionStartInput = z.object({ returnTo: z.string().min(1).max(8192) }).strict(); export const connectionStartSuccess = z.object({ connection: z.uuid(), clientName: z.string(), expiresAt: z.iso.datetime() }); export const connectionResumeInput = z.object({ connection: z.uuid() }).strict(); +export const googleAvailability = z.object({ enabled: z.boolean() }); +export const googleStartResult = z.object({ authorizationUrl: z.url() }); +export const googlePendingResult = z.object({ email: z.email(), mode: z.enum(["link", "signup", "verify-email"]) }); +export const googleUsernameResult = z.object({ available: z.boolean() }); export const loginSuccess = authSuccess.extend({ returnTo: z.string() }); /** Only local application/protocol destinations; never trust a return cookie or form field. */ @@ -69,12 +78,57 @@ 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 === "google-available") return authJson({ enabled: googleEnabled(env) }); + if (action.startsWith("google-")) { + if (!googleEnabled(env)) return failure(404, "Google sign-in is not available."); + if (action === "google-start") { + const parsed = authInputs.googleStart.parse(input); + if (parsed.connection) { + const pending = await connectionFor(env, parsed.connection); + if (!pending || !await originalBrowser(request, env, pending)) return failure(400, "This connection expired. Restart from your MCP client."); + } + const { cookie, authorizationUrl } = await startGoogleSignIn(env, safeReturnTo(parsed.returnTo), parsed.connection); + const response = authJson({ authorizationUrl }); + response.headers.append("Set-Cookie", cookie); + return response; + } + if (action === "google-pending") { + const pending = await googlePending(request, env); + return pending ? authJson(pending) : failure(400, "This Google sign-in expired. Start again from Factorize."); + } + if (action === "google-email-request") { + return await requestGoogleEmail(request, env) ? authJson({ ok: true }) : failure(400, "This Google signup expired. Start again from Factorize."); + } + if (action === "google-email-verify") { + return await verifyGoogleEmail(request, env, authInputs.verify.parse(input).token) ? authJson({ ok: true }) + : failure(400, "This link is invalid or expired. Open it in the browser where you started Google signup, or start again."); + } + if (action === "google-username") { + const available = await googleUsernameAvailable(request, env, authInputs.googleUsername.parse(input).username); + return available === null ? failure(400, "This Google signup expired. Start again from Factorize.") : authJson({ available }); + } + if (action === "google-finish") { + const result = await finishGoogleSignIn(request, env, authInputs.googleFinish.parse(input)); + if ("status" in result) return failure(result.status, result.message); + const response = await completeInteractiveSignIn(request, env, result.identity, result.returnTo, result.connection); + response.headers.append("Set-Cookie", clearGoogleCookie(env)); + return response; + } + } + if (action === "password-set-request") { + const session = await currentSession(request, env); + if (!session) return failure(401, "Sign in before setting a password."); + const repo = new AuthRepository(databaseFor(env), env); + if (await repo.hasPassword(session.userId)) return failure(409, "You already have a password. Use Change password instead."); + await repo.requestReset({ email: session.email }); + return authJson({ ok: true }); + } if (action === "connection-start") { try { const started = await startConnection(request, env, String(input.returnTo)); @@ -113,11 +167,12 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env } if (action === "session") { if (!session) return authJson({ authenticated: false }); - const workspace = (await databaseFor(env).pool.query<{ name: string | null }>("SELECT name FROM app.tenants WHERE id=$1", [session.tenantId])).rows[0]; + const workspace = (await databaseFor(env).pool.query<{ name: string | null; has_password: boolean }>(`SELECT name, EXISTS (SELECT 1 FROM app.auth_accounts + WHERE user_id=$2 AND provider='credential' AND password_hash IS NOT NULL) has_password FROM app.tenants WHERE id=$1`, [session.tenantId, session.userId])).rows[0]; return authJson(sessionResponse.parse({ authenticated: true, user: { id: session.userId, email: session.email }, team: { id: session.tenantId, name: workspace?.name ?? null, role: "owner" }, - capabilities: [...SESSION_SCOPES], expiresAt: new Date(session.exp * 1000).toISOString(), + capabilities: [...SESSION_SCOPES], hasPassword: workspace?.has_password, expiresAt: new Date(session.exp * 1000).toISOString(), })); } if (action === "device-preview" || action === "device-decision") { @@ -161,15 +216,7 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env const identity = result.body as { userId: string; tenantId: string; email: string; sessionVersion: number; connection?: string }; const member = await new IdentityRepository(databaseFor(env), identity.tenantId).member(identity.userId); if (member?.role !== "owner" || member.sessionVersion !== identity.sessionVersion) return failure(403, "This account cannot access the workspace."); - let returnTo = safeReturnTo(input.returnTo as string | undefined); - if (input.connection) { - const pending = await connectionFor(env, String(input.connection)); - if (!pending || 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); - } - return signedIn(env, identity, { ok: true, returnTo }); + return completeInteractiveSignIn(request, env, identity, safeReturnTo(input.returnTo as string | undefined), input.connection as string | undefined); } const result = action === "signup" ? await repo.signup(input) : action === "verification-request" ? await repo.requestEmail(input, "verify") @@ -195,6 +242,41 @@ 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 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); + } + return signedIn(env, identity, { ok: true, returnTo }); +} + +export async function googleSignInCallback(request: Request, env: Env) { + if (request.method !== "GET") return new Response(null, { status: 405, headers: { Allow: "GET" } }); + const redirect = (target: string) => new Response(null, { status: 303, headers: { + Location: new URL(target, env.APP_ORIGIN).href, "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", + } }); + if (request.headers.has("Authorization")) return redirect("/auth/login?google=failed"); + try { + const result = await redeemGoogleCallback(request, env); + if ("status" in result) return redirect(result.status === 403 ? "/auth/login?google=account" : "/auth/login?google=failed"); + 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")!); + response.headers.append("Set-Cookie", clearGoogleCookie(env)); + return response; + } catch { + // Never reflect provider errors, authorization codes, or token data. + return redirect("/auth/login?google=failed"); + } +} + async function signedIn(env: Env, identity: { tenantId: string; userId: string; email: string; sessionVersion: number }, body: unknown) { const lifetime = 7 * 24 * 60 * 60; const response = authJson(body); diff --git a/packages/api/src/auth-email.ts b/packages/api/src/auth-email.ts index 62c4d591..678f28d5 100644 --- a/packages/api/src/auth-email.ts +++ b/packages/api/src/auth-email.ts @@ -8,17 +8,18 @@ export function validateAuthEmailConfig(env: Env): void { } } -export async function sendAuthEmail(env: Env, email: string, token: string, purpose: "verify" | "reset", connection?: string): Promise { +export async function sendAuthEmail(env: Env, email: string, token: string, purpose: "verify" | "reset" | "google-verify", connection?: string): Promise { validateAuthEmailConfig(env); - const url = new URL(purpose === "verify" ? "/auth/verify" : "/auth/password-reset", env.APP_ORIGIN); + const action = purpose === "google-verify" ? "Confirm your Factorize email" : purpose === "verify" ? "Verify your Factorize email" : "Reset your Factorize password"; + const url = new URL(purpose === "google-verify" ? "/auth/google" : purpose === "verify" ? "/auth/verify" : "/auth/password-reset", env.APP_ORIGIN); url.searchParams.set("token", token); if (connection) url.searchParams.set("connection", connection); const response = await fetch("https://api.postmarkapp.com/email", { method: "POST", headers: { "Content-Type": "application/json", "X-Postmark-Server-Token": env.POSTMARK_SERVER_TOKEN! }, body: JSON.stringify({ From: env.POSTMARK_FROM_EMAIL, To: email, MessageStream: env.POSTMARK_MESSAGE_STREAM, - Subject: purpose === "verify" ? "Verify your Factorize email" : "Reset your Factorize password", - TextBody: `${purpose === "verify" ? "Verify your email" : "Reset your password"}: ${url}\n\nThis link expires in one hour and can be used once. If you did not request this, ignore this email.` }), + Subject: action, + TextBody: purpose === "google-verify" ? `Confirm your email in the original browser: ${url}\n\nThis link expires when your Google signup attempt expires. If you did not request this, ignore this email.` : `${purpose === "verify" ? "Verify your email" : "Reset your password"}: ${url}\n\nThis link expires in one hour and can be used once. If you did not request this, ignore this email.` }), }); const result = await response.json() as { ErrorCode?: number }; if (!response.ok || result.ErrorCode !== 0) throw new Error("Postmark could not deliver authentication email."); diff --git a/packages/api/src/google-sign-in.ts b/packages/api/src/google-sign-in.ts new file mode 100644 index 00000000..ec89a5a3 --- /dev/null +++ b/packages/api/src/google-sign-in.ts @@ -0,0 +1,222 @@ +import { serialize } from "hono/utils/cookie"; +import { z } from "zod"; +import { normalizeEmail, tokenDigest, verifyPassword } from "./auth"; +import { sendAuthEmail } from "./auth-email"; +import { requestCookie } from "./session"; +import { databaseFor, type DatabaseClient } from "./postgres/database"; +import { AuthRepository } from "./postgres/auth-repository"; +import { createJwksResolver } from "./vm-oidc"; +import type { Env } from "./types"; + +export const googleCallbackPath = "/oauth/google/sign-in/callback"; +const cookieName = "factorize_google_attempt"; +const maxAge = 600; +const tokenUrl = "https://oauth2.googleapis.com/token"; +const authorizationUrl = "https://accounts.google.com/o/oauth2/v2/auth"; +const jwksUri = "https://www.googleapis.com/oauth2/v3/certs"; +const encoder = new TextEncoder(); + +const base64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); +const random = () => base64url(crypto.getRandomValues(new Uint8Array(32))); +const secureCookie = (env: Env, value: string, maxAge: number) => serialize(cookieName, value, { + path: "/", httpOnly: true, secure: new URL(env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", maxAge, +}); +export const clearGoogleCookie = (env: Env) => secureCookie(env, "", 0); +export const googleEnabled = (env: Env) => !!(env.GOOGLE_SIGN_IN_CLIENT_ID && env.GOOGLE_SIGN_IN_CLIENT_SECRET); +const redirectUri = (env: Env) => new URL(googleCallbackPath, env.APP_ORIGIN).href; +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; +}; +export type GoogleIdentity = { userId: string; tenantId: string; email: string; sessionVersion: number }; +const fail = (status: number, message: string) => ({ status, message } as const); +const expired = () => fail(400, "This Google sign-in expired. Start again from Factorize."); + +async function digestFor(request: Request, env: Env) { + const browser = requestCookie(request, cookieName); + 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) { + const db = databaseFor(env); + const id = crypto.randomUUID(), browser = random(), verifier = random(), nonce = random(); + await db.pool.query("DELETE FROM app.google_sign_in_attempts WHERE expires_at < now()"); + await db.pool.query(`INSERT INTO app.google_sign_in_attempts + (id,browser_digest,verifier,nonce,return_to,connection_id,expires_at) + VALUES($1,$2,$3,$4,$5,$6,now()+interval '10 minutes')`, + [id, await tokenDigest(browser, env.SESSION_SIGNING_SECRET), verifier, nonce, returnTo, connectionId ?? 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", + state: id, nonce, code_challenge: base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(verifier)))), + code_challenge_method: "S256", prompt: "select_account", + }).toString(); + return { authorizationUrl: target.href, cookie: secureCookie(env, browser, maxAge) }; +} + +const jwtHeader = z.object({ alg: z.literal("RS256"), kid: z.string().min(1).max(256) }); +const jwtClaims = z.object({ + iss: z.enum(["https://accounts.google.com", "accounts.google.com"]), + aud: z.string(), + azp: z.string().optional(), + sub: z.string().min(1).max(255), + nonce: z.string(), + exp: z.number().int(), + iat: z.number().int(), + nbf: z.number().int().optional(), + email: z.string().email().max(320), + email_verified: z.literal(true), + hd: z.string().min(1).max(253).optional(), +}); +function decodePart(input: string) { + if (!/^[A-Za-z0-9_-]+$/.test(input)) throw new Error("Invalid Google identity token."); + const padded = input.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat((4 - input.length % 4) % 4); + return Uint8Array.from(atob(padded), char => char.charCodeAt(0)); +} +async function exchangeGoogleCode(env: Env, attempt: Attempt, code: string) { + const token = await fetch(tokenUrl, { + method: "POST", redirect: "error", signal: AbortSignal.timeout(10_000), + body: new URLSearchParams({ + grant_type: "authorization_code", code, client_id: env.GOOGLE_SIGN_IN_CLIENT_ID!, client_secret: env.GOOGLE_SIGN_IN_CLIENT_SECRET!, + redirect_uri: redirectUri(env), code_verifier: attempt.verifier!, + }), + }); + if (!token.ok) throw new Error("Google sign-in was not verified."); + const { id_token } = z.object({ id_token: z.string().min(1).max(16384) }).parse(await token.json()); + const parts = id_token.split("."); + if (parts.length !== 3) throw new Error("Invalid Google identity token."); + const decoder = new TextDecoder("utf-8", { fatal: true }); + const header = jwtHeader.parse(JSON.parse(decoder.decode(decodePart(parts[0])))); + const claims = jwtClaims.parse(JSON.parse(decoder.decode(decodePart(parts[1])))); + const now = Math.floor(Date.now() / 1000); + if (claims.aud !== env.GOOGLE_SIGN_IN_CLIENT_ID || (claims.azp && claims.azp !== claims.aud) || claims.nonce !== attempt.nonce || + claims.exp <= now || claims.exp <= claims.iat || claims.iat > now + 30 || claims.iat < now - maxAge || (claims.nbf ?? 0) > now + 30) throw new Error("Invalid Google sign-in claims."); + const resolveKey = createJwksResolver({ jwksUri }); + const jwk = await resolveKey(header.kid, false); + if (jwk?.kty !== "RSA" || (jwk.alg && jwk.alg !== "RS256")) throw new Error("Google signing key unavailable."); + const key = await crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]); + if (!await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, decodePart(parts[2]), encoder.encode(parts[0] + "." + parts[1]))) { + throw new Error("Google identity signature invalid."); + } + const email = normalizeEmail(claims.email); + return { subject: claims.sub, email, authoritativeEmail: email.endsWith("@gmail.com") || !!claims.hd }; +} + +async function workspace(db: DatabaseClient, userId: string): Promise { + const row = (await db.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`, [userId])).rows[0]; + return row ? { userId, tenantId: row.tenant_id, sessionVersion: row.session_version, email: row.email } : null; +} + +export async function redeemGoogleCallback(request: Request, env: Env) { + const parsed = new URL(request.url); + const state = z.uuid().safeParse(parsed.searchParams.get("state")); + const code = parsed.searchParams.get("code"); + const digest = await digestFor(request, env); + if (!googleEnabled(env) || !state.success || !code || code.length > 4096 || !digest || parsed.searchParams.has("error")) return expired(); + const db = databaseFor(env); + const attempt = await db.transaction(async sql => { + const row = (await sql.query(`SELECT * FROM app.google_sign_in_attempts + WHERE id=$1 AND browser_digest=$2 AND verifier IS NOT NULL AND expires_at>clock_timestamp() FOR UPDATE`, [state.data, digest])).rows[0]; + if (row) await sql.query("UPDATE app.google_sign_in_attempts SET verifier=NULL WHERE id=$1", [row.id]); + return row; + }); + if (!attempt) return expired(); + const google = await exchangeGoogleCode(env, attempt, code); + const linked = (await db.pool.query<{ user_id: string }>(`SELECT user_id FROM app.auth_accounts + WHERE provider='google' AND provider_account_id=$1`, [google.subject])).rows[0]; + if (linked) { + const identity = await workspace(db.pool, linked.user_id); + await db.pool.query("DELETE FROM app.google_sign_in_attempts WHERE id=$1", [attempt.id]); + return identity ? { identity, returnTo: attempt.return_to, connection: attempt.connection_id ?? undefined } : fail(403, "This account cannot access the workspace."); + } + const existing = (await db.pool.query<{ id: string }>("SELECT id FROM app.auth_users WHERE lower(email)=$1", [google.email])).rows[0]; + const updated = await db.pool.query(`UPDATE app.google_sign_in_attempts SET google_subject=$2,email=$3,existing_user_id=$4,email_confirmed=$5 + WHERE id=$1 AND expires_at>clock_timestamp() RETURNING id`, [attempt.id, google.subject, google.email, existing?.id ?? null, google.authoritativeEmail]); + return updated.rowCount ? { pending: true as const } : expired(); +} + +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()${lock ? " FOR UPDATE" : ""}`, [digest])).rows[0]; +} +export async function googlePending(request: Request, env: Env) { + const digest = await digestFor(request, env); + const attempt = digest && await pendingAttempt(databaseFor(env).pool, digest); + return attempt && attempt.email ? { email: attempt.email, mode: attempt.existing_user_id ? "link" as const : attempt.email_confirmed ? "signup" as const : "verify-email" as const } : null; +} +export async function requestGoogleEmail(request: Request, env: Env) { + const browser = await digestFor(request, env); + if (!browser) return false; + const db = databaseFor(env); + const token = random(), digest = await tokenDigest(token, env.SESSION_SIGNING_SECRET); + const attempt = (await db.pool.query<{ email: string }>(`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 + AND expires_at>clock_timestamp() AND (email_sent_at IS NULL OR email_sent_atclock_timestamp()`, [browser, digest]); + return verified.rowCount === 1; +} +export async function googleUsernameAvailable(request: Request, env: Env, username: string) { + const pending = await googlePending(request, env); + if (!pending || pending.mode !== "signup") return null; + return !(await databaseFor(env).pool.query("SELECT 1 FROM app.auth_users WHERE username=$1", [username])).rows.length; +} +export async function finishGoogleSignIn(request: Request, env: Env, input: { username: string } | { password: string }) { + const digest = await digestFor(request, env); + if (!digest) return expired(); + const db = databaseFor(env); + try { + return await db.transaction(async sql => { + const attempt = await pendingAttempt(sql, digest, true); + if (!attempt?.google_subject || !attempt.email) return expired(); + const link = async (userId: string) => sql.query(`INSERT INTO app.auth_accounts(id,user_id,provider,provider_account_id) + VALUES($1,$2,'google',$3)`, [crypto.randomUUID(), userId, attempt.google_subject]); + let userId: string; + if (attempt.existing_user_id) { + if (!("password" in input)) return fail(400, "Confirm your existing Factorize password."); + if (attempt.password_attempts >= 5) return fail(429, "Too many attempts. Start Google sign-in again or reset your password."); + await sql.query("UPDATE app.google_sign_in_attempts SET password_attempts=password_attempts+1 WHERE id=$1", [attempt.id]); + const user = (await sql.query<{ id: string; email_verified: boolean }>("SELECT id,email_verified FROM app.auth_users WHERE id=$1 AND lower(email)=$2 FOR UPDATE", [attempt.existing_user_id, attempt.email])).rows[0]; + const account = user?.email_verified ? (await sql.query<{ password_hash: string | null }>("SELECT password_hash FROM app.auth_accounts WHERE user_id=$1 AND provider='credential'", [user.id])).rows[0] : null; + if (!user || !account?.password_hash || !await verifyPassword(input.password, account.password_hash)) { + return fail(401, "Could not confirm your Factorize password. Try again or reset your password."); + } + userId = user.id; + if (!await workspace(sql, userId)) return fail(403, "This account cannot access the workspace."); + } else { + if (!("username" in input) || !attempt.email_confirmed) return fail(400, "Choose a username to finish signing up."); + userId = crypto.randomUUID(); + await sql.query("INSERT INTO app.auth_users(id,email,email_verified,username) VALUES($1,$2,true,$3)", [userId, attempt.email, input.username]); + await new AuthRepository(db, env).ensurePersonalTeam(sql, userId, attempt.email); + } + await link(userId); + const identity = await workspace(sql, userId); + if (!identity) throw new Error("Google sign-in workspace unavailable."); + await sql.query("DELETE FROM app.google_sign_in_attempts WHERE id=$1", [attempt.id]); + return { identity, returnTo: attempt.return_to, connection: attempt.connection_id ?? undefined }; + }); + } catch (error) { + const pg = error as { code?: string; constraint?: string }; + if (pg.constraint === "auth_users_username_unique") return fail(409, "That username is already taken."); + if (pg.code === "23505") return fail(409, "Account details changed. Start Google sign-in again."); + throw error; + } +} diff --git a/packages/api/src/postgres/auth-repository.ts b/packages/api/src/postgres/auth-repository.ts index 92d9c16c..87da0889 100644 --- a/packages/api/src/postgres/auth-repository.ts +++ b/packages/api/src/postgres/auth-repository.ts @@ -80,7 +80,7 @@ export class AuthRepository { } async requestReset(input: Record) { return this.requestEmail(input, "reset"); } - private async ensurePersonalTeam(client: DatabaseClient, userId: string, email: string) { + async ensurePersonalTeam(client: DatabaseClient, userId: string, email: string) { const existing = await client.query("SELECT tenant_id FROM app.members WHERE user_id=$1 AND role='owner'", [userId]); if (existing.rows.length) return; // Personal ownership never changes membership in an existing team. @@ -126,6 +126,10 @@ export class AuthRepository { } catch (error) { throw error; } } + async hasPassword(userId: string) { + return !!(await this.database.pool.query("SELECT 1 FROM app.auth_accounts WHERE user_id=$1 AND provider='credential' AND password_hash IS NOT NULL", [userId])).rows.length; + } + async changePassword(userId: string, input: Record) { const password = String(input.password ?? ""), currentPassword = String(input.currentPassword ?? ""); if (!validPassword(password) || !validPassword(currentPassword)) return { status: 400, body: { error: "Passwords must have 12–200 characters." } }; diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 2acfef56..85bc3074 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -21,12 +21,20 @@ export const teamSettings = app.table("team_settings", { export const authUsers = app.table("auth_users", { id: uuid("id").primaryKey(), username:text("username").notNull().unique("auth_users_username_unique").default(sql`'user-' || replace(gen_random_uuid()::text,'-','')`), email: text("email").notNull().unique(), emailVerified: boolean("email_verified").notNull().default(false), createdAt: createdAt() }, t => [uniqueIndex("auth_users_email_normalized").on(sql`lower(${t.email})`)]); export const authAccounts = app.table("auth_accounts", { id: uuid("id").primaryKey(), userId: uuid("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), provider: text("provider").notNull(), providerAccountId: text("provider_account_id").notNull(), passwordHash: text("password_hash"), -}, t => [unique().on(t.provider, t.providerAccountId)]); +}, t => [unique().on(t.provider, t.providerAccountId), uniqueIndex("auth_accounts_google_user_unique").on(t.userId).where(sql`${t.provider}='google'`)]); export const oauthConnections = app.table("oauth_connections", { id: uuid("id").primaryKey(), browserDigest: text("browser_digest").notNull(), deviceUserCode: text("device_user_code"), destination: text("destination").notNull(), clientName: text("client_name").notNull(), kind: text("kind").$type<"callback" | "device">().notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), userId: uuid("user_id").references(() => authUsers.id, { onDelete: "cascade" }), readyVersion: integer("ready_version"), ready: boolean("ready").notNull().default(false), usedAt: timestamp("used_at", { withTimezone: true }), }, t => [index("oauth_connections_expires").on(t.expiresAt), check("oauth_connections_kind_check", sql`${t.kind} IN ('callback','device')`)]); +export const googleSignInAttempts = app.table("google_sign_in_attempts", { + id: uuid("id").primaryKey(), browserDigest: text("browser_digest").notNull().unique(), + verifier: text("verifier"), nonce: text("nonce").notNull(), returnTo: text("return_to").notNull(), + connectionId: uuid("connection_id").references(() => 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 }), + 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)]); export const authResetTokens = app.table("auth_reset_tokens", { connectionId: uuid("connection_id").references(() => oauthConnections.id, { onDelete: "set null" }), purpose: text("purpose").$type<"verify" | "reset">().notNull().default("reset"), digest: text("digest").primaryKey(), userId: uuid("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), usedAt: timestamp("used_at", { withTimezone: true }) }, t => [check("auth_reset_tokens_purpose_check", sql`${t.purpose} IN ('verify','reset')`), index("auth_reset_tokens_expiration").on(t.expiresAt,t.digest)]); export const authSessions = app.table("auth_sessions", { id: uuid("id").primaryKey(), userId: uuid("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), revokedAt: timestamp("revoked_at", { withTimezone: true }) }, t => [index("auth_sessions_expiration").on(t.expiresAt,t.id)]); @@ -183,7 +191,7 @@ export const triggerSourceRelations = relations(triggerSources, ({ one }) => ({ })); export const databaseSchema = { - teamSettings, schemaMigrations, tenants, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, + teamSettings, schemaMigrations, tenants, oauthConnections, googleSignInAttempts, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, 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 b5d77d8d..c9c9920f 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/signup", "/auth/password-reset", "/auth/verify", "/auth/verify/request"]); +const authPages = new Set(["/auth/login", "/auth/google", "/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}/`)); @@ -19,7 +19,7 @@ export function securityHeaders(request: Request, response: Response) { const headers = new Headers(response.headers); if (!headers.has("Cache-Control")) headers.set("Cache-Control", "no-store"); headers.set("Content-Security-Policy", STATIC_CSP); - headers.set("Referrer-Policy", "same-origin"); + headers.set("Referrer-Policy", ["/auth/google", "/oauth/google/sign-in/callback"].includes(new URL(request.url).pathname) ? "no-referrer" : "same-origin"); headers.set("X-Content-Type-Options", "nosniff"); headers.set("X-Frame-Options", "DENY"); headers.set("Permissions-Policy", "camera=(), microphone=(), geolocation=()"); diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index 663d736e..13692741 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -6,6 +6,8 @@ export interface Env { ASSETS: Fetcher; APP_ORIGIN: string; MARKETING_ORIGIN?: string; + GOOGLE_SIGN_IN_CLIENT_ID?: string; + GOOGLE_SIGN_IN_CLIENT_SECRET?: string; LINEAR_CLIENT_ID: string; LINEAR_CLIENT_SECRET: string; LINEAR_OAUTH_SCOPES?: string; diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index 6a249802..b655687a 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -1,3 +1,5 @@ +import { googleSignInCallback } from "./auth-api"; +import { googleCallbackPath } from "./google-sign-in"; import { AlarmCoordinator as BaseAlarmCoordinator } from "./alarm-coordinator"; import { wakeMcpDeliveries } from "./postgres/event-match-repository"; import { staticApp, securityHeaders } from "./static-app"; @@ -93,6 +95,7 @@ export class AlarmCoordinator extends BaseAlarmCoordinator { } const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) { if (new URL(request.url).hostname === "git.factorize.sh") return new Response("Not found", { status: 404 }); + if (new URL(request.url).pathname === googleCallbackPath) return googleSignInCallback(request, env); if (new URL(request.url).pathname === "/oauth/x/callback") return request.method === "GET" ? xOAuthCallback(request, env) : new Response("Method not allowed", { status: 405, headers: { Allow: "GET" } }); const oidc = await oidcRequest(request, env); if (oidc) return oidc; diff --git a/packages/api/test/auth-api.test.ts b/packages/api/test/auth-api.test.ts index 894564b1..4cdaacd8 100644 --- a/packages/api/test/auth-api.test.ts +++ b/packages/api/test/auth-api.test.ts @@ -121,11 +121,11 @@ describe("public auth API and cookie security", () => { it("maps current authoritative identity and selected workspace without secrets", async () => { const cookie = await signSession({ ...identity, email: "stale@test.com", exp: Math.floor(Date.now() / 1000) + 100 }, env.SESSION_SIGNING_SECRET); vi.spyOn(IdentityRepository.prototype, "member").mockResolvedValue(member); - vi.mocked(env.DATABASE!.pool.query).mockResolvedValue({ rows: [{ name: "Workspace A" }] } as never); + vi.mocked(env.DATABASE!.pool.query).mockResolvedValue({ rows: [{ name: "Workspace A", has_password: true }] } as never); const response = await call("/api/v1/session", undefined, { Cookie: "factorize_session=" + cookie }); - expect(await contract(response, "/api/v1/session", "GET")).toMatchObject({ authenticated: true, user: { id: identity.userId, email: identity.email }, team: { id: identity.tenantId, name: "Workspace A", role: "owner" }, capabilities: expect.arrayContaining(["triggers:read", "triggers:write"]) }); + expect(await contract(response, "/api/v1/session", "GET")).toMatchObject({ authenticated: true, user: { id: identity.userId, email: identity.email }, team: { id: identity.tenantId, name: "Workspace A", role: "owner" }, hasPassword: true, capabilities: expect.arrayContaining(["triggers:read", "triggers:write"]) }); const query = vi.mocked(env.DATABASE!.pool.query).mock.calls.at(-1)!; - expect(query[1]).toEqual([identity.tenantId]); + expect(query[1]).toEqual([identity.tenantId, identity.userId]); }); it("returns 404 for retired team Skills API routes", async () => { diff --git a/packages/api/test/google-sign-in.postgres.test.ts b/packages/api/test/google-sign-in.postgres.test.ts new file mode 100644 index 00000000..e8732d56 --- /dev/null +++ b/packages/api/test/google-sign-in.postgres.test.ts @@ -0,0 +1,160 @@ +import { expect, it, vi } from "vitest"; +import { protectedApiFetch } from "../src/protected-api"; +import { googleSignInCallback } from "../src/auth-api"; +import { hashPassword } from "../src/auth"; +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 = "some fixture password"; +const signedPart = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url"); + +it.skipIf(!url)("links only after confirming the original password and reuses the existing workspace", async () => { + const f = await loadingFixture(url!); + try { + const h = await harness(f); + 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 email = (await f.db.pool.query<{email:string}>("SELECT email FROM app.auth_users WHERE id=$1", [f.userId])).rows[0].email; + const first = await h.google("existing-subject", email); + expect(first.result.headers.get("Location")).toBe(f.env.APP_ORIGIN + "/auth/google"); + expect(first.result.headers.getSetCookie()).toEqual([]); + const pending = await h.api("GET", "/auth/google/pending", undefined, first.browser); + expect(await pending.json()).toEqual({ email, mode: "link" }); + expect((await h.api("POST", "/auth/google/finish", { password: "incorrect password" }, first.browser)).status).toBe(401); + expect((await f.db.pool.query("SELECT 1 FROM app.auth_accounts WHERE provider='google' AND user_id=$1", [f.userId])).rows).toHaveLength(0); + const finish = await h.api("POST", "/auth/google/finish", { password }, first.browser); + expect(finish.status, await finish.clone().text()).toBe(200); + expect(await finish.json()).toEqual({ ok: true, returnTo: "/clients" }); + const cookie = h.sessionCookie(finish); + expect(await (await h.api("GET", "/session", undefined, cookie)).json()).toMatchObject({ user: { id: f.userId }, team: { id: f.tenantId }, hasPassword: true }); + + // Google can change its email metadata; subsequent sign-in is bound to the stable subject. + const returning = await h.google("existing-subject", "updated@gmail.com"); + expect(returning.result.headers.get("Location")).toBe(f.env.APP_ORIGIN + "/clients"); + expect(await (await h.api("GET", "/session", undefined, h.sessionCookie(returning.result))).json()).toMatchObject({ user: { id: f.userId, email }, team: { id: f.tenantId } }); + const byPassword = await h.api("POST", "/auth/login", { email, password }); + expect(byPassword.status).toBe(200); + expect(await (await h.api("GET", "/session", undefined, h.sessionCookie(byPassword))).json()).toMatchObject({ user: { id: f.userId }, team: { id: f.tenantId } }); + } finally { + vi.unstubAllGlobals(); + await f.cleanup(); + } +}); + +it.skipIf(!url)("checks username availability but enforces it at signup and adds a first password only through email", async () => { + const f = await loadingFixture(url!); + try { + const h = await harness(f); + const newEmail = "google-new-user@gmail.com"; + const { browser, result } = await h.google("signup-subject", newEmail); + expect(result.headers.get("Location")).toBe(f.env.APP_ORIGIN + "/auth/google"); + const checkName = async (username: string) => (await h.api("POST", "/auth/google/username", { username }, browser)).json(); + const competing = "available-now"; + expect(await checkName(competing)).toEqual({ available: true }); + await f.db.pool.query("UPDATE app.auth_users SET username=$2 WHERE id=$1", [f.userId, competing]); + const conflict = await h.api("POST", "/auth/google/finish", { username: competing }, browser); + expect(conflict.status).toBe(409); + expect(await checkName(competing)).toEqual({ available: false }); + expect((await f.db.pool.query("SELECT 1 FROM app.auth_users WHERE lower(email)=$1", [newEmail])).rows).toHaveLength(0); + const finish = await h.api("POST", "/auth/google/finish", { username: "google-factory" }, browser); + expect(finish.status, await finish.clone().text()).toBe(200); + const cookie = h.sessionCookie(finish); + const session = await (await h.api("GET", "/session", undefined, cookie)).json() as { user:{ id: string }; team:{ id: string }; hasPassword:boolean }; + expect(session).toMatchObject({ authenticated: true, user: { email: newEmail }, hasPassword: false }); + expect(session.team.id).not.toBe(f.tenantId); + expect((await h.api("POST", "/auth/password/set-request", undefined)).status).toBe(401); + expect((await h.api("POST", "/auth/password/set-request", undefined, cookie)).status).toBe(200); + expect(h.mail).toHaveLength(1); + expect(h.mail[0].To).toBe(newEmail); + const link = new URL(h.mail[0].TextBody.match(/https:\/\/\S+/)![0]); + const reset = await h.api("POST", "/auth/password-reset/complete", { token: link.searchParams.get("token"), password }); + expect(reset.status, await reset.clone().text()).toBe(200); + const next = h.sessionCookie(reset); + expect(await (await h.api("GET", "/session", undefined, next)).json()).toMatchObject({ user: { id: session.user.id }, team: { id: session.team.id }, hasPassword: true }); + expect((await h.api("POST", "/auth/password/set-request", undefined, next)).status).toBe(409); + } finally { + vi.unstubAllGlobals(); + await f.cleanup(); + } +}); + +it.skipIf(!url)("lets new Google users on a third-party email domain confirm that address without creating a password", async () => { + const f = await loadingFixture(url!); + try { + const h = await harness(f); + const email = "google-external@example.test"; + const { browser, result } = await h.google("external-subject", email); + expect(result.headers.get("Location")).toBe(f.env.APP_ORIGIN + "/auth/google"); + const state = () => h.api("GET", "/auth/google/pending", undefined, browser).then(response => response.json()); + expect(await state()).toEqual({ email, mode: "verify-email" }); + expect((await h.api("POST", "/auth/google/email/request", undefined, browser)).status).toBe(200); + expect(h.mail).toHaveLength(1); + expect(h.mail[0].To).toBe(email); + const confirmation = new URL(h.mail[0].TextBody.match(/https:\/\/\S+/)![0]); + expect(confirmation.pathname).toBe("/auth/google"); + const token = confirmation.searchParams.get("token"); + expect((await h.api("POST", "/auth/google/email/verify", { token }, browser)).status).toBe(200); + expect(await state()).toEqual({ email, mode: "signup" }); + const signup = await h.api("POST", "/auth/google/finish", { username: "external-google" }, browser); + expect(signup.status, await signup.clone().text()).toBe(200); + expect(await (await h.api("GET", "/session", undefined, h.sessionCookie(signup))).json()).toMatchObject({ + authenticated: true, user: { email }, hasPassword: 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", + POSTMARK_SERVER_TOKEN: "fixture", POSTMARK_FROM_EMAIL: "test@example.test", POSTMARK_MESSAGE_STREAM: "outbound", + }); + const pair = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]); + const publicKey = await crypto.subtle.exportKey("jwk", pair.publicKey); + const mail: { To:string; TextBody:string }[] = []; + let token: string; + let challenge: string; + vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => { + if (url === "https://oauth2.googleapis.com/token") { + const body = options!.body as URLSearchParams; + const actual = Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(body.get("code_verifier")!))).toString("base64url"); + expect(actual).toBe(challenge); + expect(body.get("redirect_uri")).toBe(env.APP_ORIGIN + "/oauth/google/sign-in/callback"); + return Response.json({ id_token: token }); + } + if (url === "https://www.googleapis.com/oauth2/v3/certs") return Response.json({ keys: [{ ...publicKey, kid: "test", alg: "RS256", use: "sig" }] }); + if (url === "https://api.postmarkapp.com/email") { + mail.push(JSON.parse(String(options?.body))); + return Response.json({ ErrorCode: 0 }); + } + throw new Error("Unexpected fixture endpoint"); + })); + 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) => { + const start = 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); + expect(authorization.origin).toBe("https://accounts.google.com"); + expect(authorization.searchParams.get("code_challenge_method")).toBe("S256"); + challenge = authorization.searchParams.get("code_challenge")!; + const now = Math.floor(Date.now()/1000); + const encoded = signedPart({ alg: "RS256", kid: "test" }) + "." + signedPart({ + iss: "https://accounts.google.com", sub: subject, aud: env.GOOGLE_SIGN_IN_CLIENT_ID, exp: now+3600, iat: now, + email, email_verified: true, nonce: authorization.searchParams.get("nonce"), + }); + token = encoded + "." + Buffer.from(await crypto.subtle.sign("RSASSA-PKCS1-v1_5", pair.privateKey, new TextEncoder().encode(encoded))).toString("base64url"); + const redirect = new URL(authorization.searchParams.get("redirect_uri")!); + redirect.search = new URLSearchParams({ state: authorization.searchParams.get("state")!, code: "fixture-code" }).toString(); + const result = await googleSignInCallback(new Request(redirect, { headers: { Cookie: browser } }), env); + return { browser, result }; + }; + const sessionCookie = (response: Response) => response.headers.getSetCookie().find(row => row.startsWith("factorize_session="))!.split(";")[0]; + return { google, sessionCookie, api, mail }; +} diff --git a/packages/app/src/features/auth/auth-screen.tsx b/packages/app/src/features/auth/auth-screen.tsx index d8a65c93..c97af449 100644 --- a/packages/app/src/features/auth/auth-screen.tsx +++ b/packages/app/src/features/auth/auth-screen.tsx @@ -1,9 +1,10 @@ +import { GoogleSignInButton } from "./google-sign-in"; import { Button, Input, Label, Page } from "../../shared/ui"; import { useEffect, useState, type FormEvent } from "react"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link, useSearch } from "@tanstack/react-router"; import { api } from "factorize-api-client"; -import { messageOf, refreshIdentity } from "./session"; +import { messageOf, refreshIdentity, sessionQuery } from "./session"; import { AccountSettingsLayout } from "../settings/navigation"; export type AuthMode = "login" | "signup" | "reset" | "verify" | "verify-request" | "password"; @@ -12,12 +13,18 @@ const titles: Record = { verify: "Verify your email", "verify-request": "Resend verification email", password: "Change password", }; export function AuthScreen({ mode, inAccountSettings = false }: { mode: AuthMode; inAccountSettings?: boolean }) { - const search = useSearch({ strict: false }) as { token?: string; returnTo?: string; connection?: string; expired?: boolean }; + const search = useSearch({ strict: false }) as { token?: string; returnTo?: string; connection?: string; expired?: boolean; google?: string }; const [username, setUsername] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [currentPassword, setCurrentPassword] = useState(""); const [notice, setNotice] = useState(""); + const account = useQuery({ ...sessionQuery, enabled: mode === "password" }); + const setPasswordMode = mode === "password" && account.data?.authenticated && account.data.hasPassword === false; + const setup = useMutation({ retry: false, mutationFn: async () => { + const { data, error } = await api.POST("/api/v1/auth/password/set-request"); + if (!data || error) throw new Error(messageOf(error)); + } }); const resetCompletion = mode === "reset" && Boolean(search.token); const continuation = useQuery({ queryKey: ["connection", search.connection], enabled: !!search.connection && !search.token && mode !== "verify", @@ -59,6 +66,12 @@ export function AuthScreen({ mode, inAccountSettings = false }: { mode: AuthMode }, }); function submit(event: FormEvent) { event.preventDefault(); setNotice(""); mutation.mutate(); } + if (setPasswordMode) return +

We’ll email you a link to set your Factorize password for {account.data!.authenticated && account.data!.user.email}.

+ + {setup.isSuccess &&

Check your email for a link to set your password.

} + {setup.error &&

{setup.error.message}

} +
; const showEmail = mode !== "password" && mode !== "verify" && !resetCompletion; const showPassword = mode === "login" || mode === "signup" || mode === "password" || resetCompletion; const content = <> @@ -66,6 +79,12 @@ export function AuthScreen({ mode, inAccountSettings = false }: { mode: AuthMode {!inAccountSettings &&

{titles[mode]}

} {search.connection &&

Connecting {continuation.data?.clientName ?? "your MCP client"}. After verification, review its permissions and choose Allow or Deny.

} {(continuation.error || search.expired) &&

{continuation.error?.message ?? "Your MCP request has expired. Start a new connection from your client."}

} + {mode === "login" && search.google &&

{ + search.google === "account" ? "This Google account couldn’t be used. Create and verify your Factorize account first, or sign in another way." + : search.google === "connection" ? "This MCP connection expired or belongs to another account. Restart from your client." + : "Google sign-in didn’t finish. Start again from Factorize." + }

} + {(mode === "login" || mode === "signup") && } {mode === "login" &&

New to Factorize? Create an account to connect your client.

}
{mode === "signup" && } diff --git a/packages/app/src/features/auth/google-sign-in.tsx b/packages/app/src/features/auth/google-sign-in.tsx new file mode 100644 index 00000000..7fab6a3e --- /dev/null +++ b/packages/app/src/features/auth/google-sign-in.tsx @@ -0,0 +1,124 @@ +import { useEffect, useState, type FormEvent } from "react"; +import { Link, useNavigate, useSearch } from "@tanstack/react-router"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import { api } from "factorize-api-client"; +import { Button, Input, Label, Page } from "../../shared/ui"; +import { messageOf, refreshIdentity } from "./session"; + +export function GoogleSignInButton({ connection, returnTo }: { connection?: string; returnTo?: string }) { + const availability = useQuery({ + queryKey: ["google-sign-in"], retry: false, staleTime: 60_000, + queryFn: async ({ signal }) => (await api.GET("/api/v1/auth/google", { signal })).data?.enabled === true, + }); + const start = useMutation({ + retry: false, + mutationFn: async () => { + const { data, error } = await api.POST("/api/v1/auth/google/start", { body: { connection, returnTo } }); + if (!data || error) throw new Error(messageOf(error)); + return data.authorizationUrl; + }, + onSuccess: url => window.location.assign(url), + }); + if (!availability.data) return null; + return
+ + {start.error &&

{start.error.message}

} +
; +} + +const validUsername = (text: string) => text.length >= 3 && text.length <= 39 && /^[a-z0-9]+(-[a-z0-9]+)*$/.test(text); +export function GoogleSignInScreen() { + const { token } = useSearch({ from: "/auth/google" }); + const navigate = useNavigate(); + const sendEmail = useMutation({ + retry: false, + mutationFn: async () => { + const { data, error } = await api.POST("/api/v1/auth/google/email/request"); + if (!data || error) throw new Error(messageOf(error)); + }, + }); + const verifyEmail = useMutation({ + retry: false, + mutationFn: async (token: string) => { + const { data, error } = await api.POST("/api/v1/auth/google/email/verify", { body: { token } }); + if (!data || error) throw new Error(messageOf(error)); + }, + onSuccess: async () => { + await navigate({ to: "/auth/google", search: {}, replace: true }); + await pending.refetch(); + }, + }); + const [username, setUsername] = useState(""); + const [confirmedName, setConfirmedName] = useState(""); + const [password, setPassword] = useState(""); + const proposedName = username.trim(); + const pending = useQuery({ + queryKey: ["google-sign-in", "pending"], retry: false, + queryFn: async ({ signal }) => { + const { data, error } = await api.GET("/api/v1/auth/google/pending", { signal }); + if (!data || error) throw new Error(messageOf(error)); + return data; + }, + }); + useEffect(() => { + const timer = setTimeout(() => setConfirmedName(proposedName), 350); + return () => clearTimeout(timer); + }, [proposedName]); + const checkingName = pending.data?.mode === "signup" && confirmedName === proposedName && validUsername(confirmedName); + const availability = useQuery({ + queryKey: ["google-sign-in", "username", confirmedName], retry: false, enabled: checkingName, + queryFn: async ({ signal }) => { + const { data, error } = await api.POST("/api/v1/auth/google/username", { signal, body: { username: confirmedName } }); + if (!data || error) throw new Error(messageOf(error)); + return data.available; + }, + }); + const finish = useMutation({ + retry: false, + mutationFn: async () => { + const body = pending.data?.mode === "signup" ? { username: proposedName } : { password }; + const { data, error } = await api.POST("/api/v1/auth/google/finish", { body }); + if (!data || error) throw new Error(messageOf(error)); + return data.returnTo; + }, + onSuccess: async target => { + await refreshIdentity(); + window.location.assign(target); + }, + }); + const signup = pending.data?.mode === "signup"; + const canSubmit = !!pending.data && pending.data.mode !== "verify-email" && !finish.isPending && (!signup || (validUsername(proposedName) && !(checkingName && availability.data === false))); + function submit(event: FormEvent) { event.preventDefault(); if (canSubmit) finish.mutate(); } + const requiresEmail = pending.data?.mode === "verify-email"; + return +

{token || requiresEmail ? "Confirm your email" : signup ? "Choose your Factorize username" : pending.data ? "Connect Google to Factorize" : "Sign in with Google"}

+ {pending.isPending &&

Checking your Google sign-in…

} + {pending.error && !token &&

{pending.error.message}

} + {token ?
+

Confirm this address to continue Google signup. Open this link in the browser where you started.

+ + {verifyEmail.error &&

{verifyEmail.error.message}

} +
: requiresEmail ?
+

We’ll send a confirmation link to {pending.data!.email}. Open it in this browser to finish signing up.

+ + {sendEmail.isSuccess &&

Check your email for the confirmation link.

} + {sendEmail.error &&

{sendEmail.error.message}

} +
: pending.data && +

{signup ? "Your account will use" : "Confirm the existing Factorize password for"} {pending.data.email}.

+ {signup ? <> + +

+ {checkingName && !finish.error && (availability.isFetching ? "Checking username…" : availability.data === true + ? Username available + : availability.data === false ? "That username is already taken." : availability.error ? "Could not check now. Availability will be checked when you continue." : null)} +

+ : <> + + Forgot password? + } + {finish.error &&

{finish.error.message}

} + + } +

Back to sign in

+
; +} diff --git a/packages/app/src/features/auth/routes.tsx b/packages/app/src/features/auth/routes.tsx index 732291ec..2d0fa51b 100644 --- a/packages/app/src/features/auth/routes.tsx +++ b/packages/app/src/features/auth/routes.tsx @@ -4,7 +4,8 @@ import { sessionQuery } from "./session"; import { queryClient } from "../../shared/query-client"; const Screen = lazyRouteComponent(() => import("./auth-screen"), "AuthScreen"); -const validateSearch = (input: Record): { token?: string; returnTo?: string; connection?: string; expired?: boolean } => ({ +const validateSearch = (input: Record): { token?: string; returnTo?: string; connection?: string; expired?: boolean; google?: string } => ({ + google: typeof input.google === "string" ? input.google : undefined, connection: typeof input.connection === "string" ? input.connection : undefined, expired: input.expired === "1", token: typeof input.token === "string" ? input.token : undefined, @@ -23,5 +24,5 @@ export function authRoutes(rootRoute: AnyRootRoute) { } } : {}), }); } - return [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/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/settings/navigation.tsx b/packages/app/src/features/settings/navigation.tsx index 8eb7452b..3ddc6b38 100644 --- a/packages/app/src/features/settings/navigation.tsx +++ b/packages/app/src/features/settings/navigation.tsx @@ -1,3 +1,5 @@ +import { useQuery } from "@tanstack/react-query"; +import { sessionQuery } from "../auth/session"; import type { ReactNode } from "react"; import { Page } from "../../shared/ui"; import { Link } from "@tanstack/react-router"; @@ -30,9 +32,11 @@ export function SettingsLayout({ title, children }: { title: string; children: R } export function AccountSettingsLayout({ title, children }: { title: string; children: ReactNode }) { + const { data: session } = useQuery(sessionQuery); + const passwordLabel = session?.authenticated && session.hasPassword === false ? "Set password" : "Change password"; return Profile API keys - Change password + {passwordLabel} }>{children}; } diff --git a/packages/app/test/functional/google-sign-in.spec.mjs b/packages/app/test/functional/google-sign-in.spec.mjs new file mode 100644 index 00000000..87c63840 --- /dev/null +++ b/packages/app/test/functional/google-sign-in.spec.mjs @@ -0,0 +1,94 @@ +import { expect } from "@playwright/test"; +import { test } from "./fixtures.mjs"; + +test("Google signup checks the current username and handles a conflict on submit", async ({ page, origin }) => { + const names = []; + await page.route("**/api/v1/session", route => route.fulfill({ json: { authenticated: false } })); + await page.route("**/api/v1/auth/google/pending", route => route.fulfill({ json: { email: "new@gmail.com", mode: "signup" } })); + await page.route("**/api/v1/auth/google/username", route => { + const { username } = route.request().postDataJSON(); + names.push(username); + return route.fulfill({ json: { available: username !== "already-taken" } }); + }); + await page.route("**/api/v1/auth/google/finish", route => route.fulfill({ + status: 409, json: { error: { code: "invalid_request", message: "That username is already taken." } }, + })); + await page.goto(origin + "/auth/google"); + await expect(page.getByRole("heading", { name: "Choose your Factorize username" })).toBeVisible(); + const username = page.getByRole("textbox", { name: "Username" }); + await username.fill("new"); + await username.fill("already-taken"); + await expect(page.getByText("That username is already taken.")).toBeVisible(); + expect(names).toEqual(["already-taken"]); + await expect(page.getByRole("button", { name: "Create account" })).toBeDisabled(); + await username.fill("free-name"); + await expect(page.getByText("Username available")).toBeVisible(); + await page.getByRole("button", { name: "Create account" }).click(); + await expect(page.getByRole("alert")).toHaveText("That username is already taken."); + await expect(page.getByText("Username available")).toHaveCount(0); +}); + +test("Google linking requires a Factorize password and offers recovery", async ({ page, origin }) => { + let sent; + await page.route("**/api/v1/session", route => route.fulfill({ json: { authenticated: false } })); + await page.route("**/api/v1/auth/google/pending", route => route.fulfill({ json: { email: "owner@example.test", mode: "link" } })); + await page.route("**/api/v1/auth/google/finish", route => { + sent = route.request().postDataJSON(); + return route.fulfill({ status: 401, json: { error: { code: "invalid_token", message: "Could not confirm your Factorize password." } } }); + }); + await page.goto(origin + "/auth/google"); + await expect(page.getByRole("heading", { name: "Connect Google to Factorize" })).toBeVisible(); + await expect(page.getByRole("link", { name: "Forgot password?" })).toHaveAttribute("href", "/auth/password-reset"); + await page.getByLabel("Factorize password").fill("fixture password"); + await page.getByRole("button", { name: "Connect and sign in" }).click(); + await expect(page.getByRole("alert")).toContainText("Could not confirm"); + expect(sent).toEqual({ password: "fixture password" }); +}); + +test("first password is set by email and settings switch to Change password", async ({ page, origin }) => { + let hasPassword = false; + let mailed = 0; + await page.route("**/api/v1/session", route => route.fulfill({ json: { + authenticated: true, user: { id: "owner", email: "google-user@gmail.com" }, + team: { id: "workspace", name: "Workspace", role: "owner" }, capabilities: [], hasPassword, + } })); + await page.route("**/api/v1/auth/password/set-request", route => { + mailed++; + return route.fulfill({ json: { ok: true } }); + }); + await page.goto(origin + "/settings/password"); + await expect(page.getByRole("heading", { name: "Set password" })).toBeVisible(); + await page.getByRole("button", { name: "Email me a link" }).click(); + await expect(page.getByRole("status")).toHaveText("Check your email for a link to set your password."); + expect(mailed).toBe(1); + hasPassword = true; + await page.reload(); + await expect(page.getByRole("heading", { name: "Change password" })).toBeVisible(); + await expect(page.getByLabel("Current password")).toBeVisible(); +}); + +test("Google signup can confirm an external email and then choose a username", async ({ page, origin }) => { + let confirmed = false; + let request = 0; + await page.route("**/api/v1/session", route => route.fulfill({ json: { authenticated: false } })); + await page.route("**/api/v1/auth/google/pending", route => route.fulfill({ json: { + email: "owner@example.test", mode: confirmed ? "signup" : "verify-email", + } })); + await page.route("**/api/v1/auth/google/email/request", route => { + request++; + return route.fulfill({ json: { ok: true } }); + }); + await page.route("**/api/v1/auth/google/email/verify", route => { + expect(route.request().postDataJSON()).toEqual({ token: "test-confirmation" }); + confirmed = true; + return route.fulfill({ json: { ok: true } }); + }); + await page.goto(origin + "/auth/google"); + await page.getByRole("button", { name: "Email me a confirmation link" }).click(); + await expect(page.getByRole("status")).toHaveText("Check your email for the confirmation link."); + expect(request).toBe(1); + await page.goto(origin + "/auth/google?token=test-confirmation"); + await page.getByRole("button", { name: "Confirm email" }).click(); + await expect(page.getByRole("heading", { name: "Choose your Factorize username" })).toBeVisible(); + await expect(page).toHaveURL(origin + "/auth/google"); +}); diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 47115125..92a47a84 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -518,6 +518,25 @@ Before deploying, configure `POSTMARK_SERVER_TOKEN` as a **production GitHub env `APP_ORIGIN` must be the canonical HTTPS origin, without a trailing slash. Run `npm run auth:validate-email --workspace=factorize` manually when needed: it checks the server token/stream with Postmark and sends one preflight email from/to the configured sender, rejecting unverified senders or sending failures. It prints no credentials. Missing configuration fails the manual check. The deploy workflow does not run this check or send a preflight email. Runtime signup and recovery also fail closed if configuration or delivery fails; users can resend verification after a delivery failure. Local mail testing needs an HTTPS origin and a separate Postmark test server/sender; automated tests mock Postmark and never send mail. +### Optional Google sign-in + +Create a **Web application** OAuth client in Google Cloud. Register exactly +`/oauth/google/sign-in/callback` as an authorized redirect URI +(`https://app.factorize.sh/oauth/google/sign-in/callback` on the hosted deployment). +Complete Google's OAuth consent screen setup for your intended audience. Set +`GOOGLE_SIGN_IN_CLIENT_ID` and `GOOGLE_SIGN_IN_CLIENT_SECRET` as Worker secrets. +The Google button is hidden unless both values are set. Apply migration 0104 +using the normal database deployment step. Google sign-in is separate from +Factorize's MCP authorization clients and uses only `openid email`. + +A first Google sign-in matching an existing verified Factorize account +requires its current Factorize password; email alone never links accounts. +New Google users choose a unique Factorize username. For addresses Google +does not manage directly, Factorize emails a confirmation link to be opened +in the browser that started signup. Once signed in, Google-first users can +use **Set password** to receive a password link at their verified email. +Keep Postmark configured for address confirmation and password recovery. + ### 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 40d07f6c..a76f159f 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -1668,6 +1668,8 @@ paths: type: string format: date-time pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z))$ + hasPassword: + type: boolean required: - authenticated - user @@ -1697,6 +1699,503 @@ paths: security: [] x-browser-auth-operation: session x-owner-session-required: false + /api/v1/auth/google: + get: + summary: Check whether Google sign-in is configured + 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 + required: + - enabled + 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_google + tags: + - auth + security: [] + x-browser-auth-operation: google-available + x-owner-session-required: false + /api/v1/auth/google/start: + post: + summary: Start browser-bound Google sign-in + 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" + "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_google_start + tags: + - auth + security: [] + x-browser-auth-operation: google-start + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + returnTo: + type: string + maxLength: 8192 + connection: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + additionalProperties: false + /api/v1/auth/google/pending: + get: + summary: Read Google signup or linking steps for the current browser + 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: + email: + type: string + format: email + pattern: ^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$ + mode: + type: string + enum: + - link + - signup + - verify-email + required: + - email + - mode + 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_google_pending + tags: + - auth + security: [] + x-browser-auth-operation: google-pending + x-owner-session-required: false + /api/v1/auth/google/email/request: + post: + summary: Send a verification link for a new Google signup + 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" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_auth_google_email_request + tags: + - auth + security: [] + x-browser-auth-operation: google-email-request + x-owner-session-required: false + /api/v1/auth/google/email/verify: + post: + summary: Verify the signup email in the initiating browser + 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_google_email_verify + tags: + - auth + security: [] + x-browser-auth-operation: google-email-verify + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + token: + type: string + minLength: 1 + maxLength: 512 + writeOnly: true + required: + - token + additionalProperties: false + /api/v1/auth/google/username: + post: + summary: Check username availability during Google signup + 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: + available: + type: boolean + required: + - available + 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_google_username + tags: + - auth + security: [] + x-browser-auth-operation: google-username + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + username: + type: string + minLength: 3 + maxLength: 39 + pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ + required: + - username + additionalProperties: false + /api/v1/auth/google/finish: + post: + summary: Choose a username or confirm your existing Factorize password + 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_google_finish + tags: + - auth + security: [] + x-browser-auth-operation: google-finish + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + anyOf: + - type: object + properties: + username: + type: string + minLength: 3 + maxLength: 39 + pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ + required: + - username + additionalProperties: false + - type: object + properties: + password: + type: string + minLength: 12 + maxLength: 200 + writeOnly: true + required: + - password + additionalProperties: false + /api/v1/auth/password/set-request: + post: + summary: Email a link to set the first password + 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" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_auth_password_set_request + tags: + - auth + security: + - cookieAuth: [] + x-browser-auth-operation: password-set-request + x-owner-session-required: true /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 50404e7c..e63f2c25 100644 --- a/packages/docs/self-hosting/configuration.mdx +++ b/packages/docs/self-hosting/configuration.mdx @@ -23,6 +23,25 @@ Before deploying, configure `POSTMARK_SERVER_TOKEN` as a **production GitHub env `APP_ORIGIN` must be the canonical HTTPS origin, without a trailing slash. Run `npm run auth:validate-email --workspace=factorize` manually when needed: it checks the server token/stream with Postmark and sends one preflight email from/to the configured sender, rejecting unverified senders or sending failures. It prints no credentials. Missing configuration fails the manual check. The deploy workflow does not run this check or send a preflight email. Runtime signup and recovery also fail closed if configuration or delivery fails; users can resend verification after a delivery failure. Local mail testing needs an HTTPS origin and a separate Postmark test server/sender; automated tests mock Postmark and never send mail. +### Optional Google sign-in + +Create a **Web application** OAuth client in Google Cloud. Register exactly +`/oauth/google/sign-in/callback` as an authorized redirect URI +(`https://app.factorize.sh/oauth/google/sign-in/callback` on the hosted deployment). +Complete Google's OAuth consent screen setup for your intended audience. Set +`GOOGLE_SIGN_IN_CLIENT_ID` and `GOOGLE_SIGN_IN_CLIENT_SECRET` as Worker secrets. +The Google button is hidden unless both values are set. Apply migration 0104 +using the normal database deployment step. Google sign-in is separate from +Factorize's MCP authorization clients and uses only `openid email`. + +A first Google sign-in matching an existing verified Factorize account +requires its current Factorize password; email alone never links accounts. +New Google users choose a unique Factorize username. For addresses Google +does not manage directly, Factorize emails a confirmation link to be opened +in the browser that started signup. Once signed in, Google-first users can +use **Set password** to receive a password link at their verified email. +Keep Postmark configured for address confirmation and password recovery. + ### 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. From 39b4d6b30c6bae63f6013e5f02b6994fb97c21bb Mon Sep 17 00:00:00 2001 From: Brendan Asselstine Date: Tue, 24 Nov 2026 11:28:09 -0700 Subject: [PATCH 2/3] Require fresh Google proof for password setup and managed recovery --- packages/api-client/src/schema.d.ts | 73 +++++++- .../api/migrations/0104_google_sign_in.sql | 13 ++ packages/api/src/api-contract.ts | 3 +- packages/api/src/auth-api.ts | 49 ++++-- packages/api/src/auth-email.ts | 9 +- packages/api/src/google-sign-in.ts | 161 +++++++++++++++--- packages/api/src/postgres/auth-repository.ts | 18 +- packages/api/src/postgres/schema.ts | 3 +- packages/api/src/types.ts | 1 + packages/api/src/worker.ts | 3 +- .../api/test/google-sign-in.postgres.test.ts | 141 +++++++++++++-- packages/api/wrangler.jsonc | 1 + .../app/src/features/auth/auth-screen.tsx | 17 +- .../app/src/features/auth/google-sign-in.tsx | 29 +++- .../test/functional/google-sign-in.spec.mjs | 23 ++- packages/docs/llms-full.txt | 15 +- packages/docs/openapi.yaml | 90 +++++++++- packages/docs/self-hosting/configuration.mdx | 15 +- 18 files changed, 577 insertions(+), 87 deletions(-) diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 3c13e801..74e6152d 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -396,6 +396,26 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/auth/google/password/complete": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Set the Factorize password with fresh Google proof and email confirmation + * @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_google_password_complete"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/auth/google/finish": { parameters: { query?: never; @@ -426,7 +446,7 @@ export interface paths { get?: never; put?: never; /** - * Email a link to set the first password + * Start fresh Google verification before setting or recovering a password * @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_password_set_request"]; @@ -3211,6 +3231,7 @@ export interface operations { capabilities: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "integrations:read" | "integrations:write" | "vms:read" | "vms:edit" | "apps:manage")[]; /** Format: date-time */ expiresAt: string; + googleManagedRecovery?: boolean; hasPassword?: boolean; }; }; @@ -3326,7 +3347,7 @@ export interface operations { /** Format: email */ email: string; /** @enum {string} */ - mode: "link" | "signup" | "verify-email"; + mode: "link" | "signup" | "verify-email" | "set-password"; }; }; }; @@ -3458,6 +3479,50 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + post_api_v1_auth_google_password_complete: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + token: string; + 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": { + /** @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_google_finish: { parameters: { query?: never; @@ -3523,8 +3588,8 @@ export interface operations { }; content: { "application/json": { - /** @constant */ - ok: true; + /** Format: uri */ + authorizationUrl: string; }; }; }; diff --git a/packages/api/migrations/0104_google_sign_in.sql b/packages/api/migrations/0104_google_sign_in.sql index f59baa53..339d60a4 100644 --- a/packages/api/migrations/0104_google_sign_in.sql +++ b/packages/api/migrations/0104_google_sign_in.sql @@ -16,3 +16,16 @@ CREATE TABLE app.google_sign_in_attempts ( ); CREATE INDEX google_sign_in_attempts_expiry ON app.google_sign_in_attempts(expires_at); CREATE UNIQUE INDEX auth_accounts_google_user_unique ON app.auth_accounts(user_id) WHERE provider='google'; + +ALTER TABLE app.auth_users + ADD COLUMN google_recovery_managed boolean NOT NULL DEFAULT false, + ADD COLUMN google_recovery_candidate text, + ADD COLUMN google_recovery_address_confirmed boolean NOT NULL DEFAULT false, + ADD COLUMN google_recovery_suspended boolean NOT NULL DEFAULT false, + ADD COLUMN google_recovery_observed_at integer NOT NULL DEFAULT 0, + ADD COLUMN google_recovery_revision integer NOT NULL DEFAULT 0; +ALTER TABLE app.google_sign_in_attempts + ADD COLUMN password_user_id uuid REFERENCES app.auth_users(id) ON DELETE CASCADE, + ADD COLUMN recovery_revision integer, + ADD COLUMN provider_observed_at integer NOT NULL DEFAULT 0, + ADD COLUMN provider_managed_email boolean NOT NULL DEFAULT false; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 02f20796..3c8452ae 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -238,8 +238,9 @@ export const API_ROUTES: RouteContract[] = [ authRoute("POST", "/api/v1/auth/google/email/request", "google-email-request", "Send a verification link for a new Google signup", authSuccess), authRoute("POST", "/api/v1/auth/google/email/verify", "google-email-verify", "Verify the signup email in the initiating browser", authSuccess, authInputs.verify), authRoute("POST", "/api/v1/auth/google/username", "google-username", "Check username availability during Google signup", googleUsernameResult, authInputs.googleUsername), + 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", "Email a link to set the first password", authSuccess),ownerSession:true}, + {...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("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 b65501d5..2d9d5d17 100644 --- a/packages/api/src/auth-api.ts +++ b/packages/api/src/auth-api.ts @@ -1,4 +1,4 @@ -import { clearGoogleCookie, finishGoogleSignIn, googleEnabled, googlePending, googleUsernameAvailable, redeemGoogleCallback, requestGoogleEmail, startGoogleSignIn, verifyGoogleEmail, type GoogleIdentity } from "./google-sign-in"; +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"; import { ACCESS_SCOPES } from "./access-tokens"; @@ -37,6 +37,7 @@ export const sessionResponse = z.discriminatedUnion("authenticated", [ team: z.object({ id: z.string(), name: z.string().nullable(), role: z.literal("owner") }).strict(), capabilities: z.array(z.enum(SESSION_SCOPES)), expiresAt: z.iso.datetime(), + googleManagedRecovery: z.boolean().optional(), hasPassword: z.boolean().optional(), }).strict(), ]); @@ -47,7 +48,7 @@ export const connectionStartSuccess = z.object({ connection: z.uuid(), clientNam export const connectionResumeInput = z.object({ connection: z.uuid() }).strict(); export const googleAvailability = z.object({ enabled: z.boolean() }); export const googleStartResult = z.object({ authorizationUrl: z.url() }); -export const googlePendingResult = z.object({ email: z.email(), mode: z.enum(["link", "signup", "verify-email"]) }); +export const googlePendingResult = z.object({ email: z.email(), mode: z.enum(["link", "signup", "verify-email", "set-password"]) }); export const googleUsernameResult = z.object({ available: z.boolean() }); export const loginSuccess = authSuccess.extend({ returnTo: z.string() }); @@ -72,13 +73,22 @@ const failure = (status: number, message: string) => authJson({ error: { code: s function sessionCookie(env: Env, value: string, maxAge: number): string { return serialize("factorize_session", value, { httpOnly: true, secure: new URL(env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/", maxAge }); } +async function limitGoogleStart(request: Request, env: Env) { + if (!env.GOOGLE_SIGN_IN_START_LIMIT) return failure(503, "Google sign-in is temporarily unavailable."); + // Cloudflare sets CF-Connecting-IP on ingress. Do not trust X-Forwarded-For. + const { success } = await env.GOOGLE_SIGN_IN_START_LIMIT.limit({ key: request.headers.get("CF-Connecting-IP") ?? "unknown" }); + if (success) return null; + const response = failure(429, "Too many Google sign-in attempts. Try again in a minute."); + response.headers.set("Retry-After", "60"); + return response; +} async function currentSession(request: Request, env: Env): Promise { const session = await readSession(requestCookie(request, "factorize_session"), env.SESSION_SIGNING_SECRET); if (!session) return null; const member = await new IdentityRepository(databaseFor(env), session.tenantId).member(session.userId); return member?.role === "owner" && member.sessionVersion === session.sessionVersion ? { ...session, email: member.email } : null; } -export type AuthAction = "google-available" | "google-start" | "google-pending" | "google-username" | "google-email-request" | "google-email-verify" | "google-finish" | "password-set-request" | "profile" | "profile-update" | "connection-start" | "connection-resume" | "session" | "login" | "signup" | "verification-request" | "verification" | "reset-request" | "reset" | "password" | "logout" | "consent-preview" | "consent-decision" | "device-preview" | "device-decision"; +export type AuthAction = "google-available" | "google-start" | "google-pending" | "google-username" | "google-email-request" | "google-email-verify" | "google-password-complete" | "google-finish" | "password-set-request" | "profile" | "profile-update" | "connection-start" | "connection-resume" | "session" | "login" | "signup" | "verification-request" | "verification" | "reset-request" | "reset" | "password" | "logout" | "consent-preview" | "consent-decision" | "device-preview" | "device-decision"; export async function executeAuth(action: AuthAction, request: Request, env: Env, input: Record = {}): Promise { // These operations use browser cookies only. Ignore neither a bad bearer nor a @@ -88,6 +98,8 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env if (action.startsWith("google-")) { if (!googleEnabled(env)) return failure(404, "Google sign-in is not available."); if (action === "google-start") { + const limited = await limitGoogleStart(request, env); + if (limited) return limited; const parsed = authInputs.googleStart.parse(input); if (parsed.connection) { const pending = await connectionFor(env, parsed.connection); @@ -113,6 +125,13 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env const available = await googleUsernameAvailable(request, env, authInputs.googleUsername.parse(input).username); return available === null ? failure(400, "This Google signup expired. Start again from Factorize.") : authJson({ available }); } + if (action === "google-password-complete") { + const result = await finishGooglePassword(request, env, authInputs.reset.parse(input)); + if ("status" in result) return failure(result.status, result.message); + const response = await signedIn(env, result.identity, { ok: true, returnTo: "/settings/password" }); + response.headers.append("Set-Cookie", clearGoogleCookie(env)); + return response; + } if (action === "google-finish") { const result = await finishGoogleSignIn(request, env, authInputs.googleFinish.parse(input)); if ("status" in result) return failure(result.status, result.message); @@ -124,10 +143,19 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env if (action === "password-set-request") { const session = await currentSession(request, env); if (!session) return failure(401, "Sign in before setting a password."); - const repo = new AuthRepository(databaseFor(env), env); - if (await repo.hasPassword(session.userId)) return failure(409, "You already have a password. Use Change password instead."); - await repo.requestReset({ email: session.email }); - return authJson({ ok: true }); + if (!googleEnabled(env)) return failure(404, "Google sign-in is not available."); + const limited = await limitGoogleStart(request, env); + if (limited) return limited; + const account = (await databaseFor(env).pool.query<{ google_recovery_managed: boolean; google_linked: boolean; has_password: boolean }>(`SELECT google_recovery_managed, + EXISTS (SELECT 1 FROM app.auth_accounts WHERE user_id=u.id AND provider='google') google_linked, + EXISTS (SELECT 1 FROM app.auth_accounts WHERE user_id=u.id AND provider='credential' AND password_hash IS NOT NULL) has_password + FROM app.auth_users u WHERE id=$1`, [session.userId])).rows[0]; + if (!account?.google_linked) return failure(400, "Use password recovery for this account."); + if (account.has_password && !account.google_recovery_managed) return failure(409, "You already have a password. Use Change password instead."); + const { cookie, authorizationUrl } = await startGoogleSignIn(env, "/settings/password", undefined, session.userId); + const response = authJson({ authorizationUrl }); + response.headers.append("Set-Cookie", cookie); + return response; } if (action === "connection-start") { try { @@ -167,12 +195,13 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env } if (action === "session") { if (!session) return authJson({ authenticated: false }); - const workspace = (await databaseFor(env).pool.query<{ name: string | null; has_password: boolean }>(`SELECT name, EXISTS (SELECT 1 FROM app.auth_accounts + const workspace = (await databaseFor(env).pool.query<{ name: string | null; has_password: boolean; google_managed_recovery: boolean }>(`SELECT name, + (SELECT google_recovery_managed FROM app.auth_users WHERE id=$2) google_managed_recovery, EXISTS (SELECT 1 FROM app.auth_accounts WHERE user_id=$2 AND provider='credential' AND password_hash IS NOT NULL) has_password FROM app.tenants WHERE id=$1`, [session.tenantId, session.userId])).rows[0]; return authJson(sessionResponse.parse({ authenticated: true, user: { id: session.userId, email: session.email }, team: { id: session.tenantId, name: workspace?.name ?? null, role: "owner" }, - capabilities: [...SESSION_SCOPES], hasPassword: workspace?.has_password, expiresAt: new Date(session.exp * 1000).toISOString(), + capabilities: [...SESSION_SCOPES], hasPassword: workspace?.has_password, googleManagedRecovery: workspace?.google_managed_recovery, expiresAt: new Date(session.exp * 1000).toISOString(), })); } if (action === "device-preview" || action === "device-decision") { @@ -262,7 +291,7 @@ export async function googleSignInCallback(request: Request, env: Env) { if (request.headers.has("Authorization")) return redirect("/auth/login?google=failed"); try { const result = await redeemGoogleCallback(request, env); - if ("status" in result) return redirect(result.status === 403 ? "/auth/login?google=account" : "/auth/login?google=failed"); + 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 ("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"); diff --git a/packages/api/src/auth-email.ts b/packages/api/src/auth-email.ts index 678f28d5..c6e5efcd 100644 --- a/packages/api/src/auth-email.ts +++ b/packages/api/src/auth-email.ts @@ -8,10 +8,11 @@ export function validateAuthEmailConfig(env: Env): void { } } -export async function sendAuthEmail(env: Env, email: string, token: string, purpose: "verify" | "reset" | "google-verify", connection?: string): Promise { +export async function sendAuthEmail(env: Env, email: string, token: string, purpose: "verify" | "reset" | "google-verify" | "google-password", connection?: string): Promise { validateAuthEmailConfig(env); - const action = purpose === "google-verify" ? "Confirm your Factorize email" : purpose === "verify" ? "Verify your Factorize email" : "Reset your Factorize password"; - const url = new URL(purpose === "google-verify" ? "/auth/google" : purpose === "verify" ? "/auth/verify" : "/auth/password-reset", env.APP_ORIGIN); + const google = purpose === "google-verify" || purpose === "google-password"; + const action = purpose === "google-password" ? "Set your Factorize password" : purpose === "google-verify" ? "Confirm your Factorize email" : purpose === "verify" ? "Verify your Factorize email" : "Reset your Factorize password"; + const url = new URL(google ? "/auth/google" : purpose === "verify" ? "/auth/verify" : "/auth/password-reset", env.APP_ORIGIN); url.searchParams.set("token", token); if (connection) url.searchParams.set("connection", connection); const response = await fetch("https://api.postmarkapp.com/email", { @@ -19,7 +20,7 @@ export async function sendAuthEmail(env: Env, email: string, token: string, purp headers: { "Content-Type": "application/json", "X-Postmark-Server-Token": env.POSTMARK_SERVER_TOKEN! }, body: JSON.stringify({ From: env.POSTMARK_FROM_EMAIL, To: email, MessageStream: env.POSTMARK_MESSAGE_STREAM, Subject: action, - TextBody: purpose === "google-verify" ? `Confirm your email in the original browser: ${url}\n\nThis link expires when your Google signup attempt expires. If you did not request this, ignore this email.` : `${purpose === "verify" ? "Verify your email" : "Reset your password"}: ${url}\n\nThis link expires in one hour and can be used once. If you did not request this, ignore this email.` }), + TextBody: google ? `${action} in the browser where you confirmed Google: ${url}\n\nThis link expires when your Google verification attempt expires. If you did not request this, ignore this email.` : `${purpose === "verify" ? "Verify your email" : "Reset your password"}: ${url}\n\nThis link expires in one hour and can be used once. If you did not request this, ignore this email.` }), }); const result = await response.json() as { ErrorCode?: number }; if (!response.ok || result.ErrorCode !== 0) throw new Error("Postmark could not deliver authentication email."); diff --git a/packages/api/src/google-sign-in.ts b/packages/api/src/google-sign-in.ts index ec89a5a3..9e9b5cde 100644 --- a/packages/api/src/google-sign-in.ts +++ b/packages/api/src/google-sign-in.ts @@ -1,6 +1,6 @@ import { serialize } from "hono/utils/cookie"; import { z } from "zod"; -import { normalizeEmail, tokenDigest, verifyPassword } from "./auth"; +import { hashPassword, normalizeEmail, tokenDigest, verifyPassword } from "./auth"; import { sendAuthEmail } from "./auth-email"; import { requestCookie } from "./session"; import { databaseFor, type DatabaseClient } from "./postgres/database"; @@ -9,7 +9,7 @@ import { createJwksResolver } from "./vm-oidc"; import type { Env } from "./types"; export const googleCallbackPath = "/oauth/google/sign-in/callback"; -const cookieName = "factorize_google_attempt"; +const cookieName = (env: Env) => new URL(env.APP_ORIGIN).protocol === "https:" ? "__Host-factorize_google_attempt" : "factorize_google_attempt"; const maxAge = 600; const tokenUrl = "https://oauth2.googleapis.com/token"; const authorizationUrl = "https://accounts.google.com/o/oauth2/v2/auth"; @@ -18,7 +18,7 @@ const encoder = new TextEncoder(); const base64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); const random = () => base64url(crypto.getRandomValues(new Uint8Array(32))); -const secureCookie = (env: Env, value: string, maxAge: number) => serialize(cookieName, value, { +const secureCookie = (env: Env, value: string, maxAge: number) => serialize(cookieName(env), value, { path: "/", httpOnly: true, secure: new URL(env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", maxAge, }); export const clearGoogleCookie = (env: Env) => secureCookie(env, "", 0); @@ -27,24 +27,24 @@ 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; }; export type GoogleIdentity = { userId: string; tenantId: string; email: string; sessionVersion: number }; const fail = (status: number, message: string) => ({ status, message } as const); const expired = () => fail(400, "This Google sign-in expired. Start again from Factorize."); async function digestFor(request: Request, env: Env) { - const browser = requestCookie(request, cookieName); + const browser = requestCookie(request, cookieName(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) { +export async function startGoogleSignIn(env: Env, returnTo: string, connectionId?: string, passwordUserId?: string) { const db = databaseFor(env); const id = crypto.randomUUID(), browser = random(), verifier = random(), nonce = random(); - await db.pool.query("DELETE FROM app.google_sign_in_attempts WHERE expires_at < now()"); await db.pool.query(`INSERT INTO app.google_sign_in_attempts - (id,browser_digest,verifier,nonce,return_to,connection_id,expires_at) - VALUES($1,$2,$3,$4,$5,$6,now()+interval '10 minutes')`, - [id, await tokenDigest(browser, env.SESSION_SIGNING_SECRET), verifier, nonce, returnTo, connectionId ?? null]); + (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]); 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,11 @@ export async function startGoogleSignIn(env: Env, returnTo: string, connectionId return { authorizationUrl: target.href, cookie: secureCookie(env, browser, maxAge) }; } +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 { @@ -109,6 +114,61 @@ async function workspace(db: DatabaseClient, userId: string): Promise (await sql.query(`SELECT + email,google_recovery_managed,google_recovery_suspended,google_recovery_candidate,google_recovery_address_confirmed,google_recovery_observed_at,google_recovery_revision + FROM app.auth_users WHERE id=$1 AND email_verified FOR UPDATE`, [userId])).rows[0]; + +async function retireEmailAuthority(sql: DatabaseClient, userId: string, email: string | null, candidate: string | null = null, confirmedByFactorize = false) { + // The user row is held by the caller. Pending Google password attempts are + // fenced by this revision, even when email later changes back to an old value. + const row = (await sql.query(`UPDATE app.auth_users + SET email=COALESCE($2,email),google_recovery_suspended=($2::text IS NULL),google_recovery_candidate=$3,google_recovery_address_confirmed=$4,google_recovery_revision=google_recovery_revision+1 + WHERE id=$1 RETURNING email,google_recovery_managed,google_recovery_suspended,google_recovery_candidate,google_recovery_address_confirmed,google_recovery_observed_at,google_recovery_revision`, [userId, email, candidate, confirmedByFactorize])).rows[0]!; + await sql.query("UPDATE app.auth_reset_tokens SET used_at=clock_timestamp() WHERE user_id=$1 AND used_at IS NULL", [userId]); + await sql.query("UPDATE app.members SET email=COALESCE($2,email),session_version=session_version+1 WHERE user_id=$1", [userId, email]); + await sql.query("UPDATE app.auth_sessions SET revoked_at=clock_timestamp() WHERE user_id=$1 AND revoked_at IS NULL", [userId]); + return row; +} + +async function updateManagedEmail(sql: DatabaseClient, userId: string, email: string, confirmedByFactorize = false) { + // Account creation does not take the recovery lock. The unique index remains + // the authority, including if a competing signup claims the email after lookup. + await sql.query("SAVEPOINT google_recovery_email"); + try { + const updated = await retireEmailAuthority(sql, userId, email, null, confirmedByFactorize); + await sql.query("RELEASE SAVEPOINT google_recovery_email"); + return updated; + } catch (error) { + if ((error as { code?: string }).code !== "23505") throw error; + await sql.query("ROLLBACK TO SAVEPOINT google_recovery_email"); + await sql.query("RELEASE SAVEPOINT google_recovery_email"); + return null; + } +} + +async function syncGoogleRecovery(sql: DatabaseClient, userId: string, google: { email: string; authoritativeEmail: boolean; issuedAt: number }) { + let recovery = await lockRecovery(sql, userId); + if (!recovery || !recovery.google_recovery_managed) return { recovery, email: recovery?.email }; + const observedEmail = recovery.google_recovery_candidate ?? recovery.email; + const confirmed = google.authoritativeEmail || (recovery.email === google.email && recovery.google_recovery_address_confirmed); + // A delayed callback cannot put an older observed address back in charge. + if (google.issuedAt <= recovery.google_recovery_observed_at && + (google.email !== observedEmail || recovery.google_recovery_suspended === confirmed)) { + return { recovery, email: undefined }; + } + await sql.query("UPDATE app.auth_users SET google_recovery_observed_at=GREATEST(google_recovery_observed_at,$2) WHERE id=$1", [userId, google.issuedAt]); + const sameEmail = recovery.email === google.email; + if (sameEmail && !recovery.google_recovery_suspended && confirmed) return { recovery, email: recovery.email }; + if (google.authoritativeEmail) { + const updated = await updateManagedEmail(sql, userId, google.email); + if (updated) return { recovery: updated, email: updated.email }; + } + if (!recovery.google_recovery_suspended || recovery.google_recovery_candidate !== google.email) recovery = await retireEmailAuthority(sql, userId, null, google.email); + const occupied = (await sql.query("SELECT 1 FROM app.auth_users WHERE lower(email)=$1 AND id<>$2", [google.email, userId])).rows.length; + return { recovery, email: occupied ? undefined : google.email }; +} + export async function redeemGoogleCallback(request: Request, env: Env) { const parsed = new URL(request.url); const state = z.uuid().safeParse(parsed.searchParams.get("state")); @@ -126,39 +186,56 @@ export async function redeemGoogleCallback(request: Request, env: Env) { const google = await exchangeGoogleCode(env, attempt, code); const linked = (await db.pool.query<{ user_id: string }>(`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) { - const identity = await workspace(db.pool, linked.user_id); - await db.pool.query("DELETE FROM app.google_sign_in_attempts WHERE id=$1", [attempt.id]); - return identity ? { identity, returnTo: attempt.return_to, connection: attempt.connection_id ?? undefined } : fail(403, "This account cannot access the workspace."); + return db.transaction(async sql => { + // Lock attempt before user, consistent with both password setup and linking. + const active = (await sql.query("SELECT id FROM app.google_sign_in_attempts WHERE id=$1 AND expires_at>clock_timestamp() FOR UPDATE", [attempt.id])).rows.length; + if (!active) return expired(); + const state = await syncGoogleRecovery(sql, linked.user_id, google); + const identity = await workspace(sql, linked.user_id); + if (!identity) return fail(403, "This account cannot access the workspace."); + if (attempt.password_user_id) { + if (!state.recovery || !state.email) return fail(409, "That Google email belongs to another Factorize account. Password recovery is paused; you can still sign in with Google."); + await sql.query(`UPDATE app.google_sign_in_attempts SET google_subject=$2,email=$3,recovery_revision=$4 WHERE id=$1`, + [attempt.id, google.subject, state.email, state.recovery.google_recovery_revision]); + return { pending: true as const }; + } + await sql.query("DELETE FROM app.google_sign_in_attempts WHERE id=$1", [attempt.id]); + return { identity, returnTo: attempt.return_to, connection: attempt.connection_id ?? undefined }; + }); } const existing = (await db.pool.query<{ id: string }>("SELECT id FROM app.auth_users WHERE lower(email)=$1", [google.email])).rows[0]; - const updated = await db.pool.query(`UPDATE app.google_sign_in_attempts SET google_subject=$2,email=$3,existing_user_id=$4,email_confirmed=$5 - WHERE id=$1 AND expires_at>clock_timestamp() RETURNING id`, [attempt.id, google.subject, google.email, existing?.id ?? null, google.authoritativeEmail]); + const updated = await db.pool.query(`UPDATE app.google_sign_in_attempts SET google_subject=$2,email=$3,existing_user_id=$4,email_confirmed=$5,provider_managed_email=$5,provider_observed_at=$6 + WHERE id=$1 AND expires_at>clock_timestamp() RETURNING id`, [attempt.id, google.subject, google.email, existing?.id ?? null, google.authoritativeEmail, google.issuedAt]); return updated.rowCount ? { pending: true as const } : expired(); } 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()${lock ? " FOR UPDATE" : ""}`, [digest])).rows[0]; + WHERE browser_digest=$1 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) { const digest = await digestFor(request, env); const attempt = digest && await pendingAttempt(databaseFor(env).pool, digest); - return attempt && attempt.email ? { email: attempt.email, mode: attempt.existing_user_id ? "link" as const : attempt.email_confirmed ? "signup" as const : "verify-email" as const } : null; + return attempt && attempt.email ? { email: attempt.email, mode: attempt.password_user_id ? "set-password" as const : attempt.existing_user_id ? "link" as const : attempt.email_confirmed ? "signup" as const : "verify-email" as const } : null; } export async function requestGoogleEmail(request: Request, env: Env) { const browser = await digestFor(request, env); if (!browser) return false; const db = databaseFor(env); const token = random(), digest = await tokenDigest(token, env.SESSION_SIGNING_SECRET); - const attempt = (await db.pool.query<{ email: string }>(`UPDATE app.google_sign_in_attempts + 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 + 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_atclock_timestamp()`, [browser, digest]); + AND password_user_id IS NULL AND NOT email_confirmed AND expires_at>clock_timestamp()`, [browser, digest]); return verified.rowCount === 1; } export async function googleUsernameAvailable(request: Request, env: Env, username: string) { @@ -186,7 +263,7 @@ export async function finishGoogleSignIn(request: Request, env: Env, input: { us try { return await db.transaction(async sql => { const attempt = await pendingAttempt(sql, digest, true); - if (!attempt?.google_subject || !attempt.email) return expired(); + if (!attempt?.google_subject || !attempt.email || attempt.password_user_id) return expired(); const link = async (userId: string) => sql.query(`INSERT INTO app.auth_accounts(id,user_id,provider,provider_account_id) VALUES($1,$2,'google',$3)`, [crypto.randomUUID(), userId, attempt.google_subject]); let userId: string; @@ -204,7 +281,7 @@ export async function finishGoogleSignIn(request: Request, env: Env, input: { us } else { if (!("username" in input) || !attempt.email_confirmed) return fail(400, "Choose a username to finish signing up."); userId = crypto.randomUUID(); - await sql.query("INSERT INTO app.auth_users(id,email,email_verified,username) VALUES($1,$2,true,$3)", [userId, attempt.email, input.username]); + await sql.query("INSERT INTO app.auth_users(id,email,email_verified,username,google_recovery_managed,google_recovery_observed_at) VALUES($1,$2,true,$3,$4,$5)", [userId, attempt.email, input.username, attempt.provider_managed_email, attempt.provider_observed_at]); await new AuthRepository(db, env).ensurePersonalTeam(sql, userId, attempt.email); } await link(userId); @@ -220,3 +297,39 @@ export async function finishGoogleSignIn(request: Request, env: Env, input: { us throw error; } } + + +export async function finishGooglePassword(request: Request, env: Env, input: { token: string; password: string }) { + const browser = await digestFor(request, env); + if (!browser) return expired(); + const emailDigest = await tokenDigest(input.token, env.SESSION_SIGNING_SECRET); + return databaseFor(env).transaction(async sql => { + const attempt = await pendingAttempt(sql, browser, true); + const userId = attempt?.password_user_id; + if (!userId || !attempt.google_subject || !attempt.email) return expired(); + const emailProof = (await sql.query("SELECT 1 FROM app.google_sign_in_attempts WHERE id=$1 AND email_token_digest=$2", [attempt.id, emailDigest])).rows.length; + if (!emailProof) return fail(400, "This email link is invalid or expired. Use the latest link in the browser where you confirmed Google."); + const recovery = await lockRecovery(sql, userId); + if (!recovery || recovery.google_recovery_revision !== attempt.recovery_revision) return expired(); + const linked = (await sql.query("SELECT 1 FROM app.auth_accounts WHERE user_id=$1 AND provider='google' AND provider_account_id=$2", [userId, attempt.google_subject])).rows.length; + if (!linked || !await workspace(sql, userId)) return fail(403, "This account cannot access the workspace."); + if (recovery.google_recovery_managed && recovery.google_recovery_suspended) { + if (recovery.google_recovery_candidate !== attempt.email) return expired(); + if (!await updateManagedEmail(sql, userId, attempt.email, true)) return fail(409, "That email belongs to another Factorize account. No password was changed."); + } else if (attempt.email !== recovery.email) return expired(); + + // Independently verified email can reset an existing native password by + // the usual flow. Do not use a stalled enrollment attempt to replace it. + const hasPassword = (await sql.query("SELECT 1 FROM app.auth_accounts WHERE user_id=$1 AND provider='credential' AND password_hash IS NOT NULL", [userId])).rows.length; + if (hasPassword && !recovery.google_recovery_managed) return fail(409, "You already have a password. Use Change password or the regular reset flow."); + await sql.query(`INSERT INTO app.auth_accounts(id,user_id,provider,provider_account_id,password_hash) + VALUES($1,$2::uuid,'credential',$2::uuid::text,$3) + ON CONFLICT(provider,provider_account_id) DO UPDATE SET password_hash=excluded.password_hash`, [crypto.randomUUID(), userId, await hashPassword(input.password)]); + await sql.query("UPDATE app.auth_users SET google_recovery_revision=google_recovery_revision+1 WHERE id=$1", [userId]); + await sql.query("UPDATE app.members SET session_version=session_version+1 WHERE user_id=$1", [userId]); + await sql.query("UPDATE app.auth_reset_tokens SET used_at=clock_timestamp() WHERE user_id=$1 AND used_at IS NULL", [userId]); + await sql.query("UPDATE app.auth_sessions SET revoked_at=clock_timestamp() WHERE user_id=$1 AND revoked_at IS NULL", [userId]); + await sql.query("DELETE FROM app.google_sign_in_attempts WHERE id=$1", [attempt.id]); + return { identity: (await workspace(sql, userId))! }; + }); +} diff --git a/packages/api/src/postgres/auth-repository.ts b/packages/api/src/postgres/auth-repository.ts index 87da0889..c45aee50 100644 --- a/packages/api/src/postgres/auth-repository.ts +++ b/packages/api/src/postgres/auth-repository.ts @@ -8,6 +8,15 @@ type AuthResult = { status: number; body: { ok?: boolean; error?: string; userId const ok = () => ({ status: 200, body: { ok: true } }); const invalidLink = () => ({ status: 400, body: { error: "The link is invalid or expired." } }); +// A Google-only account cannot acquire a password using an ordinary email +// reset. Provider-managed recovery always requires a fresh Google proof, even +// after a password exists, so stale address ownership is never sufficient. +export async function requiresGooglePasswordProof(db: DatabaseClient, userId: string) { + return !!(await db.query(`SELECT 1 FROM app.auth_users u WHERE u.id=$1 AND + (u.google_recovery_managed OR (EXISTS (SELECT 1 FROM app.auth_accounts a WHERE a.user_id=u.id AND a.provider='google') + AND NOT EXISTS (SELECT 1 FROM app.auth_accounts a WHERE a.user_id=u.id AND a.provider='credential' AND a.password_hash IS NOT NULL)))`, [userId])).rows.length; +} + export class AuthRepository { constructor(private database: Database, private env: Env) {} @@ -75,7 +84,9 @@ export class AuthRepository { validateAuthEmailConfig(this.env); const email = normalizeEmail(String(input.email ?? "")); const user = (await this.database.pool.query<{ id: string; email_verified: boolean }>("SELECT id,email_verified FROM app.auth_users WHERE lower(email)=$1", [email])).rows[0]; - if (user && (purpose === "reset" || !user.email_verified)) await this.issueEmail(user.id, email, purpose, input.connection as string | undefined); + if (user && (purpose === "reset" ? !await requiresGooglePasswordProof(this.database.pool, user.id) : !user.email_verified)) { + await this.issueEmail(user.id, email, purpose, input.connection as string | undefined); + } return ok(); } async requestReset(input: Record) { return this.requestEmail(input, "reset"); } @@ -108,6 +119,7 @@ export class AuthRepository { const active = await client.query("SELECT digest,connection_id FROM app.auth_reset_tokens WHERE digest=$1 AND purpose=$2 AND used_at IS NULL AND expires_at>clock_timestamp() FOR UPDATE", [digest, purpose]); if (!active.rows.length) return false; if (purpose === "reset") { + if (await requiresGooglePasswordProof(client, row.user_id)) return false; // Email possession lets legacy Linear-only users establish native credentials. await client.query(`INSERT INTO app.auth_accounts(id,user_id,provider,provider_account_id,password_hash) VALUES ($1,$2::uuid,'credential',$2::uuid::text,$3) ON CONFLICT (provider,provider_account_id) DO UPDATE SET password_hash=excluded.password_hash`, [crypto.randomUUID(), row.user_id, passwordHash]); @@ -126,10 +138,6 @@ export class AuthRepository { } catch (error) { throw error; } } - async hasPassword(userId: string) { - return !!(await this.database.pool.query("SELECT 1 FROM app.auth_accounts WHERE user_id=$1 AND provider='credential' AND password_hash IS NOT NULL", [userId])).rows.length; - } - async changePassword(userId: string, input: Record) { const password = String(input.password ?? ""), currentPassword = String(input.currentPassword ?? ""); if (!validPassword(password) || !validPassword(currentPassword)) return { status: 400, body: { error: "Passwords must have 12–200 characters." } }; diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 85bc3074..67e0bcbf 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -18,7 +18,7 @@ export const teamSettings = app.table("team_settings", { tenantId: uuid("tenant_id").primaryKey().references(() => tenants.id, { onDelete: "cascade" }), updatedAt: updatedAt(), }); -export const authUsers = app.table("auth_users", { id: uuid("id").primaryKey(), username:text("username").notNull().unique("auth_users_username_unique").default(sql`'user-' || replace(gen_random_uuid()::text,'-','')`), email: text("email").notNull().unique(), emailVerified: boolean("email_verified").notNull().default(false), createdAt: createdAt() }, t => [uniqueIndex("auth_users_email_normalized").on(sql`lower(${t.email})`)]); +export const authUsers = app.table("auth_users", { id: uuid("id").primaryKey(), username:text("username").notNull().unique("auth_users_username_unique").default(sql`'user-' || replace(gen_random_uuid()::text,'-','')`), email: text("email").notNull().unique(), emailVerified: boolean("email_verified").notNull().default(false), googleRecoveryManaged: boolean("google_recovery_managed").notNull().default(false), googleRecoveryAddressConfirmed: boolean("google_recovery_address_confirmed").notNull().default(false), googleRecoveryCandidate: text("google_recovery_candidate"), googleRecoverySuspended: boolean("google_recovery_suspended").notNull().default(false), googleRecoveryObservedAt: integer("google_recovery_observed_at").notNull().default(0), googleRecoveryRevision: integer("google_recovery_revision").notNull().default(0), createdAt: createdAt() }, t => [uniqueIndex("auth_users_email_normalized").on(sql`lower(${t.email})`)]); export const authAccounts = app.table("auth_accounts", { id: uuid("id").primaryKey(), userId: uuid("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), provider: text("provider").notNull(), providerAccountId: text("provider_account_id").notNull(), passwordHash: text("password_hash"), }, t => [unique().on(t.provider, t.providerAccountId), uniqueIndex("auth_accounts_google_user_unique").on(t.userId).where(sql`${t.provider}='google'`)]); @@ -33,6 +33,7 @@ export const googleSignInAttempts = app.table("google_sign_in_attempts", { connectionId: uuid("connection_id").references(() => 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), 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)]); diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index 13692741..83120c32 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -6,6 +6,7 @@ export interface Env { ASSETS: Fetcher; APP_ORIGIN: string; MARKETING_ORIGIN?: string; + GOOGLE_SIGN_IN_START_LIMIT?: RateLimit; GOOGLE_SIGN_IN_CLIENT_ID?: string; GOOGLE_SIGN_IN_CLIENT_SECRET?: string; LINEAR_CLIENT_ID: string; diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index b655687a..4b024523 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -1,5 +1,5 @@ import { googleSignInCallback } from "./auth-api"; -import { googleCallbackPath } from "./google-sign-in"; +import { clearExpiredGoogleSignIns, googleCallbackPath } from "./google-sign-in"; import { AlarmCoordinator as BaseAlarmCoordinator } from "./alarm-coordinator"; import { wakeMcpDeliveries } from "./postgres/event-match-repository"; import { staticApp, securityHeaders } from "./static-app"; @@ -163,6 +163,7 @@ export default { await wakeMcpDeliveries(env).catch(() => {}); // Retire expired VM proofs and incomplete enrollments. const db = databaseFor(env); + await clearExpiredGoogleSignIns(db.pool); await db.pool.query(`DELETE FROM app.vm_permission_proofs WHERE (tenant_id,grant_id,proof_id) IN (SELECT tenant_id,grant_id,proof_id FROM app.vm_permission_proofs WHERE expires_at ({ WorkerEntrypoint: class {}, DurableObject: class {} })); @@ -34,6 +34,8 @@ it.skipIf(!url)("links only after confirming the original password and reuses th const returning = await h.google("existing-subject", "updated@gmail.com"); expect(returning.result.headers.get("Location")).toBe(f.env.APP_ORIGIN + "/clients"); expect(await (await h.api("GET", "/session", undefined, h.sessionCookie(returning.result))).json()).toMatchObject({ user: { id: f.userId, email }, team: { id: f.tenantId } }); + expect((await h.api("POST", "/auth/password-reset/request", { email })).status).toBe(200); + expect(h.mail.map(message => message.To)).toEqual([email]); const byPassword = await h.api("POST", "/auth/login", { email, password }); expect(byPassword.status).toBe(200); expect(await (await h.api("GET", "/session", undefined, h.sessionCookie(byPassword))).json()).toMatchObject({ user: { id: f.userId }, team: { id: f.tenantId } }); @@ -43,7 +45,7 @@ it.skipIf(!url)("links only after confirming the original password and reuses th } }); -it.skipIf(!url)("checks username availability but enforces it at signup and adds a first password only through email", async () => { +it.skipIf(!url)("checks username availability but enforces it at signup and adds a first password with fresh Google proof and email", async () => { const f = await loadingFixture(url!); try { const h = await harness(f); @@ -65,15 +67,22 @@ it.skipIf(!url)("checks username availability but enforces it at signup and adds expect(session).toMatchObject({ authenticated: true, user: { email: newEmail }, hasPassword: false }); expect(session.team.id).not.toBe(f.tenantId); expect((await h.api("POST", "/auth/password/set-request", undefined)).status).toBe(401); - expect((await h.api("POST", "/auth/password/set-request", undefined, cookie)).status).toBe(200); + expect((await h.api("POST", "/auth/password-reset/request", { email: newEmail })).status).toBe(200); + expect(h.mail).toHaveLength(0); + const proof = await h.google("signup-subject", newEmail, cookie); + expect(proof.result.headers.get("Location")).toBe(f.env.APP_ORIGIN + "/auth/google"); + expect(await (await h.api("GET", "/auth/google/pending", undefined, proof.browser)).json()).toEqual({ email: newEmail, mode: "set-password" }); + expect((await h.api("POST", "/auth/google/email/request", undefined, proof.browser)).status).toBe(200); expect(h.mail).toHaveLength(1); expect(h.mail[0].To).toBe(newEmail); const link = new URL(h.mail[0].TextBody.match(/https:\/\/\S+/)![0]); - const reset = await h.api("POST", "/auth/password-reset/complete", { token: link.searchParams.get("token"), password }); + const token = link.searchParams.get("token"); + const reset = await h.api("POST", "/auth/google/password/complete", { token, password }, proof.browser); expect(reset.status, await reset.clone().text()).toBe(200); const next = h.sessionCookie(reset); - expect(await (await h.api("GET", "/session", undefined, next)).json()).toMatchObject({ user: { id: session.user.id }, team: { id: session.team.id }, hasPassword: true }); - expect((await h.api("POST", "/auth/password/set-request", undefined, next)).status).toBe(409); + expect(await (await h.api("GET", "/session", undefined, next)).json()).toMatchObject({ user: { id: session.user.id }, team: { id: session.team.id }, hasPassword: true, googleManagedRecovery: true }); + expect((await h.api("POST", "/auth/password-reset/request", { email: newEmail })).status).toBe(200); + expect(h.mail).toHaveLength(1); } finally { vi.unstubAllGlobals(); await f.cleanup(); @@ -99,8 +108,11 @@ it.skipIf(!url)("lets new Google users on a third-party email domain confirm tha expect(await state()).toEqual({ email, mode: "signup" }); const signup = await h.api("POST", "/auth/google/finish", { username: "external-google" }, browser); expect(signup.status, await signup.clone().text()).toBe(200); - expect(await (await h.api("GET", "/session", undefined, h.sessionCookie(signup))).json()).toMatchObject({ - authenticated: true, user: { email }, hasPassword: false, + const existing = await (await h.api("GET", "/session", undefined, h.sessionCookie(signup))).json() as { user: { id: string }; team: { id: string } }; + expect(existing).toMatchObject({ authenticated: true, user: { email }, hasPassword: false, googleManagedRecovery: false }); + const returning = await h.google("external-subject", "different@gmail.com"); + expect(await (await h.api("GET", "/session", undefined, h.sessionCookie(returning.result))).json()).toMatchObject({ + user: { id: existing.user.id, email }, team: { id: existing.team.id }, googleManagedRecovery: false, }); } finally { vi.unstubAllGlobals(); @@ -108,9 +120,115 @@ it.skipIf(!url)("lets new Google users on a third-party email domain confirm tha } }); +it.skipIf(!url)("retires managed recovery authority and old links when the linked Google email changes", async () => { + const f = await loadingFixture(url!); + try { + const h = await harness(f); + const oldEmail = "google-old@gmail.com", newEmail = "google-current@gmail.com"; + const signup = await h.google("managed-subject", oldEmail); + const created = await h.api("POST", "/auth/google/finish", { username: "managed-google" }, signup.browser); + expect(created.status).toBe(200); + const previousSession = h.sessionCookie(created); + const initial = await (await h.api("GET", "/session", undefined, previousSession)).json() as { user: { id: string }; team: { id: string } }; + const oldProof = await h.google("managed-subject", oldEmail, previousSession); + expect((await h.api("POST", "/auth/google/email/request", undefined, oldProof.browser)).status).toBe(200); + const previousGoogleLink = new URL(h.mail[0].TextBody.match(/https:\/\/\S+/)![0]).searchParams.get("token"); + 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("outstanding-previous-link", f.env.SESSION_SIGNING_SECRET), initial.user.id]); + + const changed = await h.google("managed-subject", newEmail); + const nextSession = h.sessionCookie(changed.result); + expect(await (await h.api("GET", "/session", undefined, nextSession)).json()).toMatchObject({ + user: { id: initial.user.id, email: newEmail }, team: { id: initial.team.id }, hasPassword: false, googleManagedRecovery: true, + }); + expect(await (await h.api("GET", "/session", undefined, previousSession)).json()).toEqual({ authenticated: false }); + const row = (await f.db.pool.query("SELECT used_at FROM app.auth_reset_tokens WHERE user_id=$1", [initial.user.id])).rows[0]; + expect(row.used_at).toBeInstanceOf(Date); + const stale = await h.api("POST", "/auth/google/password/complete", { token: previousGoogleLink, password }, oldProof.browser); + expect(stale.status).toBe(400); + expect((await h.api("POST", "/auth/password-reset/request", { email: oldEmail })).status).toBe(200); + expect(h.mail).toHaveLength(1); + const freshProof = await h.google("managed-subject", newEmail, nextSession); + expect((await h.api("POST", "/auth/google/email/request", undefined, freshProof.browser)).status).toBe(200); + expect(h.mail.map(msg => msg.To)).toEqual([oldEmail, newEmail]); + } finally { + vi.unstubAllGlobals(); + await f.cleanup(); + } +}); + +it.skipIf(!url)("verifies a changed non-authoritative address before enabling managed password recovery", async () => { + const f = await loadingFixture(url!); + try { + const h = await harness(f); + const oldEmail = "google-managed@gmail.com", newEmail = "changed@example.test"; + const signup = await h.google("managed-external", oldEmail); + const created = await h.api("POST", "/auth/google/finish", { username: "managed-external" }, signup.browser); + const existing = h.sessionCookie(created); + const fresh = await h.google("managed-external", newEmail, existing); + expect(fresh.result.headers.get("Location")).toBe(f.env.APP_ORIGIN + "/auth/google"); + expect(await (await h.api("GET", "/session", undefined, existing)).json()).toEqual({ authenticated: false }); + expect((await h.api("POST", "/auth/google/email/request", undefined, fresh.browser)).status).toBe(200); + expect(h.mail.map(msg => msg.To)).toEqual([newEmail]); + const token = new URL(h.mail[0].TextBody.match(/https:\/\/\S+/)![0]).searchParams.get("token"); + const completed = await h.api("POST", "/auth/google/password/complete", { token, password }, fresh.browser); + expect(completed.status, await completed.clone().text()).toBe(200); + const newSession = h.sessionCookie(completed); + expect(await (await h.api("GET", "/session", undefined, newSession)).json()).toMatchObject({ + user: { email: newEmail }, hasPassword: true, googleManagedRecovery: true, + }); + await h.google("managed-external", newEmail); + expect((await h.api("GET", "/session", undefined, newSession)).status).toBe(200); + expect(await (await h.api("GET", "/session", undefined, newSession)).json()).toMatchObject({ authenticated: true, user: { email: newEmail } }); + } finally { + vi.unstubAllGlobals(); + await f.cleanup(); + } +}); + +it.skipIf(!url)("keeps the managed account separate when Google later reports an address in use", async () => { + const f = await loadingFixture(url!); + try { + const h = await harness(f); + const email = "google-second@gmail.com"; + const initial = await h.google("subject-two", email); + const created = await h.api("POST", "/auth/google/finish", { username: "google-two" }, initial.browser); + const cookie = h.sessionCookie(created); + const account = await (await h.api("GET", "/session", undefined, cookie)).json() as { user: { id: string }; team: { id: string } }; + const claimed = "owner-google@gmail.com"; + await f.db.pool.query("UPDATE app.auth_users SET email=$1 WHERE id=$2", [claimed, f.userId]); + const fresh = await h.google("subject-two", claimed); + const session = h.sessionCookie(fresh.result); + expect(await (await h.api("GET", "/session", undefined, session)).json()).toMatchObject({ user: { id: account.user.id, email }, team: { id: account.team.id } }); + const blocked = await h.google("subject-two", claimed, session); + expect(blocked.result.headers.get("Location")).toBe(f.env.APP_ORIGIN + "/auth/login?google=collision"); + expect(h.mail).toHaveLength(0); + expect((await f.db.pool.query("SELECT google_recovery_suspended FROM app.auth_users WHERE id=$1", [account.user.id])).rows[0].google_recovery_suspended).toBe(true); + } finally { + vi.unstubAllGlobals(); + await f.cleanup(); + } +}); + +it.skipIf(!url)("checks the start limit before allocating a Google sign-in attempt", async () => { + const f = await loadingFixture(url!); + try { + const h = await harness(f); + vi.mocked(f.env.GOOGLE_SIGN_IN_START_LIMIT!.limit).mockResolvedValue({ success: false }); + const response = await h.api("POST", "/auth/google/start", { returnTo: "/clients" }); + expect(response.status).toBe(429); + expect(response.headers.get("Retry-After")).toBe("60"); + expect((await f.db.pool.query("SELECT * FROM app.google_sign_in_attempts")).rows).toHaveLength(0); + } 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", + GOOGLE_SIGN_IN_START_LIMIT: { limit: vi.fn(async () => ({ success: true })) }, POSTMARK_SERVER_TOKEN: "fixture", POSTMARK_FROM_EMAIL: "test@example.test", POSTMARK_MESSAGE_STREAM: "outbound", }); const pair = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]); @@ -118,6 +236,7 @@ async function harness(f: Awaited>) { const mail: { To:string; TextBody:string }[] = []; let token: string; let challenge: string; + let issuedAt = Math.floor(Date.now() / 1000) - 20; vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => { if (url === "https://oauth2.googleapis.com/token") { const body = options!.body as URLSearchParams; @@ -136,8 +255,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) => { - const start = await api("POST", "/auth/google/start", { returnTo: "/clients" }); + 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" }); 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); @@ -146,7 +265,7 @@ async function harness(f: Awaited>) { challenge = authorization.searchParams.get("code_challenge")!; const now = Math.floor(Date.now()/1000); const encoded = signedPart({ alg: "RS256", kid: "test" }) + "." + signedPart({ - iss: "https://accounts.google.com", sub: subject, aud: env.GOOGLE_SIGN_IN_CLIENT_ID, exp: now+3600, iat: now, + iss: "https://accounts.google.com", sub: subject, aud: env.GOOGLE_SIGN_IN_CLIENT_ID, exp: now+3600, iat: ++issuedAt, email, email_verified: true, nonce: authorization.searchParams.get("nonce"), }); token = encoded + "." + Buffer.from(await crypto.subtle.sign("RSASSA-PKCS1-v1_5", pair.privateKey, new TextEncoder().encode(encoded))).toString("base64url"); diff --git a/packages/api/wrangler.jsonc b/packages/api/wrangler.jsonc index ec969ecc..3cf4a48f 100644 --- a/packages/api/wrangler.jsonc +++ b/packages/api/wrangler.jsonc @@ -14,6 +14,7 @@ "artifacts": [{ "binding": "SKILL_ARTIFACTS", "namespace": "factorize-skills", "remote": false }], "workflows": [{ "binding": "SKILL_PUSH", "name": "factorize-skill-push", "class_name": "SkillPushWorkflow" }], "triggers": { "crons": ["*/5 * * * *"], "events": [{ "type": "cf.artifacts.repo.pushed", "filter": { "namespace": "factorize-skills" }, "targets": [{ "type": "workflow", "workflow_name": "factorize-skill-push" }] }] }, + "ratelimits": [{ "name": "GOOGLE_SIGN_IN_START_LIMIT", "namespace_id": "10430", "simple": { "limit": 15, "period": 60 } }], "r2_buckets": [{ "binding": "PROXY_ARTIFACTS", "bucket_name": "factorize-run-artifacts" }], "durable_objects": { "bindings": [{ "name": "SCHEDULER", "class_name": "AlarmCoordinator" }] diff --git a/packages/app/src/features/auth/auth-screen.tsx b/packages/app/src/features/auth/auth-screen.tsx index c97af449..10de4fc9 100644 --- a/packages/app/src/features/auth/auth-screen.tsx +++ b/packages/app/src/features/auth/auth-screen.tsx @@ -21,10 +21,12 @@ export function AuthScreen({ mode, inAccountSettings = false }: { mode: AuthMode const [notice, setNotice] = useState(""); const account = useQuery({ ...sessionQuery, enabled: mode === "password" }); const setPasswordMode = mode === "password" && account.data?.authenticated && account.data.hasPassword === false; + const managedRecovery = mode === "password" && account.data?.authenticated && account.data.googleManagedRecovery === true; const setup = useMutation({ retry: false, mutationFn: async () => { const { data, error } = await api.POST("/api/v1/auth/password/set-request"); if (!data || error) throw new Error(messageOf(error)); - } }); + return data.authorizationUrl; + }, onSuccess: url => window.location.assign(url) }); const resetCompletion = mode === "reset" && Boolean(search.token); const continuation = useQuery({ queryKey: ["connection", search.connection], enabled: !!search.connection && !search.token && mode !== "verify", @@ -67,9 +69,8 @@ export function AuthScreen({ mode, inAccountSettings = false }: { mode: AuthMode }); function submit(event: FormEvent) { event.preventDefault(); setNotice(""); mutation.mutate(); } if (setPasswordMode) return -

We’ll email you a link to set your Factorize password for {account.data!.authenticated && account.data!.user.email}.

- - {setup.isSuccess &&

Check your email for a link to set your password.

} +

Confirm your linked Google account first. Then we’ll email you a link to set a Factorize password.

+ {setup.error &&

{setup.error.message}

}
; const showEmail = mode !== "password" && mode !== "verify" && !resetCompletion; @@ -80,7 +81,8 @@ export function AuthScreen({ mode, inAccountSettings = false }: { mode: AuthMode {search.connection &&

Connecting {continuation.data?.clientName ?? "your MCP client"}. After verification, review its permissions and choose Allow or Deny.

} {(continuation.error || search.expired) &&

{continuation.error?.message ?? "Your MCP request has expired. Start a new connection from your client."}

} {mode === "login" && search.google &&

{ - search.google === "account" ? "This Google account couldn’t be used. Create and verify your Factorize account first, or sign in another way." + search.google === "collision" ? "That Google email is already used by another Factorize account. Password recovery is paused. You can still sign in with your linked Google account." + : search.google === "account" ? "This Google account couldn’t be used. Create and verify your Factorize account first, or sign in another way." : search.google === "connection" ? "This MCP connection expired or belongs to another account. Restart from your client." : "Google sign-in didn’t finish. Start again from Factorize." }

} @@ -95,6 +97,11 @@ export function AuthScreen({ mode, inAccountSettings = false }: { mode: AuthMode {mutation.isError &&

{mutation.error.message}

} {notice &&

{notice}

} + {managedRecovery &&
+ + {setup.error &&

{setup.error.message}

} +
} + {mode === "reset" && !resetCompletion &&

If your recovery address is managed by Google, sign in with Google and use password recovery in Account settings.

} {mode !== "password" &&