diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index cecb36ec..74e6152d 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -276,6 +276,186 @@ 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/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; + 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; + /** + * 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"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/auth/login": { parameters: { query?: never; @@ -3051,6 +3231,365 @@ 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; + }; + }; + }; + 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" | "set-password"; + }; + }; + }; + 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_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; + 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": { + /** Format: uri */ + authorizationUrl: string; }; }; }; 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..339d60a4 --- /dev/null +++ b/packages/api/migrations/0104_google_sign_in.sql @@ -0,0 +1,31 @@ +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'; + +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 b3e84ef5..3c8452ae 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,15 @@ 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/password/complete", "google-password-complete", "Set the Factorize password with fresh Google proof and email confirmation", loginSuccess, authInputs.reset), + authRoute("POST", "/api/v1/auth/google/finish", "google-finish", "Choose a username or confirm your existing Factorize password", loginSuccess, authInputs.googleFinish), + {...authRoute("POST", "/api/v1/auth/password/set-request", "password-set-request", "Start fresh Google verification before setting or recovering a password", googleStartResult),ownerSession:true}, authRoute("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..2d9d5d17 100644 --- a/packages/api/src/auth-api.ts +++ b/packages/api/src/auth-api.ts @@ -1,3 +1,4 @@ +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"; @@ -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,8 @@ 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(), ]); export const authSuccess = z.object({ ok: z.literal(true) }).strict(); @@ -40,6 +46,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", "set-password"]) }); +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. */ @@ -63,18 +73,90 @@ 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 = "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 // 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 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); + 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-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); + 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."); + 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 { const started = await startConnection(request, env, String(input.returnTo)); @@ -113,11 +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 }>("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; 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], 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") { @@ -161,15 +245,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 +271,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 === 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"); + 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..c6e5efcd 100644 --- a/packages/api/src/auth-email.ts +++ b/packages/api/src/auth-email.ts @@ -8,17 +8,19 @@ 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" | "google-password", connection?: string): Promise { validateAuthEmailConfig(env); - const url = new URL(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", { 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: 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 new file mode 100644 index 00000000..9e9b5cde --- /dev/null +++ b/packages/api/src/google-sign-in.ts @@ -0,0 +1,335 @@ +import { serialize } from "hono/utils/cookie"; +import { z } from "zod"; +import { hashPassword, normalizeEmail, tokenDigest, verifyPassword } from "./auth"; +import { sendAuthEmail } from "./auth-email"; +import { requestCookie } from "./session"; +import { 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 = (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"; +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(env), 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; + 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(env)); + return browser && /^[A-Za-z0-9_-]{43}$/.test(browser) ? tokenDigest(browser, env.SESSION_SIGNING_SECRET) : null; +} + +export async function startGoogleSignIn(env: Env, returnTo: string, connectionId?: string, passwordUserId?: string) { + const db = databaseFor(env); + const id = crypto.randomUUID(), browser = random(), verifier = random(), nonce = random(); + await db.pool.query(`INSERT INTO app.google_sign_in_attempts + (id,browser_digest,verifier,nonce,return_to,connection_id,password_user_id,expires_at) + VALUES($1,$2,$3,$4,$5,$6,$7,now()+interval '10 minutes')`, + [id, await tokenDigest(browser, env.SESSION_SIGNING_SECRET), verifier, nonce, returnTo, connectionId ?? null, passwordUserId ?? null]); + 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) }; +} + +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 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, issuedAt: claims.iat }; +} + +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; +} + +type Recovery = { email: string; google_recovery_managed: boolean; google_recovery_suspended: boolean; google_recovery_candidate: string | null; google_recovery_address_confirmed: boolean; google_recovery_observed_at: number; google_recovery_revision: number }; +const lockRecovery = async (sql: DatabaseClient, userId: string) => (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")); + 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 (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) { + 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,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() + 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.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; 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]); + 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 || 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; + 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,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); + 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; + } +} + + +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 92d9c16c..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,12 +84,14 @@ 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"); } - 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. @@ -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]); diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 2acfef56..67e0bcbf 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -18,15 +18,24 @@ 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)]); +}, 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 }), + 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)]); 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 +192,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..83120c32 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -6,6 +6,9 @@ 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; LINEAR_CLIENT_SECRET: string; LINEAR_OAUTH_SCOPES?: string; diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index 6a249802..4b024523 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -1,3 +1,5 @@ +import { googleSignInCallback } from "./auth-api"; +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"; @@ -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; @@ -160,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 { 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..1cc7e468 --- /dev/null +++ b/packages/api/test/google-sign-in.postgres.test.ts @@ -0,0 +1,279 @@ +import { expect, it, vi } from "vitest"; +import { protectedApiFetch } from "../src/protected-api"; +import { googleSignInCallback } from "../src/auth-api"; +import { hashPassword, tokenDigest } 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 } }); + 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 } }); + } finally { + vi.unstubAllGlobals(); + await f.cleanup(); + } +}); + +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); + 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-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 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, 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(); + } +}); + +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); + 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(); + await f.cleanup(); + } +}); + +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"]); + const publicKey = await crypto.subtle.exportKey("jwk", pair.publicKey); + 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; + 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, 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); + 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: ++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"); + 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/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 d8a65c93..10de4fc9 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,20 @@ 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 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", @@ -59,6 +68,11 @@ export function AuthScreen({ mode, inAccountSettings = false }: { mode: AuthMode }, }); function submit(event: FormEvent) { event.preventDefault(); setNotice(""); mutation.mutate(); } + if (setPasswordMode) return +

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; const showPassword = mode === "login" || mode === "signup" || mode === "password" || resetCompletion; const content = <> @@ -66,6 +80,13 @@ 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 === "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." + }

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

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

}
{mode === "signup" && } @@ -76,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" &&