diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index dce8d6c2..f8c4e712 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1,5 +1,45 @@ // Generated from packages/docs/openapi.yaml. Do not edit. export interface paths { + "/api/v1/auth/connections": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Persist an individual validated MCP connection; sets a per-attempt browser cookie + * @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_connections"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/connections/resume": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Resume verified onboarding in the initiating browser; never grants OAuth access + * @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_connections_resume"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/session": { parameters: { query?: never; @@ -90,7 +130,7 @@ export interface paths { get?: never; put?: never; /** - * Complete email verification + * Verify email, establish an owner session, and resume explicit consent; callbacks stay 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_email_verification_complete"]; @@ -130,7 +170,7 @@ export interface paths { get?: never; put?: never; /** - * Complete password reset + * Complete password reset and resume onboarding * @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_reset_complete"]; @@ -1883,6 +1923,100 @@ export interface components { } export type $defs = Record; export interface operations { + post_api_v1_auth_connections: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + returnTo: 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: uuid */ + connection: string; + clientName: string; + /** Format: date-time */ + expiresAt: 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_connections_resume: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** 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": { + /** @constant */ + ok: true; + returnTo?: string; + crossBrowser?: boolean; + pending?: boolean; + clientName?: string; + /** Format: date-time */ + expiresAt?: 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_session: { parameters: { query?: never; @@ -1949,6 +2083,8 @@ export interface operations { email: string; password: string; returnTo?: string; + /** Format: uuid */ + connection?: string; }; }; }; @@ -1994,6 +2130,8 @@ export interface operations { /** Format: email */ email: string; password: string; + /** Format: uuid */ + connection?: string; }; }; }; @@ -2037,6 +2175,8 @@ export interface operations { "application/json": { /** Format: email */ email: string; + /** Format: uuid */ + connection?: string; }; }; }; @@ -2096,6 +2236,12 @@ export interface operations { "application/json": { /** @constant */ ok: true; + returnTo?: string; + crossBrowser?: boolean; + pending?: boolean; + clientName?: string; + /** Format: date-time */ + expiresAt?: string; }; }; }; @@ -2122,6 +2268,8 @@ export interface operations { "application/json": { /** Format: email */ email: string; + /** Format: uuid */ + connection?: string; }; }; }; @@ -2182,6 +2330,12 @@ export interface operations { "application/json": { /** @constant */ ok: true; + returnTo?: string; + crossBrowser?: boolean; + pending?: boolean; + clientName?: string; + /** Format: date-time */ + expiresAt?: string; }; }; }; @@ -2300,6 +2454,7 @@ export interface operations { clientName: string; scopes: string[]; expiresAt: string; + signature: string; }; }; }; @@ -2325,6 +2480,7 @@ export interface operations { content: { "application/json": { userCode: string; + signature: string; /** @enum {string} */ decision: "allow" | "deny"; }; diff --git a/packages/api/migrations/0014_oauth_onboarding.sql b/packages/api/migrations/0014_oauth_onboarding.sql new file mode 100644 index 00000000..341f54a9 --- /dev/null +++ b/packages/api/migrations/0014_oauth_onboarding.sql @@ -0,0 +1,23 @@ +-- Individual browser-bound requests survive email delivery without sharing a return cookie. +CREATE TABLE app.oauth_connections ( + id uuid PRIMARY KEY, + browser_digest text NOT NULL, + destination text NOT NULL, + device_user_code text, + client_name text NOT NULL, + kind text NOT NULL CHECK (kind IN ('callback','device')), + expires_at timestamptz NOT NULL, + user_id uuid REFERENCES app.auth_users(id) ON DELETE CASCADE, + ready_version integer, + ready boolean NOT NULL DEFAULT false, + used_at timestamptz +); +ALTER TABLE app.auth_reset_tokens ADD COLUMN connection_id uuid REFERENCES app.oauth_connections(id) ON DELETE SET NULL; +CREATE TABLE app.oauth_consent_previews ( + id uuid PRIMARY KEY, + expires_at timestamptz NOT NULL, + used_at timestamptz +); + +CREATE INDEX oauth_connections_expires ON app.oauth_connections(expires_at); +CREATE INDEX oauth_consent_previews_expires ON app.oauth_consent_previews(expires_at); diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 1faeb517..6408c3e9 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -15,7 +15,7 @@ import { } from "./flow-schemas"; import { traceReplaySchema } from "./trace-replay-schemas"; import document from "./api-document.json"; -import { authInputs, authSuccess, loginSuccess, sessionResponse, type AuthAction } from "./auth-api"; +import { authInputs, authSuccess, continuationSuccess, connectionStartInput, connectionStartSuccess, connectionResumeInput, loginSuccess, sessionResponse, type AuthAction } from "./auth-api"; type JsonSchema = Record; export interface RouteContract { @@ -165,18 +165,20 @@ function authRoute(method: string, path: string, action: AuthAction, summary: st } export const API_ROUTES: RouteContract[] = [ + authRoute("POST", "/api/v1/auth/connections", "connection-start", "Persist an individual validated MCP connection; sets a per-attempt browser cookie", connectionStartSuccess, connectionStartInput), + authRoute("POST", "/api/v1/auth/connections/resume", "connection-resume", "Resume verified onboarding in the initiating browser; never grants OAuth access", continuationSuccess, connectionResumeInput), authRoute("GET", "/api/v1/session", "session", "Get current browser session", sessionResponse), 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), - authRoute("POST", "/api/v1/auth/email-verification/complete", "verification", "Complete email verification", authSuccess, authInputs.verify), + authRoute("POST", "/api/v1/auth/email-verification/complete", "verification", "Verify email, establish an owner session, and resume explicit consent; callbacks stay in the initiating browser", continuationSuccess, authInputs.verify), authRoute("POST", "/api/v1/auth/password-reset/request", "reset-request", "Request password reset", authSuccess, authInputs.request), - authRoute("POST", "/api/v1/auth/password-reset/complete", "reset", "Complete password reset", authSuccess, authInputs.reset), + authRoute("POST", "/api/v1/auth/password-reset/complete", "reset", "Complete password reset and resume onboarding", continuationSuccess, authInputs.reset), authRoute("POST", "/api/v1/auth/password", "password", "Change password and invalidate sessions", authSuccess, authInputs.change), authRoute("POST", "/api/v1/auth/logout", "logout", "Revoke current session and clear browser cookie", authSuccess), - route("POST", "/api/v1/oauth/device/preview", "flows:read", { summary: "Inspect a device authorization code", responses: { "200": { description: "Pending device request", content: { "application/json": { schema: jsonSchema(z.object({ userCode: z.string(), clientName: z.string(), scopes: z.array(z.string()), expiresAt: z.string() }), "output") } } } } }, async () => undefined, { body: z.object({ userCode: z.string().min(1).max(32) }).strict(), authOperation: "device-preview", ownerSession: true }), - route("POST", "/api/v1/oauth/device/decision", "flows:write", { summary: "Approve or deny a device authorization code", responses: { "200": { description: "Device decision", content: { "application/json": { schema: jsonSchema(z.object({ status: z.enum(["approved", "denied"]) }), "output") } } } } }, async () => undefined, { body: z.object({ userCode: z.string().min(1).max(32), decision: z.enum(["allow", "deny"]) }).strict(), authOperation: "device-decision", ownerSession: true }), + route("POST", "/api/v1/oauth/device/preview", "flows:read", { summary: "Inspect a device authorization code", responses: { "200": { description: "Pending device request", content: { "application/json": { schema: jsonSchema(z.object({ userCode: z.string(), clientName: z.string(), scopes: z.array(z.string()), expiresAt: z.string(), signature: z.string() }), "output") } } } } }, async () => undefined, { body: z.object({ userCode: z.string().min(1).max(32) }).strict(), authOperation: "device-preview", ownerSession: true }), + route("POST", "/api/v1/oauth/device/decision", "flows:write", { summary: "Approve or deny a device authorization code", responses: { "200": { description: "Device decision", content: { "application/json": { schema: jsonSchema(z.object({ status: z.enum(["approved", "denied"]) }), "output") } } } } }, async () => undefined, { body: z.object({ userCode: z.string().min(1).max(32), signature: z.string().min(1).max(256), decision: z.enum(["allow", "deny"]) }).strict(), authOperation: "device-decision", ownerSession: true }), route("POST", "/api/v1/oauth/consent/preview", "flows:read", { summary: "Inspect an OAuth consent request", responses: { "200": { description: "Owner-bound expiring consent", content: { "application/json": { schema: jsonSchema(consentPreviewResponse, "output") } } } } }, async () => undefined, { body: consentPreviewInput, authOperation: "consent-preview", ownerSession: true }), route("POST", "/api/v1/oauth/consent/decision", "flows:write", { summary: "Decide an OAuth consent request", responses: { "200": { description: "Validated protocol destination", content: { "application/json": { schema: jsonSchema(consentDecisionResponse, "output") } } } } }, async () => undefined, { body: consentDecisionInput, authOperation: "consent-decision", ownerSession: true }), route("GET", "/api/v1/trigger-contexts", "flows:read", { diff --git a/packages/api/src/auth-api.ts b/packages/api/src/auth-api.ts index 83759463..cdbcd3bb 100644 --- a/packages/api/src/auth-api.ts +++ b/packages/api/src/auth-api.ts @@ -1,4 +1,5 @@ -import { inspectDevice, decideDevice } from "./device-oauth"; +import { connectionFor, originalBrowser, startConnection, connectionDestination } from "./oauth-continuation"; +import { inspectDevice, decideDevice, deviceConsentSignature, safeEqual } from "./device-oauth"; import { consentPreview, consentDecision, consentPreviewInput, consentDecisionInput } from "./consent-api"; import { serialize } from "hono/utils/cookie"; import { z } from "zod"; @@ -11,11 +12,12 @@ import type { Env } from "./types"; export const SESSION_SCOPES = ["flows:read", "flows:write", "runs:read", "runs:write"] as const; const email = z.string().trim().toLowerCase().email().max(320); const password = z.string().min(12).max(200).meta({ writeOnly: true }); +const connection = z.uuid().optional(); const token = z.string().min(1).max(512).meta({ writeOnly: true }); export const authInputs = { - login: z.object({ email, password, returnTo: z.string().max(4096).optional() }).strict(), - signup: z.object({ email, password }).strict(), - request: z.object({ email }).strict(), + login: z.object({ email, password, returnTo: z.string().max(8192).optional(), connection }).strict(), + signup: z.object({ email, password, connection }).strict(), + request: z.object({ email, connection }).strict(), verify: z.object({ token }).strict(), reset: z.object({ token, password }).strict(), change: z.object({ currentPassword: password, password }).strict(), @@ -31,6 +33,10 @@ export const sessionResponse = z.discriminatedUnion("authenticated", [ }).strict(), ]); export const authSuccess = z.object({ ok: z.literal(true) }).strict(); +export const continuationSuccess = authSuccess.extend({ returnTo: z.string().optional(), crossBrowser: z.boolean().optional(), pending: z.boolean().optional(), clientName: z.string().optional(), expiresAt: z.iso.datetime().optional() }); +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 loginSuccess = authSuccess.extend({ returnTo: z.string() }); /** Only local application/protocol destinations; never trust a return cookie or form field. */ @@ -60,12 +66,39 @@ async function currentSession(request: Request, env: Env): Promise = {}): Promise { // These operations use browser cookies only. Ignore neither a bad bearer nor a // good bearer and silently fall back to a potentially unrelated browser identity. if (request.headers.has("Authorization")) return failure(403, "An interactive browser session is required."); + if (action === "connection-start") { + try { + const started = await startConnection(request, env, String(input.returnTo)); + if (!started) return failure(400, "Invalid or expired MCP request. Restart connecting from your client."); + const { cookie, ...body } = started; + const response = authJson(body); response.headers.append("Set-Cookie", cookie); return response; + } catch { return failure(400, "Invalid MCP request. Restart connecting from your client."); } + } + if (action === "connection-resume") { + const pending = await connectionFor(env, String(input.connection)); + if (!pending || !await originalBrowser(request, env, pending)) return failure(400, "Invalid or expired connection. Restart connecting from your MCP client."); + if (!pending.ready || !pending.user_id) { + // A refresh after the one-time session handoff must still reach consent. + const session = pending.user_id ? await currentSession(request, env) : null; + if (session?.userId === pending.user_id) return authJson({ ok: true, returnTo: connectionDestination(pending) }); + return authJson({ ok: true, pending: true, clientName: pending.client_name, expiresAt: pending.expires_at.toISOString() }); + } + const member = (await databaseFor(env).pool.query<{ tenant_id: string; session_version: number; email: string }>("SELECT m.tenant_id,m.session_version,u.email FROM app.members m JOIN app.auth_users u ON u.id=m.user_id WHERE m.user_id=$1 AND m.role='owner' AND u.email_verified ORDER BY m.created_at,m.tenant_id LIMIT 1", [pending.user_id])).rows[0]; + if (!member || member.session_version !== pending.ready_version) return failure(403, "This verification session was revoked. Sign in again to continue."); + const resumed = await databaseFor(env).pool.query("UPDATE app.oauth_connections SET ready=false WHERE id=$1 AND ready=true AND expires_at>now() AND used_at IS NULL RETURNING id", [pending.id]); + if (!resumed.rows.length) return authJson({ ok: true, pending: true, clientName: pending.client_name, expiresAt: pending.expires_at.toISOString() }); + return signedIn(env, { userId: pending.user_id, email: member.email, tenantId: member.tenant_id, sessionVersion: member.session_version }, { ok: true, returnTo: connectionDestination(pending) }); + } + if (input.connection && ["login", "signup", "verification-request", "reset-request"].includes(action)) { + const pending = await connectionFor(env, String(input.connection)); + if (!pending || !await originalBrowser(request, env, pending)) return failure(400, "Invalid or expired connection. Restart connecting from your MCP client."); + } if (action === "session" || action === "logout" || action === "password" || action === "consent-preview" || action === "consent-decision" || action === "device-preview" || action === "device-decision") { const session = await currentSession(request, env); if (action === "session") { @@ -80,15 +113,20 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env if (action === "device-preview" || action === "device-decision") { if (!session) return failure(401, "Sign in before authorizing a device."); if (!env.OAUTH_PROVIDER) return failure(400, "Device authorization is unavailable."); - const result = action === "device-preview" ? await inspectDevice(env, String(input.userCode)) : await decideDevice(env, env.OAUTH_PROVIDER, session, String(input.userCode), input.decision as "allow" | "deny"); - return result ? authJson(result) : failure(400, "Invalid or expired device code."); + const preview = await inspectDevice(env, String(input.userCode)); + if (!preview) return failure(400, "This device request is invalid, expired, or already completed. Start a new connection in your client."); + const signature = await deviceConsentSignature(env, session, preview); + if (action === "device-preview") return authJson({ ...preview, signature }); + if (!safeEqual(String(input.signature), signature)) return failure(403, "Invalid device consent. Review the device request before approving it."); + const result = await decideDevice(env, env.OAUTH_PROVIDER, session, preview.userCode, input.decision as "allow" | "deny"); + return result ? authJson(result) : failure(400, "This device request has expired or already completed. Start a new connection in your client."); } if (action === "consent-preview" || action === "consent-decision") { if (!session) return failure(401, "Sign in before authorizing a client."); try { - const data = action === "consent-preview" ? await consentPreview(env, session, consentPreviewInput.parse(input)) : await consentDecision(env, session, consentDecisionInput.parse(input)); - return data ? authJson(data) : failure(400, "Invalid or expired authorization request."); - } catch { return failure(400, "Invalid authorization request."); } + const data = action === "consent-preview" ? await consentPreview(env, session, consentPreviewInput.parse(input), request) : await consentDecision(env, session, consentDecisionInput.parse(input)); + return data ? authJson(data) : failure(400, "This authorization request is invalid, expired, or already completed. Start a new connection from your MCP client."); + } catch { return failure(400, "This authorization request could not be validated. Return to the browser where you started connecting, or start a new connection from your MCP client."); } } if (action === "logout") { if (session) await new IdentityRepository(databaseFor(env), session.tenantId).revoke(session.userId); @@ -107,22 +145,46 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env if (action === "login") { const result = await repo.login(input); if (result.status !== 200 || !result.body.userId || !result.body.tenantId || !result.body.email || result.body.sessionVersion === undefined) return failure(result.status, "error" in result.body ? (result.body.error ?? "Sign in failed.") : "Sign in failed."); - const identity = result.body; + 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."); - const lifetime = 7 * 24 * 60 * 60; - const response = authJson({ ok: true, returnTo: safeReturnTo(requestCookie(request, "factorize_oauth_return") ?? input.returnTo as string | undefined) }); - response.headers.append("Set-Cookie", sessionCookie(env, await signSession({ ...identity, exp: Math.floor(Date.now() / 1000) + lifetime }, env.SESSION_SIGNING_SECRET), lifetime)); - response.headers.append("Set-Cookie", serialize("factorize_oauth_return", "", { httpOnly: true, secure: new URL(env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/", maxAge: 0 })); - return response; + 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 }); } const result = action === "signup" ? await repo.signup(input) : action === "verification-request" ? await repo.requestEmail(input, "verify") : action === "verification" ? await repo.completeVerification(String(input.token)) : action === "reset-request" ? await repo.requestReset(input) : await repo.completeReset(input); + if ((action === "verification" || action === "reset") && result.status === 200 && "userId" in result.body && result.body.userId && result.body.email && result.body.tenantId && result.body.sessionVersion !== undefined) { + 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."); + const pending = identity.connection ? await connectionFor(env, identity.connection) : null; + const sameBrowser = pending ? await originalBrowser(request, env, pending) : false; + if (pending && sameBrowser) await databaseFor(env).pool.query("UPDATE app.oauth_connections SET ready=false WHERE id=$1", [pending.id]); + const continuation = pending + ? pending.kind === "device" || sameBrowser ? { returnTo: connectionDestination(pending) } : { crossBrowser: true } + : { returnTo: identity.connection ? "/auth/login?expired=1" : "/settings/integrations" }; + return signedIn(env, identity, { ok: true, ...continuation }); + } + if ((action === "verification" || action === "reset") && result.status === 200 && "userId" in result.body && result.body.userId && !result.body.tenantId) return failure(403, "This account needs a workspace owner invitation."); // The new public signup contract intentionally does not enumerate accounts. // Keep legacy form status compatibility until those screens are cut over. if (action === "signup" && (result.status === 201 || result.status === 409)) return authJson({ ok: true }, 202); - return result.status < 300 ? authJson({ ok: true }) : failure(result.status, "error" in result.body ? result.body.error : "Request failed."); + return result.status < 300 ? authJson({ ok: true }) : failure(result.status, "error" in result.body ? result.body.error ?? "Request failed." : "Request 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); + response.headers.append("Set-Cookie", sessionCookie(env, await signSession({ tenantId: identity.tenantId, userId: identity.userId, email: identity.email, sessionVersion: identity.sessionVersion, exp: Math.floor(Date.now() / 1000) + lifetime }, env.SESSION_SIGNING_SECRET), lifetime)); + return response; } diff --git a/packages/api/src/auth-email.ts b/packages/api/src/auth-email.ts index d4208cc0..62c4d591 100644 --- a/packages/api/src/auth-email.ts +++ b/packages/api/src/auth-email.ts @@ -8,10 +8,11 @@ export function validateAuthEmailConfig(env: Env): void { } } -export async function sendAuthEmail(env: Env, email: string, token: string, purpose: "verify" | "reset"): Promise { +export async function sendAuthEmail(env: Env, email: string, token: string, purpose: "verify" | "reset", connection?: string): Promise { validateAuthEmailConfig(env); const url = new URL(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! }, diff --git a/packages/api/src/consent-api.ts b/packages/api/src/consent-api.ts index 07a09444..75662477 100644 --- a/packages/api/src/consent-api.ts +++ b/packages/api/src/consent-api.ts @@ -1,3 +1,5 @@ +import { databaseFor } from "./postgres/database"; +import { connectionFor, originalBrowser } from "./oauth-continuation"; import { z } from "zod"; import type { AuthRequest } from "@cloudflare/workers-oauth-provider"; import { hmac } from "./crypto"; @@ -12,18 +14,30 @@ const encode = (value: unknown) => btoa(String.fromCharCode(...new TextEncoder() const decode = (value: string) => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0)))); const binding = (payload: string, session: Session) => `${payload}.${session.tenantId}.${session.userId}.${session.sessionVersion}`; const equal = (a: string, b: string) => { let diff = a.length ^ b.length; for (let i = 0; i < Math.max(a.length, b.length); i++) diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0); return diff === 0; }; -export async function consentPreview(env: Env, session: Session, input: z.infer) { +export async function consentPreview(env: Env, session: Session, input: z.infer, browserRequest?: Request) { if (!env.OAUTH_PROVIDER) throw new Error("OAuth provider unavailable"); - const parsed = await env.OAUTH_PROVIDER.parseAuthRequest(new Request(`${env.APP_ORIGIN}/authorize?${input.authorizationQuery.replace(/^\?/, "")}`)); + const url = new URL(`${env.APP_ORIGIN}/authorize?${input.authorizationQuery.replace(/^\?/, "")}`); + const connectionId = url.searchParams.get("connection"); + const connection = connectionId ? await connectionFor(env, connectionId) : null; + if (connectionId) { + if (!connection || connection.kind !== "callback" || !browserRequest || !await originalBrowser(browserRequest, env, connection) || connection.user_id && connection.user_id !== session.userId) return null; + url.searchParams.delete("connection"); + if (url.pathname + url.search !== connection.destination) return null; + await databaseFor(env).pool.query("UPDATE app.oauth_connections SET user_id=$2 WHERE id=$1 AND (user_id IS NULL OR user_id=$2)", [connection.id, session.userId]); + } + const parsed = await env.OAUTH_PROVIDER.parseAuthRequest(new Request(url)); const client = await env.OAUTH_PROVIDER.lookupClient(parsed.clientId); if (!client) return null; - const expiresAt = Math.min(session.exp, Math.floor(Date.now() / 1000) + 600); - const request = encode({ parsed, expiresAt }); + const expiresAt = Math.min(session.exp, Math.floor(Date.now() / 1000) + 600, connection ? Math.floor(connection.expires_at.getTime() / 1000) : Infinity); + await databaseFor(env).pool.query("DELETE FROM app.oauth_consent_previews WHERE expires_at supported.includes(scope)), request, signature: await hmac(binding(request, session), env.SESSION_SIGNING_SECRET), expiresAt: new Date(expiresAt * 1000).toISOString() }; } export async function consentDecision(env: Env, session: Session, input: z.infer) { if (!env.OAUTH_PROVIDER || !equal(input.signature, await hmac(binding(input.request, session), env.SESSION_SIGNING_SECRET))) return null; - let envelope: { parsed: AuthRequest; expiresAt: number }; + let envelope: { parsed: AuthRequest; expiresAt: number; nonce: string; connection?: string }; try { envelope = decode(input.request); } catch { return null; } if (!Number.isFinite(envelope.expiresAt) || envelope.expiresAt <= Math.floor(Date.now() / 1000)) return null; const parsed = envelope.parsed; @@ -31,8 +45,16 @@ export async function consentDecision(env: Env, session: Session, input: z.infer const client = await env.OAUTH_PROVIDER.lookupClient(parsed.clientId); if (!client || !client.redirectUris.includes(parsed.redirectUri)) return null; if (input.scopes.some(scope => !parsed.scope.includes(scope) || !supported.includes(scope))) return null; - if (input.decision === "deny") { const redirect = new URL(parsed.redirectUri); redirect.searchParams.set("error", "access_denied"); redirect.searchParams.set("state", parsed.state); if (parsed.issuer) redirect.searchParams.set("iss", parsed.issuer); return { redirectTo: redirect.toString() }; } - const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: input.scopes, authMethod: "oauth" }; - const { redirectTo } = await env.OAUTH_PROVIDER.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: input.scopes, props }); - return { redirectTo }; + return databaseFor(env).transaction(async transaction => { + const preview = await transaction.query("UPDATE app.oauth_consent_previews SET used_at=now() WHERE id=$1 AND used_at IS NULL AND expires_at>clock_timestamp() RETURNING id", [envelope.nonce]); + if (!preview.rows.length) return null; + if (envelope.connection) { + const consumed = await transaction.query("UPDATE app.oauth_connections SET used_at=now(),ready=false WHERE id=$1 AND user_id=$2 AND expires_at>clock_timestamp() AND used_at IS NULL RETURNING id", [envelope.connection, session.userId]); + if (!consumed.rows.length) return null; + } + if (input.decision === "deny") { const redirect = new URL(parsed.redirectUri); redirect.searchParams.set("error", "access_denied"); redirect.searchParams.set("state", parsed.state); if (parsed.issuer) redirect.searchParams.set("iss", parsed.issuer); return { redirectTo: redirect.toString() }; } + const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: input.scopes, authMethod: "oauth" }; + const { redirectTo } = await env.OAUTH_PROVIDER!.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: input.scopes, props }); + return { redirectTo }; + }); } diff --git a/packages/api/src/device-oauth.ts b/packages/api/src/device-oauth.ts index 489a4371..2e29b932 100644 --- a/packages/api/src/device-oauth.ts +++ b/packages/api/src/device-oauth.ts @@ -3,6 +3,7 @@ import type { AuthRequest } from "@cloudflare/workers-oauth-provider"; import { hmac } from "./crypto"; import type { Env, OAuthProps } from "./types"; import { and, eq, gt } from "drizzle-orm"; +import type { DatabaseClient } from "./postgres/database"; import { databaseFor } from "./postgres/database"; import { oauthDeviceAuthorizations } from "./postgres/schema"; @@ -36,16 +37,6 @@ type DeviceRecord = { const noStoreHeaders = { "Content-Type": "application/json", "Cache-Control": "no-store", Pragma: "no-cache" }; const json = (body: unknown, status = 200) => Response.json(body, { status, headers: noStoreHeaders }); const oauthError = (error: string, description: string, status = 400) => json({ error, error_description: description }, status); -export function deviceLoginRedirect(appOrigin: string, returnTo: string): Response { - return new Response(null, { - status: 302, - headers: { - "Cache-Control": "no-store", - Location: `${appOrigin}/auth/login`, - "Set-Cookie": `factorize_oauth_return=${encodeURIComponent(returnTo)}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=600`, - }, - }); -} const random = (bytes = 32) => { const value = crypto.getRandomValues(new Uint8Array(bytes)); return btoa(String.fromCharCode(...value)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); @@ -62,7 +53,7 @@ async function challenge(value: string): Promise { async function sha256Hex(value: string): Promise { return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))), byte => byte.toString(16).padStart(2, "0")).join(""); } -function safeEqual(left: string, right: string): boolean { +export function safeEqual(left: string, right: string): boolean { if (left.length !== right.length) return false; let difference = 0; for (let index = 0; index < left.length; index++) difference |= left.charCodeAt(index) ^ right.charCodeAt(index); @@ -161,30 +152,46 @@ export async function deviceToken(request: Request, env: Env, oauthProvider: { f const basic = basicCredentials(request); const clientId = basic?.clientId ?? String(form.get("client_id") ?? ""); if (!deviceCode || !clientId) return oauthError("invalid_request", "device_code and client_id are required."); - const record = await readDevice(env, deviceCode); - const now = Math.floor(Date.now() / 1000); - if (!record || record.expiresAt <= now) return oauthError("expired_token", "The device code has expired."); - if (record.clientId !== clientId) return oauthError("invalid_grant", "The device code was not issued to this client."); - if (!await authenticateDeviceClient(request, env, form, { clientId: record.clientId, redirectUris: [record.redirectUri], tokenEndpointAuthMethod: record.tokenEndpointAuthMethod })) return oauthError("invalid_client", "Client authentication failed.", 401); - if (record.status === "denied") return oauthError("access_denied", "The resource owner denied the request."); - if (record.status === "pending") { - return oauthError("authorization_pending", "The resource owner has not completed authorization."); - } - if (!record.authorizationCode) return oauthError("server_error", "The approved device grant is incomplete.", 500); + const process = async (transaction?: DatabaseClient): Promise => { + const record = transaction ? (await transaction.query("SELECT record FROM app.oauth_device_authorizations WHERE device_code=$1 FOR UPDATE", [deviceCode])).rows[0]?.record as DeviceRecord | undefined : await readDevice(env, deviceCode); - const exchange = new URLSearchParams(); - form.forEach((value, key) => { if (key === "client_id" || key === "client_secret") exchange.append(key, String(value)); }); - exchange.set("grant_type", "authorization_code"); - exchange.set("code", record.authorizationCode); - exchange.set("redirect_uri", record.redirectUri); - exchange.set("code_verifier", await verifier(deviceCode, env.SESSION_SIGNING_SECRET)); - exchange.set("resource", record.resource); - const headers = new Headers({ "Content-Type": "application/x-www-form-urlencoded" }); - const authorization = request.headers.get("Authorization"); - if (authorization) headers.set("Authorization", authorization); - const response = await oauthProvider.fetch(new Request(`${env.APP_ORIGIN}/oauth/token`, { method: "POST", headers, body: exchange }), env, ctx); - if (response.ok) await deleteDevice(env, deviceCode); - return response; + const now = Math.floor(Date.now() / 1000); + if (!record || record.expiresAt <= now) return oauthError("expired_token", "The device code has expired."); + if (record.clientId !== clientId) return oauthError("invalid_grant", "The device code was not issued to this client."); + if (!await authenticateDeviceClient(request, env, form, { clientId: record.clientId, redirectUris: [record.redirectUri], tokenEndpointAuthMethod: record.tokenEndpointAuthMethod })) return oauthError("invalid_client", "Client authentication failed.", 401); + if (record.status === "denied") return oauthError("access_denied", "The resource owner denied the request."); + if (record.lastPolledAt !== undefined && now - record.lastPolledAt < record.interval) { + record.interval += 5; record.lastPolledAt = now; + if (transaction) await transaction.query("UPDATE app.oauth_device_authorizations SET record=$2,updated_at=now() WHERE device_code=$1", [deviceCode, JSON.stringify(record)]); + else await env.OAUTH_KV!.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: Math.max(1, record.expiresAt - now) }); + return oauthError("slow_down", `Poll no more often than every ${record.interval} seconds.`); + } + record.lastPolledAt = now; + if (transaction) await transaction.query("UPDATE app.oauth_device_authorizations SET record=$2,updated_at=now() WHERE device_code=$1", [deviceCode, JSON.stringify(record)]); + else await env.OAUTH_KV!.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: Math.max(1, record.expiresAt - now) }); + if (record.status === "pending") { + return oauthError("authorization_pending", "The resource owner has not completed authorization."); + } + if (!record.authorizationCode) return oauthError("server_error", "The approved device grant is incomplete.", 500); + + const exchange = new URLSearchParams(); + form.forEach((value, key) => { if (key === "client_id" || key === "client_secret") exchange.append(key, String(value)); }); + exchange.set("grant_type", "authorization_code"); + exchange.set("code", record.authorizationCode); + exchange.set("redirect_uri", record.redirectUri); + exchange.set("code_verifier", await verifier(deviceCode, env.SESSION_SIGNING_SECRET)); + exchange.set("resource", record.resource); + const headers = new Headers({ "Content-Type": "application/x-www-form-urlencoded" }); + const authorization = request.headers.get("Authorization"); + if (authorization) headers.set("Authorization", authorization); + const response = await oauthProvider.fetch(new Request(`${env.APP_ORIGIN}/oauth/token`, { method: "POST", headers, body: exchange }), env, ctx); + if (response.ok) { + if (transaction) await transaction.query("DELETE FROM app.oauth_device_authorizations WHERE device_code=$1", [deviceCode]); + else await deleteDevice(env, deviceCode); + } + return response; + }; + return env.DATABASE || env.HYPERDRIVE ? databaseFor(env).transaction(process) : process(); } export async function deviceVerification(request: Request, env: Env, oauth: OAuthHelpers, session: { tenantId: string; userId: string; email: string; sessionVersion: number }): Promise { @@ -197,8 +204,10 @@ export async function deviceVerification(request: Request, env: Env, oauth: OAut if (request.headers.get("Origin") !== env.APP_ORIGIN || request.headers.get("Sec-Fetch-Site") === "cross-site") return new Response("Invalid request origin", { status: 403 }); const decision = form?.get("decision"); if (decision !== "allow" && decision !== "deny") return Response.redirect(`${env.APP_ORIGIN}/device?user_code=${encodeURIComponent(suppliedCode)}`, 303); + const preview = await inspectDevice(env, suppliedCode); + if (!preview || !safeEqual(String(form?.get("signature") ?? ""), await deviceConsentSignature(env, session, preview))) return new Response("Invalid device consent. Review this request before approving it.", { status: 403 }); const result = await decideDevice(env, oauth, session, suppliedCode, decision); - return new Response(result ? result.status === "approved" ? "Device connected. You can close this window." : "Authorization denied. You can close this window." : "Invalid or expired device code", { status: result ? 200 : 400, headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" } }); + return new Response(result ? result.status === "approved" ? "Device connected. You can close this window." : "Authorization denied. You can close this window." : "Invalid or expired device code. Request a new code in your MCP client.", { status: result ? 200 : 400, headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" } }); } export async function inspectDevice(env: Env, userCode: string) { @@ -225,7 +234,9 @@ export async function decideDevice(env: Env, oauth: OAuthHelpers, session: { ten if (!env.DATABASE && !env.HYPERDRIVE) return authorize(await readDevice(env, code), record => writeDevice(env, code, normalized, record)); return databaseFor(env).transaction(async client => { const row = (await client.query("SELECT record FROM app.oauth_device_authorizations WHERE device_code=$1 AND expires_at>now() FOR UPDATE", [code])).rows[0]; - return authorize(row?.record ?? null, async record => { await client.query("UPDATE app.oauth_device_authorizations SET record=$2,updated_at=now() WHERE device_code=$1", [code, JSON.stringify(record)]); }); + const result = await authorize(row?.record ?? null, async record => { await client.query("UPDATE app.oauth_device_authorizations SET record=$2,updated_at=now() WHERE device_code=$1", [code, JSON.stringify(record)]); }); + if (result) await client.query("UPDATE app.oauth_connections SET used_at=now(),ready=false WHERE kind='device' AND device_user_code=$1 AND used_at IS NULL", [normalized]); + return result; }); } @@ -264,3 +275,7 @@ export async function deviceClientRegistration(request: Request, env: Env, oauth result.redirect_uris = originalRedirectUris; return json(result, response.status); } + +export function deviceConsentSignature(env: Env, session: { tenantId: string; userId: string; sessionVersion: number }, preview: { userCode: string; expiresAt: string }) { + return hmac(`device:${preview.userCode}:${preview.expiresAt}:${session.tenantId}:${session.userId}:${session.sessionVersion}`, env.SESSION_SIGNING_SECRET); +} diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 305c1e63..a4370e1a 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -1,3 +1,4 @@ +import { executeAuth } from "./auth-api"; import { STATIC_CSP, staticApp } from "./static-app"; import { Hono } from "hono"; import { deleteCookie, getCookie, setCookie } from "hono/cookie"; @@ -43,18 +44,6 @@ app.onError((error, c) => { return c.text("Internal Server Error", 500); }); -async function authIdentity(c: any, path: string, input: Record) { - const auth = new AuthRepository(databaseFor(c.env), c.env); - const result = path === "/signup" ? await auth.signup(input) : path === "/login" ? await auth.login(input) : path === "/reset/request" ? await auth.requestReset(input) : await auth.completeReset(input); - return { response: new Response(JSON.stringify(result.body), { status: result.status, headers: { "Content-Type": "application/json" } }), body: result.body as any }; -} -async function establishSession(c: any, identity: { userId: string; email: string; tenantId: string; sessionVersion: number }) { - const data = await new IdentityRepository(databaseFor(c.env), identity.tenantId).member(identity.userId); - if (data?.role !== "owner" || data.sessionVersion !== identity.sessionVersion) return false; - const lifetime = 60 * 60 * 24 * 7; - setCookie(c, "factorize_session", await signSession({ tenantId: identity.tenantId, userId: identity.userId, email: identity.email, exp: Math.floor(Date.now() / 1000) + lifetime, sessionVersion: data.sessionVersion }, c.env.SESSION_SIGNING_SECRET), { httpOnly: true, secure: new URL(c.env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/", maxAge: lifetime }); - return true; -} async function authed(c: any): Promise { return readSession(getCookie(c, "factorize_session"), c.env.SESSION_SIGNING_SECRET); } async function owner(c: any): Promise { const started = performance.now(); @@ -105,22 +94,22 @@ app.post("/auth/logout", async (c) => { return c.redirect("/"); }); -app.post("/auth/signup", async (c) => { const input = await c.req.parseBody(); const result = await authIdentity(c, "/signup", input as Record); return c.text(result.response.ok ? "Check your email for the next step." : "The request could not be completed. Try again.", result.response.status as any); }); -app.post("/auth/login", async (c) => { const input = await c.req.parseBody(); const result = await authIdentity(c, "/login", input as Record); if (!result.response.ok) return c.text("The request could not be completed. Return to the sign-in page and try again.", result.response.status as any); if (!await establishSession(c, result.body)) return c.text("This account cannot access the tenant", 403); const oauthReturn = getCookie(c, "factorize_oauth_return"); - if (oauthReturn?.startsWith("/authorize?") || oauthReturn?.startsWith("/device")) { deleteCookie(c, "factorize_oauth_return", { path: "/" }); return c.redirect(oauthReturn, 303); } - return c.redirect("/settings/integrations", 303); }); -app.post("/auth/password-reset", async (c) => { const input = await c.req.parseBody(); const result = await authIdentity(c, "/reset/request", input as Record); return c.text(result.response.ok ? "Check your email for the next step." : "The request could not be completed. Try again.", result.response.status as any); }); -app.post("/auth/password-reset/complete", async (c) => { const input = await c.req.parseBody(); const result = await authIdentity(c, "/reset/complete", input as Record); return result.response.ok ? c.redirect("/auth/login", 303) : c.text("The request could not be completed. Return to the sign-in page and try again.", result.response.status as any); }); - -app.post("/auth/verify", async (c) => { - const input = await c.req.parseBody(); - const result = await new AuthRepository(databaseFor(c.env), c.env).completeVerification(String(input.token ?? "")); - return result.status === 200 ? c.redirect("/auth/login", 303) : c.text("The request could not be completed. Return to the sign-in page and try again.", 400); -}); -app.post("/auth/verify/request", async (c) => { - const result = await new AuthRepository(databaseFor(c.env), c.env).requestEmail(await c.req.parseBody(), "verify"); - return c.text(result.status === 202 ? "Check your email for the next step." : "The request could not be completed. Try again.", result.status as any); -}); +// Form compatibility uses the same continuation and session rules as the JSON API. +async function authForm(c: any, action: "signup" | "login" | "reset-request" | "reset" | "verification" | "verification-request") { + const response = await executeAuth(action, c.req.raw, c.env, await c.req.parseBody()); + const body = await response.json() as any; + if (!response.ok) return c.text(body.error?.message ?? "The request could not be completed.", response.status); + const headers = new Headers(response.headers); + headers.set("Content-Type", "text/plain; charset=utf-8"); + if (body.returnTo) { headers.set("Location", body.returnTo); return new Response(null, { status: 303, headers }); } + return new Response(body.crossBrowser ? "Email verified. Return to the original browser to finish connecting your MCP client." : "Check your email for the next step.", { status: action === "signup" ? 201 : 200, headers }); +} +app.post("/auth/signup", c => authForm(c, "signup")); +app.post("/auth/login", c => authForm(c, "login")); +app.post("/auth/password-reset", c => authForm(c, "reset-request")); +app.post("/auth/password-reset/complete", c => authForm(c, "reset")); +app.post("/auth/verify", c => authForm(c, "verification")); +app.post("/auth/verify/request", c => authForm(c, "verification-request")); app.post("/auth/password-change", async (c) => { const session = await owner(c); if (!session) return c.text("Unauthorized", 401); const result = await new AuthRepository(databaseFor(c.env), c.env).changePassword(session.userId, await c.req.parseBody()); diff --git a/packages/api/src/oauth-continuation.ts b/packages/api/src/oauth-continuation.ts new file mode 100644 index 00000000..1d62314e --- /dev/null +++ b/packages/api/src/oauth-continuation.ts @@ -0,0 +1,49 @@ +import { serialize } from "hono/utils/cookie"; +import { databaseFor } from "./postgres/database"; +import { tokenDigest } from "./auth"; +import { requestCookie } from "./session"; +import { inspectDevice } from "./device-oauth"; +import type { Env } from "./types"; + +export type Connection = { id: string; browser_digest: string; destination: string; client_name: string; kind: "callback" | "device"; expires_at: Date; user_id: string | null; ready: boolean; ready_version: number | null; used_at: Date | null }; +export const connectionCookie = (id: string) => `factorize_connection_${id}`; +export async function connectionFor(env: Env, id: string): Promise { + if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) return null; + const row = (await databaseFor(env).pool.query("SELECT * FROM app.oauth_connections WHERE id=$1 AND expires_at>now() AND used_at IS NULL", [id])).rows[0]; + return row ?? null; +} +export async function originalBrowser(request: Request, env: Env, connection: Connection): Promise { + const cookie = requestCookie(request, connectionCookie(connection.id)); + return !!cookie && await tokenDigest(cookie, env.SESSION_SIGNING_SECRET) === connection.browser_digest; +} +export async function startConnection(request: Request, env: Env, destination: string) { + if (!destination.startsWith("/") || destination.startsWith("//") || /[\\\x00-\x20]/.test(destination)) return null; + const url = new URL(destination, env.APP_ORIGIN); + if (url.origin !== env.APP_ORIGIN || !["/authorize", "/device"].includes(url.pathname)) return null; + url.searchParams.delete("connection"); url.hash = ""; + let deviceUserCode: string | null = null, clientName: string, kind: "callback" | "device", expiresAt = new Date(Date.now() + 3600_000); + if (url.pathname === "/authorize") { + if (!env.OAUTH_PROVIDER) return null; + const parsed = await env.OAUTH_PROVIDER.parseAuthRequest(new Request(url)); + const client = await env.OAUTH_PROVIDER.lookupClient(parsed.clientId); + if (!client || !client.redirectUris.includes(parsed.redirectUri) || parsed.responseType !== "code" || !parsed.codeChallenge || parsed.codeChallengeMethod !== "S256") return null; + clientName = client.clientName ?? "this MCP client"; kind = "callback"; + } else { + const code = url.searchParams.get("user_code"); + const device = code ? await inspectDevice(env, code) : null; + if (code && !device) return null; + deviceUserCode = device?.userCode.replace("-", "") ?? null; + clientName = device?.clientName ?? "your device"; kind = "device"; + expiresAt = device ? new Date(device.expiresAt) : new Date(Date.now() + 600_000); + } + // Keep expired history only briefly; email tokens outlive neither this retention nor their own TTL. + await databaseFor(env).pool.query("DELETE FROM app.oauth_connections WHERE expires_at ({ status: 200, body: { ok: true } }); const invalidLink = () => ({ status: 400, body: { error: "The link is invalid or expired." } }); @@ -23,7 +24,7 @@ export class AuthRepository { if (error?.code === "23505") return { status: 409, body: { error: "That email is already registered. Sign in, resend verification, or reset your password." } }; throw error; } - await this.issueEmail(userId, email, "verify"); + await this.issueEmail(userId, email, "verify", input.connection as string | undefined); return { status: 201, body: { ok: true } }; } @@ -41,10 +42,14 @@ export class AuthRepository { }); } - private async issueEmail(userId: string, email: string, purpose: "verify" | "reset") { + private async issueEmail(userId: string, email: string, purpose: "verify" | "reset", connection?: string) { + if (connection) { + const bound = await this.database.pool.query("UPDATE app.oauth_connections SET user_id=$2 WHERE id=$1 AND expires_at>now() AND used_at IS NULL AND (user_id IS NULL OR user_id=$2) RETURNING id", [connection, userId]); + if (!bound.rows.length) throw new Error("Invalid or expired connection. Restart from your MCP client."); + } const token = crypto.randomUUID() + crypto.randomUUID(), digest = await tokenDigest(token, this.env.SESSION_SIGNING_SECRET); - await this.database.pool.query("INSERT INTO app.auth_reset_tokens(digest,user_id,expires_at,purpose) VALUES ($1,$2,now()+interval '1 hour',$3)", [digest, userId, purpose]); - try { await sendAuthEmail(this.env, email, token, purpose); } + await this.database.pool.query("INSERT INTO app.auth_reset_tokens(digest,user_id,expires_at,purpose,connection_id) VALUES ($1,$2,now()+interval '1 hour',$3,$4)", [digest, userId, purpose, connection ?? null]); + try { await sendAuthEmail(this.env, email, token, purpose, connection); } catch (error) { await this.database.pool.query("DELETE FROM app.auth_reset_tokens WHERE digest=$1", [digest]); throw error; } } @@ -52,7 +57,7 @@ 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); + if (user && (purpose === "reset" || !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"); } @@ -71,7 +76,7 @@ export class AuthRepository { if (!validPassword(password)) return { status: 400, body: { error: "Use a password of 12–200 characters." } }; return this.consumeToken(String(input.token ?? ""), "reset", await hashPassword(password)); } - private async consumeToken(token: string, purpose: "verify" | "reset", passwordHash?: string) { + private async consumeToken(token: string, purpose: "verify" | "reset", passwordHash?: string): Promise { if (!token) return invalidLink(); const digest = await tokenDigest(token, this.env.SESSION_SIGNING_SECRET); try { @@ -81,7 +86,7 @@ export class AuthRepository { const row = (await client.query<{ user_id: string; email: string }>(`SELECT u.id user_id,u.email FROM app.auth_users u WHERE u.id=( SELECT user_id FROM app.auth_reset_tokens WHERE digest=$1 AND purpose=$2 AND used_at IS NULL AND expires_at>now()) FOR UPDATE`, [digest, purpose])).rows[0]; if (!row) return false; - const active = await client.query("SELECT digest 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]); + 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") { // Email possession lets legacy Linear-only users establish native credentials. @@ -92,10 +97,13 @@ export class AuthRepository { } await client.query("UPDATE app.auth_users SET email_verified=true WHERE id=$1", [row.user_id]); await this.ensureWorkspace(client, row.user_id, row.email); - await client.query("UPDATE app.auth_reset_tokens SET used_at=now() WHERE user_id=$1 AND purpose=$2 AND used_at IS NULL", [row.user_id, purpose]); - return true; + await client.query("UPDATE app.auth_reset_tokens SET used_at=now() WHERE used_at IS NULL AND (digest=$1 OR (user_id=$2 AND purpose='reset' AND $3='reset'))", [digest, row.user_id, purpose]); + const connection = active.rows[0].connection_id as string | null; + if (connection) await client.query("UPDATE app.oauth_connections SET ready=true,ready_version=(SELECT session_version FROM app.members WHERE user_id=$2 AND role='owner' ORDER BY created_at,tenant_id LIMIT 1) WHERE id=$1 AND user_id=$2 AND expires_at>now() AND used_at IS NULL", [connection, row.user_id]); + const member = (await client.query<{ tenant_id: string; session_version: number }>("SELECT tenant_id,session_version FROM app.members WHERE user_id=$1 AND role='owner' ORDER BY created_at,tenant_id LIMIT 1", [row.user_id])).rows[0]; + return { userId: row.user_id, email: row.email, tenantId: member?.tenant_id, sessionVersion: member?.session_version, connection: connection ?? undefined }; }); - return completed ? ok() : invalidLink(); + return completed ? { status: 200, body: { ok: true, ...completed } } : invalidLink(); } catch (error) { throw error; } } diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index fc980d9f..bf6b04ca 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -21,7 +21,13 @@ export const authUsers = app.table("auth_users", { id: uuid("id").primaryKey(), 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)]); -export const authResetTokens = app.table("auth_reset_tokens", { 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')`)]); +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 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')`)]); 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 }) }); export const oauthDeviceAuthorizations = app.table("oauth_device_authorizations", { deviceCode: text("device_code").primaryKey(), userCode: text("user_code").notNull().unique(), record: jsonb("record").$type>().notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), createdAt: createdAt(), updatedAt: updatedAt(), @@ -117,7 +123,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({ })); export const databaseSchema = { - schemaMigrations, tenants, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, + schemaMigrations, tenants, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, connections, linearWorkspaces, githubInstallations, githubSetupStates, jobs, triggers, webhookConditionsCutover, invocations, jobRuns, runs, runArtifacts, runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, jobEditDeliveries, jobEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks, diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index 438ff11f..34532765 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -4,8 +4,9 @@ import app from "./index"; import { readSession, requestCookie } from "./session"; import { isBrowserAuthOperation } from "./api-contract"; import { ProtectedApiHandler, protectedApiFetch } from "./protected-api"; -import { hmac } from "./crypto"; -import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceLoginRedirect, deviceToken, deviceVerification } from "./device-oauth"; +import { startConnection, connectionFor } from "./oauth-continuation"; +import { consentDecision } from "./consent-api"; +import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceToken, deviceVerification } from "./device-oauth"; import type { Env, OAuthProps } from "./types"; import { authenticateAccessToken } from "./access-tokens"; import { artifactUpload } from "./artifact-upload"; @@ -38,9 +39,19 @@ const defaultHandler: ExportedHandler = { try { if (request.method === "POST" && (request.headers.get("Origin") !== env.APP_ORIGIN || request.headers.get("Sec-Fetch-Site") === "cross-site")) return new Response("Invalid request origin", { status: 403 }); const session = await currentOwner(request, env); - if (!session) { - return deviceLoginRedirect(env.APP_ORIGIN, url.pathname + url.search); + if (request.method === "GET" || request.method === "HEAD") { + let connection = url.searchParams.get("connection"); + if (!connection && (!session || url.pathname === "/authorize")) { + const started = await startConnection(request, env, url.pathname + url.search); + if (!started) return new Response("Invalid or expired MCP request. Start a new connection from your client.", { status: 400 }); + connection = started.connection; + url.searchParams.set("connection", connection); + return new Response(null, { status: 302, headers: { Location: session ? url.toString() : `${env.APP_ORIGIN}/auth/login?connection=${connection}`, "Set-Cookie": started.cookie, "Cache-Control": "no-store" } }); + } + if (connection && !await connectionFor(env, connection)) return new Response("This MCP connection expired or already completed. Start a new connection from your client.", { status: 400 }); + if (!session) return Response.redirect(`${env.APP_ORIGIN}/auth/login${connection ? `?connection=${connection}` : ""}`, 302); } + if (!session) return new Response("Sign in before approving this request.", { status: 401 }); if (url.pathname === "/device") return request.method === "GET" || request.method === "HEAD" ? (await staticApp(request, env))! : deviceVerification(request, env, env.OAUTH_PROVIDER!, session); if (request.method === "GET" || request.method === "HEAD") { const parsed = await env.OAUTH_PROVIDER!.parseAuthRequest(request); @@ -49,19 +60,11 @@ const defaultHandler: ExportedHandler = { return (await staticApp(request, env))!; } if (request.method !== "POST") return new Response("Method not allowed", { status: 405 }); - const form = await request.formData(), payload = String(form.get("request") ?? ""), signature = String(form.get("signature") ?? ""); - if (!payload || signature !== await hmac(`${payload}.${session.tenantId}.${session.userId}`, env.SESSION_SIGNING_SECRET)) return new Response("Invalid consent request", { status: 400 }); - const parsed = JSON.parse(atob(payload)) as AuthRequest; - const client = await env.OAUTH_PROVIDER!.lookupClient(parsed.clientId); - if (!client || !client.redirectUris.includes(parsed.redirectUri)) return new Response("Invalid consent request", { status: 400 }); - if (form.get("decision") !== "allow") { - const redirect = new URL(parsed.redirectUri); redirect.searchParams.set("error", "access_denied"); redirect.searchParams.set("state", parsed.state); if (parsed.issuer) redirect.searchParams.set("iss", parsed.issuer); - return Response.redirect(redirect, 302); - } - const granted = form.getAll("scope").map(String).filter(scope => parsed.scope.includes(scope) && scopes.includes(scope)); - const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: granted, authMethod: "oauth" }; - const { redirectTo } = await env.OAUTH_PROVIDER!.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: granted, props }); - return Response.redirect(redirectTo, 302); + const form = await request.formData(); + const decision = form.get("decision"); + if (decision !== "allow" && decision !== "deny") return new Response("Invalid decision", { status: 400 }); + const result = await consentDecision(env, session, { request: String(form.get("request") ?? ""), signature: String(form.get("signature") ?? ""), decision, scopes: form.getAll("scope").map(String) as any }); + return result ? Response.redirect(result.redirectTo, 302) : new Response("Invalid, expired, or already completed consent request. Restart from your client.", { status: 400 }); } catch (error) { if (error instanceof AuthorizationError) return oauthError(error); throw error; } }, }; diff --git a/packages/api/test/auth-api.test.ts b/packages/api/test/auth-api.test.ts index 773ab895..beb00d64 100644 --- a/packages/api/test/auth-api.test.ts +++ b/packages/api/test/auth-api.test.ts @@ -212,7 +212,7 @@ describe("cookie-only consent and device API boundaries", () => { ["/api/v1/oauth/consent/preview", { authorizationQuery: "client_id=client" }], ["/api/v1/oauth/consent/decision", { request: "request", signature: "signature", decision: "allow", scopes: [] }], ["/api/v1/oauth/device/preview", { userCode: "ABCD-EFGH" }], - ["/api/v1/oauth/device/decision", { userCode: "ABCD-EFGH", decision: "allow" }], + ["/api/v1/oauth/device/decision", { userCode: "ABCD-EFGH", signature: "signature", decision: "allow" }], ] as const; it("requires an authoritative owner session and never accepts bearer credentials", async () => { for (const [path, body] of requests) { @@ -226,3 +226,20 @@ describe("cookie-only consent and device API boundaries", () => { } }); }); + +it("protects public onboarding start/resume operations against CSRF, bearer identity and malformed input", async () => { + const operations = [ + ["/api/v1/auth/connections", { returnTo: "/device" }], + ["/api/v1/auth/connections/resume", { connection: "11111111-1111-4111-8111-111111111111" }], + ] as const; + for (const [path, body] of operations) { + for (const headers of [{ Origin: "https://evil.test" }, { "Sec-Fetch-Site": "cross-site" }, { Authorization: "Bearer unrelated" }] as Record[]) { + const response = await call(path, body, headers); + expect(response.status).toBe(403); + expect(response.headers.get("Set-Cookie")).toBeNull(); + await contract(response, path, "POST"); + } + expect((await call(path, { ...body, userId: "forged" })).status).toBe(400); + } + expect((await call("/api/v1/auth/connections/resume", { connection: "invalid" })).status).toBe(400); +}); diff --git a/packages/api/test/consent-api.test.ts b/packages/api/test/consent-api.test.ts index bccfb75a..e3d8591c 100644 --- a/packages/api/test/consent-api.test.ts +++ b/packages/api/test/consent-api.test.ts @@ -6,8 +6,13 @@ const session = { tenantId: "tenant", userId: "owner", email: "owner@example.tes const parsed = { responseType: "code", clientId: "client", redirectUri: "https://client.test/callback", scope: ["flows:read", "runs:write"], state: "state", codeChallenge: "challenge", codeChallengeMethod: "S256", resource: "https://factorize.test/mcp", issuer: "https://factorize.test" }; function fixture() { const values = new Map(); + const used = new Set(); + const query = vi.fn(async (_sql: string, args: unknown[]) => { + if (_sql.startsWith("INSERT") || _sql.startsWith("DELETE")) return { rows: [] }; + const id = String(args[0]); if (used.has(id)) return { rows: [] }; used.add(id); return { rows: [{ id }] }; + }); const oauth = { parseAuthRequest: vi.fn(async () => parsed), lookupClient: vi.fn(async () => ({ clientId: "client", clientName: "External client", redirectUris: [parsed.redirectUri], tokenEndpointAuthMethod: "none" })), completeAuthorization: vi.fn(async (_options: unknown) => ({ redirectTo: parsed.redirectUri + "?code=authorized&state=state" })) }; - const env = { APP_ORIGIN: "https://factorize.test", SESSION_SIGNING_SECRET: "test-signing", OAUTH_PROVIDER: oauth, OAUTH_KV: { get: async (key: string, type?: string) => { const value = values.get(key); return value ? type === "json" ? JSON.parse(value) : value : null; }, put: async (key: string, value: string) => { values.set(key, value); }, delete: async (key: string) => { values.delete(key); } } } as unknown as Env; + const env = { DATABASE: { pool: { query }, transaction: async (work: any) => work({ query }) }, APP_ORIGIN: "https://factorize.test", SESSION_SIGNING_SECRET: "test-signing", OAUTH_PROVIDER: oauth, OAUTH_KV: { get: async (key: string, type?: string) => { const value = values.get(key); return value ? type === "json" ? JSON.parse(value) : value : null; }, put: async (key: string, value: string) => { values.set(key, value); }, delete: async (key: string) => { values.delete(key); } } } as unknown as Env; return { env, oauth }; } describe("static consent support", () => { @@ -34,7 +39,7 @@ describe("static consent support", () => { } finally { vi.useRealTimers(); } }); it("inspects only public device metadata and keeps grant/code state server-owned", async () => { - const { env, oauth } = fixture(), form = new FormData(); form.set("client_id", "client"); form.set("scope", "flows:read"); + const { env, oauth } = fixture(); delete env.DATABASE; const form = new FormData(); form.set("client_id", "client"); form.set("scope", "flows:read"); const issued = await (await deviceAuthorization(new Request(env.APP_ORIGIN + "/oauth/device_authorization", { method: "POST", body: form }), env, oauth as any, ["flows:read"])).json() as any; const info = await inspectDevice(env, issued.user_code); expect(info).toMatchObject({ clientName: "External client", scopes: ["flows:read"] }); expect(info).not.toHaveProperty("device_code"); expect(await decideDevice(env, oauth as any, session, issued.user_code, "allow")).toEqual({ status: "approved" }); expect(await inspectDevice(env, issued.user_code)).toBeNull(); expect(await decideDevice(env, oauth as any, session, issued.user_code, "allow")).toBeNull(); expect(oauth.completeAuthorization).toHaveBeenCalledTimes(1); diff --git a/packages/api/test/device-oauth.test.ts b/packages/api/test/device-oauth.test.ts index ee42d3b7..91a7333f 100644 --- a/packages/api/test/device-oauth.test.ts +++ b/packages/api/test/device-oauth.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceLoginRedirect, deviceToken, deviceVerification } from "../src/device-oauth"; +import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceConsentSignature, inspectDevice, deviceToken, deviceVerification } from "../src/device-oauth"; import type { Env } from "../src/types"; class MemoryKv { @@ -24,14 +24,6 @@ function environment(kv: MemoryKv): Env { const publicClient = { clientId: "client-1", clientName: "Codex", redirectUris: ["http://127.0.0.1/callback"], tokenEndpointAuthMethod: "none" }; describe("OAuth device authorization", () => { - it("redirects unauthenticated device approval through login and preserves the device code", () => { - const response = deviceLoginRedirect("https://factorize.test", "/device?user_code=ABCD-2345"); - expect(response.status).toBe(302); - expect(response.headers.get("cache-control")).toBe("no-store"); - expect(response.headers.get("location")).toBe("https://factorize.test/auth/login"); - expect(response.headers.get("set-cookie")).toContain("factorize_oauth_return=%2Fdevice%3Fuser_code%3DABCD-2345"); - }); - it("issues RFC 8628 device and user codes", async () => { const kv = new MemoryKv(), env = environment(kv); const response = await deviceAuthorization(new Request("https://factorize.test/oauth/device_authorization", { @@ -56,12 +48,16 @@ describe("OAuth device authorization", () => { await expect(badResource.json()).resolves.toMatchObject({ error: "invalid_target" }); }); - it("keeps polling read-only while approval is outstanding", async () => { + it("increases the polling interval after every early poll", async () => { const kv = new MemoryKv(), env = environment(kv); const issue = await deviceAuthorization(new Request("https://factorize.test/oauth/device_authorization", { method: "POST", body: new URLSearchParams({ client_id: "client-1", scope: "runs:read" }) }), env, { lookupClient: vi.fn().mockResolvedValue(publicClient), completeAuthorization: vi.fn() }, ["flows:read", "runs:read"]); const { device_code } = await issue.json() as any; const poll = () => deviceToken(new Request("https://factorize.test/oauth/token", { method: "POST", body: new URLSearchParams({ grant_type: DEVICE_GRANT, client_id: "client-1", device_code }) }), env, { fetch: vi.fn() }, {} as ExecutionContext); await expect((await poll()).json()).resolves.toMatchObject({ error: "authorization_pending" }); + await expect((await poll()).json()).resolves.toMatchObject({ error: "slow_down" }); + const record = JSON.parse(kv.values.get(`device:${device_code}`)!); + expect(record.interval).toBe(10); + record.lastPolledAt -= 10; kv.values.set(`device:${device_code}`, JSON.stringify(record)); await expect((await poll()).json()).resolves.toMatchObject({ error: "authorization_pending" }); }); @@ -71,7 +67,8 @@ describe("OAuth device authorization", () => { const oauth = { lookupClient: vi.fn().mockResolvedValue(publicClient), completeAuthorization }; const issue = await deviceAuthorization(new Request("https://factorize.test/oauth/device_authorization", { method: "POST", body: new URLSearchParams({ client_id: "client-1", scope: "runs:read" }) }), env, oauth, ["flows:read", "runs:read"]); const issued = await issue.json() as any; - const approved = await deviceVerification(new Request("https://factorize.test/device", { method: "POST", headers: { Origin: env.APP_ORIGIN }, body: new URLSearchParams({ user_code: issued.user_code, decision: "allow" }) }), env, oauth, { tenantId: "tenant-1", userId: "owner-1", email: "owner@example.com", sessionVersion: 3 }); + const signature = await deviceConsentSignature(env, { tenantId: "tenant-1", userId: "owner-1", sessionVersion: 3 }, (await inspectDevice(env, issued.user_code))!); + const approved = await deviceVerification(new Request("https://factorize.test/device", { method: "POST", headers: { Origin: env.APP_ORIGIN }, body: new URLSearchParams({ user_code: issued.user_code, signature, decision: "allow" }) }), env, oauth, { tenantId: "tenant-1", userId: "owner-1", email: "owner@example.com", sessionVersion: 3 }); expect(approved.status).toBe(200); expect(completeAuthorization).toHaveBeenCalledWith(expect.objectContaining({ scope: ["runs:read"], revokeExistingGrants: false })); const providerFetch = vi.fn(async (request: Request) => { diff --git a/packages/api/test/oauth-onboarding.postgres.test.ts b/packages/api/test/oauth-onboarding.postgres.test.ts new file mode 100644 index 00000000..cc515f8e --- /dev/null +++ b/packages/api/test/oauth-onboarding.postgres.test.ts @@ -0,0 +1,130 @@ +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { protectedApiFetch } from "../src/protected-api"; +import { deviceAuthorization, deviceToken, DEVICE_GRANT } from "../src/device-oauth"; +import { readSession } from "../src/session"; +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); +const password = "correct horse battery staple"; +describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP onboarding public boundaries with PostgreSQL", () => { + let f: Awaited>, emails: string[] = []; + const grant = vi.fn(async ({ request }: any) => ({ redirectTo: `${request.redirectUri}?code=grant&state=${request.state}` })); + const oauth = { + lookupClient: async (id: string) => id === "client" ? { clientId: id, clientName: "MCP CLI", redirectUris: ["http://127.0.0.1/callback"], tokenEndpointAuthMethod: "none" } : null, + parseAuthRequest: async (request: Request) => { + const q = new URL(request.url).searchParams; + if (q.get("redirect_uri") !== "http://127.0.0.1/callback" || q.get("code_challenge_method") !== "S256") throw new Error("invalid redirect/PKCE"); + return { responseType: "code", clientId: q.get("client_id"), redirectUri: q.get("redirect_uri"), scope: ["flows:read"], state: q.get("state"), codeChallenge: q.get("code_challenge"), codeChallengeMethod: "S256", resource: f.env.APP_ORIGIN + "/mcp", issuer: f.env.APP_ORIGIN }; + }, completeAuthorization: grant, + }; + beforeAll(async () => { f = await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!); Object.assign(f.env, { OAUTH_PROVIDER: oauth, POSTMARK_SERVER_TOKEN: "test-only", POSTMARK_FROM_EMAIL: "accounts@example.test", POSTMARK_MESSAGE_STREAM: "outbound" }); }); + afterAll(async () => { await f?.cleanup(); }); + afterEach(() => { vi.unstubAllGlobals(); emails = []; grant.mockClear(); }); + function mail() { vi.stubGlobal("fetch", vi.fn(async (_url: unknown, init: RequestInit) => { emails.push(JSON.parse(String(init.body)).TextBody); return Response.json({ ErrorCode: 0 }); })); } + const token = (i = emails.length - 1) => new URL(emails[i].match(/https:\/\/\S+/)![0]).searchParams.get("token")!; + const email = () => `onboarding_${crypto.randomUUID()}@example.test`; + const call = (path: string, body: object, cookie = "", origin = f.env.APP_ORIGIN) => protectedApiFetch(new Request(f.env.APP_ORIGIN + path, { method: "POST", headers: { Origin: origin, Cookie: cookie, "Content-Type": "application/json" }, body: JSON.stringify(body) }), f.env, null, {} as ExecutionContext); + const tokenBody = async (response: Response) => await response.json() as { error?: string; access_token?: string }; + const cookieOf = (response: Response) => response.headers.get("Set-Cookie")!.split(";")[0]; + const sessionOf = (cookie: string) => readSession(decodeURIComponent(cookie.split("=").slice(1).join("=")), f.env.SESSION_SIGNING_SECRET); + function destination(state: string) { return "/authorize?" + new URLSearchParams({ client_id: "client", response_type: "code", redirect_uri: "http://127.0.0.1/callback", scope: "flows:read", state, code_challenge: `challenge-${state}`, code_challenge_method: "S256" }); } + async function start(state: string, returnTo = destination(state)) { + const response = await call("/api/v1/auth/connections", { returnTo }); expect(response.status).toBe(200); + expect(response.headers.get("Set-Cookie")).toContain("HttpOnly"); + return { ...await response.json() as any, cookie: cookieOf(response), destination: returnTo }; + } + async function consent(returnTo: string, cookie: string, decision: "allow" | "deny" = "allow") { + const previewResponse = await call("/api/v1/oauth/consent/preview", { authorizationQuery: returnTo.split("?")[1] }, cookie); expect(previewResponse.status).toBe(200); + const preview = await previewResponse.json() as any; + const input = { request: preview.request, signature: preview.signature, decision, scopes: ["flows:read"] }; + return { response: await call("/api/v1/oauth/consent/decision", input, cookie), input }; + } + it("signs up, verifies, signs in automatically and explicitly consents once with original state/PKCE", async () => { + mail(); const a = await start("new-user"), account = email(); + expect((await call("/api/v1/auth/signup", { email: account, password, connection: a.connection }, a.cookie)).status).toBe(202); + expect(await (await call("/api/v1/auth/connections/resume", { connection: a.connection }, a.cookie)).json()).toMatchObject({ pending: true, clientName: "MCP CLI" }); + const verification = token(); const verified = await call("/api/v1/auth/email-verification/complete", { token: verification }, a.cookie); + expect(verified.status).toBe(200); const body = await verified.json() as any, cookie = a.cookie + "; " + cookieOf(verified); + expect(await sessionOf(cookieOf(verified))).toMatchObject({ email: account }); + expect(body.returnTo).toBe(a.destination + `&connection=${a.connection}`); expect(grant).not.toHaveBeenCalled(); + expect((await call("/api/v1/auth/email-verification/complete", { token: verification }, a.cookie)).status).toBe(400); + const approved = await consent(body.returnTo, cookie); expect(approved.response.status).toBe(200); + expect(grant).toHaveBeenCalledWith(expect.objectContaining({ request: expect.objectContaining({ state: "new-user", codeChallenge: "challenge-new-user", redirectUri: "http://127.0.0.1/callback" }) })); + expect((await call("/api/v1/oauth/consent/decision", approved.input, cookie)).status).toBe(400); + expect((await call("/api/v1/auth/connections/resume", { connection: a.connection }, a.cookie)).status).toBe(400); expect(grant).toHaveBeenCalledTimes(1); + }); + it("verifies in another browser but allows callback consent only in the initiating browser; denial is final", async () => { + mail(); const a = await start("another-browser"), account = email(); + await call("/api/v1/auth/signup", { email: account, password, connection: a.connection }, a.cookie); + const verified = await call("/api/v1/auth/email-verification/complete", { token: token() }); expect(await verified.json()).toEqual({ ok: true, crossBrowser: true }); + const foreign = cookieOf(verified), returnTo = a.destination + `&connection=${a.connection}`; + expect((await call("/api/v1/oauth/consent/preview", { authorizationQuery: returnTo.split("?")[1] }, foreign)).status).toBe(400); + expect((await call("/api/v1/auth/connections/resume", { connection: a.connection }, foreign)).status).toBe(400); + const resumed = await call("/api/v1/auth/connections/resume", { connection: a.connection }, a.cookie); expect(await resumed.json()).toMatchObject({ returnTo }); + const cookie = a.cookie + "; " + cookieOf(resumed); + expect(await (await call("/api/v1/auth/connections/resume", { connection: a.connection }, cookie)).json()).toMatchObject({ returnTo }); + const denied = await consent(returnTo, cookie, "deny"); expect(denied.response.status).toBe(200); + expect(new URL((await denied.response.json() as any).redirectTo).searchParams.get("error")).toBe("access_denied"); + expect((await call("/api/v1/oauth/consent/decision", denied.input, cookie)).status).toBe(400); expect(grant).not.toHaveBeenCalled(); + }); + it("isolates simultaneous requests through resend, existing-account login and password recovery", async () => { + mail(); const a = await start("a"), b = await start("b"), account = email(), cookies = a.cookie + "; " + b.cookie; + expect(a.cookie.split("=")[0]).not.toBe(b.cookie.split("=")[0]); + await call("/api/v1/auth/signup", { email: account, password, connection: a.connection }, cookies); const first = token(); + await call("/api/v1/auth/email-verification/request", { email: account, connection: b.connection }, cookies); const second = token(); + for (const [t, c] of [[first, a], [second, b]]) { const verified = await call("/api/v1/auth/email-verification/complete", { token: t }, cookies); expect(verified.status).toBe(200); expect((await verified.json() as any).returnTo).toContain(`connection=${c.connection}`); } + const c = await start("existing"), signed = await call("/api/v1/auth/login", { email: account, password, connection: c.connection }, c.cookie); + expect(signed.status).toBe(200); const signedBody = await signed.json() as any; expect(signedBody.returnTo).toContain("state=existing"); + expect((await consent(signedBody.returnTo, c.cookie + "; " + cookieOf(signed))).response.status).toBe(200); + const d = await start("recovery"); await call("/api/v1/auth/password-reset/request", { email: account, connection: d.connection }, d.cookie); + const reset = await call("/api/v1/auth/password-reset/complete", { token: token(), password: "replacement long password" }, d.cookie); + expect(reset.status).toBe(200); const body = await reset.json() as any; expect(body.returnTo).toContain(`connection=${d.connection}`); + expect((await consent(body.returnTo, d.cookie + "; " + cookieOf(reset))).response.status).toBe(200); + }); + it("rejects forged/expired connections and revoked verification without extending the client request", async () => { + mail(); for (const returnTo of ["https://evil.test", "//evil.test", destination("bad").replace("127.0.0.1", "evil.test"), destination("bad").replace("S256", "plain")]) expect((await call("/api/v1/auth/connections", { returnTo })).status).toBe(400); + const a = await start("expired"), account = email(); + expect((await call("/api/v1/auth/signup", { email: account, password, connection: a.connection })).status).toBe(400); + await call("/api/v1/auth/signup", { email: account, password, connection: a.connection }, a.cookie); const verification = token(); + await f.db.pool.query("UPDATE app.oauth_connections SET expires_at=now()-interval '1 second' WHERE id=$1", [a.connection]); + expect((await call("/api/v1/auth/email-verification/request", { email: account, connection: a.connection }, a.cookie)).status).toBe(400); + const verified = await call("/api/v1/auth/email-verification/complete", { token: verification }, a.cookie); expect(verified.status).toBe(200); expect(await verified.json()).toMatchObject({ returnTo: "/auth/login?expired=1" }); + expect((await call("/api/v1/auth/connections/resume", { connection: a.connection }, a.cookie)).status).toBe(400); expect(grant).not.toHaveBeenCalled(); + const b = await start("revoked"); await call("/api/v1/auth/password-reset/request", { email: account, connection: b.connection }, b.cookie); + const reset = await call("/api/v1/auth/password-reset/complete", { token: token(), password }), session = await sessionOf(cookieOf(reset)); + await f.db.pool.query("UPDATE app.members SET session_version=session_version+1 WHERE user_id=$1", [session!.userId]); + expect((await call("/api/v1/auth/connections/resume", { connection: b.connection }, b.cookie)).status).toBe(403); + }); + async function device() { return await (await deviceAuthorization(new Request(f.env.APP_ORIGIN + "/oauth/device_authorization", { method: "POST", body: new URLSearchParams({ client_id: "client", scope: "flows:read" }) }), f.env, oauth as any, ["flows:read"])).json() as any; } + it("continues device signup in the verification browser and rejects unsigned, cross-owner and forged consent", async () => { + mail(); const issued = await device(), a = await start("device", `/device?user_code=${issued.user_code}`), account = email(); + await call("/api/v1/auth/signup", { email: account, password, connection: a.connection }, a.cookie); + const verified = await call("/api/v1/auth/email-verification/complete", { token: token() }), cookie = cookieOf(verified); + expect((await verified.json() as any).returnTo).toContain("/device?user_code="); expect(grant).not.toHaveBeenCalled(); + const preview = await (await call("/api/v1/oauth/device/preview", { userCode: issued.user_code }, cookie)).json() as any; + const input = { userCode: issued.user_code, decision: "allow", signature: preview.signature }; + expect((await call("/api/v1/oauth/device/decision", { ...input, signature: "forged" }, cookie)).status).toBe(403); + expect((await call("/api/v1/oauth/device/decision", { userCode: issued.user_code, decision: "allow" }, cookie)).status).toBe(400); + expect((await call("/api/v1/oauth/device/decision", input, f.cookie)).status).toBe(403); + expect((await call("/api/v1/oauth/device/decision", input, cookie, "https://evil.test")).status).toBe(403); + expect((await call("/api/v1/oauth/device/decision", input, cookie)).status).toBe(200); + expect((await call("/api/v1/oauth/device/decision", input, cookie)).status).toBe(400); expect(grant).toHaveBeenCalledTimes(1); + }); + it("serializes polls with pending, slow_down, denied, expired and successful single-use token outcomes", async () => { + const issued = await device(), fetchToken = vi.fn(async () => Response.json({ access_token: "token", token_type: "bearer" })); + const poll = (code = issued.device_code, client = "client") => deviceToken(new Request(f.env.APP_ORIGIN + "/oauth/token", { method: "POST", body: new URLSearchParams({ grant_type: DEVICE_GRANT, client_id: client, device_code: code }) }), f.env, { fetch: fetchToken }, {} as ExecutionContext); + expect((await tokenBody(await poll(issued.device_code, "other"))).error).toBe("invalid_grant"); + const results = await Promise.all([poll(), poll()]); expect((await Promise.all(results.map(tokenBody))).map(r => r.error).sort()).toEqual(["authorization_pending", "slow_down"]); + expect((await tokenBody(await poll())).error).toBe("slow_down"); + expect((await f.db.pool.query("SELECT record FROM app.oauth_device_authorizations WHERE device_code=$1", [issued.device_code])).rows[0].record.interval).toBe(15); + const p = await (await call("/api/v1/oauth/device/preview", { userCode: issued.user_code }, f.cookie)).json() as any; + await call("/api/v1/oauth/device/decision", { userCode: issued.user_code, signature: p.signature, decision: "deny" }, f.cookie); + expect((await tokenBody(await poll())).error).toBe("access_denied"); expect(fetchToken).not.toHaveBeenCalled(); + const expired = await device(); await f.db.pool.query("UPDATE app.oauth_device_authorizations SET expires_at=now()-interval '1 second',record=jsonb_set(record,'{expiresAt}',to_jsonb(1)) WHERE device_code=$1", [expired.device_code]); + expect((await tokenBody(await poll(expired.device_code))).error).toBe("expired_token"); expect((await call("/api/v1/oauth/device/preview", { userCode: expired.user_code }, f.cookie)).status).toBe(400); + const approved = await device(), preview = await (await call("/api/v1/oauth/device/preview", { userCode: approved.user_code }, f.cookie)).json() as any; + await call("/api/v1/oauth/device/decision", { userCode: approved.user_code, signature: preview.signature, decision: "allow" }, f.cookie); + const tokens = await Promise.all([poll(approved.device_code), poll(approved.device_code)]); + expect((await Promise.all(tokens.map(tokenBody))).map(r => r.access_token ?? r.error).sort()).toEqual(["expired_token", "token"]); expect(fetchToken).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/api/test/protocol-api.postgres.test.ts b/packages/api/test/protocol-api.postgres.test.ts index a2d46660..360a4911 100644 --- a/packages/api/test/protocol-api.postgres.test.ts +++ b/packages/api/test/protocol-api.postgres.test.ts @@ -29,7 +29,7 @@ describe.skipIf(!url)("cookie protocol APIs against PostgreSQL", () => { const issued = await (await deviceAuthorization(new Request(f.env.APP_ORIGIN + "/oauth/device_authorization", { method: "POST", body: form }), f.env, oauth as any, ["flows:read"])).json() as any; const request = (path: string, body: unknown) => protectedApiFetch(new Request(f.env.APP_ORIGIN + path, { method: "POST", headers: { Cookie: f.cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify(body) }), f.env, null, {} as ExecutionContext); const preview = await (await request("/api/v1/oauth/device/preview", { userCode: issued.user_code })).json() as any; expect(preview.clientName).toBe("CLI"); expect(preview.device_code).toBeUndefined(); - const responses = await Promise.all([request("/api/v1/oauth/device/decision", { userCode: issued.user_code, decision: "allow" }), request("/api/v1/oauth/device/decision", { userCode: issued.user_code, decision: "allow" })]); + const responses = await Promise.all([request("/api/v1/oauth/device/decision", { userCode: issued.user_code, signature: preview.signature, decision: "allow" }), request("/api/v1/oauth/device/decision", { userCode: issued.user_code, signature: preview.signature, decision: "allow" })]); expect(responses.map(r => r.status).sort()).toEqual([200, 400]); expect(oauth.completeAuthorization).toHaveBeenCalledTimes(1); const successful = await responses.find(r => r.status === 200)!.json(); expect(successful).toEqual({ status: "approved" }); const row = (await f.db.pool.query("SELECT record FROM app.oauth_device_authorizations WHERE device_code=$1", [issued.device_code])).rows[0]; expect(row.record.authorizationCode).toBe("issued"); expect(row.record.status).toBe("approved"); diff --git a/packages/app/src/features/auth/auth-screen.tsx b/packages/app/src/features/auth/auth-screen.tsx index 499c4ead..c63df028 100644 --- a/packages/app/src/features/auth/auth-screen.tsx +++ b/packages/app/src/features/auth/auth-screen.tsx @@ -1,6 +1,6 @@ import { Button, Input, Label, Page } from "../../shared/ui"; -import { useState, type FormEvent } from "react"; -import { useMutation } from "@tanstack/react-query"; +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"; @@ -11,24 +11,30 @@ const titles: Record = { verify: "Verify your email", "verify-request": "Resend verification email", password: "Change password", }; export function AuthScreen({ mode }: { mode: AuthMode }) { - const search = useSearch({ strict: false }) as { token?: string; returnTo?: string }; + const search = useSearch({ strict: false }) as { token?: string; returnTo?: string; connection?: string; expired?: boolean }; const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [currentPassword, setCurrentPassword] = useState(""); const [notice, setNotice] = useState(""); const resetCompletion = mode === "reset" && Boolean(search.token); + const continuation = useQuery({ + queryKey: ["connection", search.connection], enabled: !!search.connection && !search.token && mode !== "verify", + queryFn: async () => { const { data, error } = await api.POST("/api/v1/auth/connections/resume", { body: { connection: search.connection! } }); if (!data || error) throw new Error(messageOf(error)); return data; }, + retry: false, staleTime: 0, refetchInterval: query => query.state.error ? false : 3000, + }); + useEffect(() => { if (continuation.data?.returnTo) { void refreshIdentity().then(() => window.location.assign(continuation.data!.returnTo!)); } }, [continuation.data]); const mutation = useMutation({ retry: false, mutationFn: async () => { let result; switch (mode) { - case "login": result = await api.POST("/api/v1/auth/login", { body: { email, password, returnTo: search.returnTo } }); break; - case "signup": result = await api.POST("/api/v1/auth/signup", { body: { email, password } }); break; + case "login": result = await api.POST("/api/v1/auth/login", { body: { email, password, returnTo: search.returnTo, connection: search.connection } }); break; + case "signup": result = await api.POST("/api/v1/auth/signup", { body: { email, password, connection: search.connection } }); break; case "reset": result = resetCompletion ? await api.POST("/api/v1/auth/password-reset/complete", { body: { token: search.token!, password } }) - : await api.POST("/api/v1/auth/password-reset/request", { body: { email } }); break; + : await api.POST("/api/v1/auth/password-reset/request", { body: { email, connection: search.connection } }); break; case "verify": result = await api.POST("/api/v1/auth/email-verification/complete", { body: { token: search.token ?? "" } }); break; - case "verify-request": result = await api.POST("/api/v1/auth/email-verification/request", { body: { email } }); break; + case "verify-request": result = await api.POST("/api/v1/auth/email-verification/request", { body: { email, connection: search.connection } }); break; case "password": result = await api.POST("/api/v1/auth/password", { body: { currentPassword, password } }); break; } if (result.error || !result.data) throw new Error(messageOf(result.error)); @@ -36,14 +42,15 @@ export function AuthScreen({ mode }: { mode: AuthMode }) { }, onSuccess: async data => { setPassword(""); setCurrentPassword(""); - if (mode === "login") { + if ("returnTo" in data && typeof data.returnTo === "string") { await refreshIdentity(); - if ("returnTo" in data && typeof data.returnTo === "string") window.location.assign(data.returnTo); + window.location.assign(data.returnTo); } else if (mode === "password" || resetCompletion) { await refreshIdentity(); setNotice("Password updated. Sign in with your new password."); } else if (mode === "verify") { - setNotice("Your email is verified. You can now sign in."); + await refreshIdentity(); + setNotice("Your email is verified and you are signed in. Return to the browser where you started connecting your MCP client; it will continue to the Allow/Deny screen. If the request has expired, start a new connection in your client."); } else { setNotice("If this email can receive the requested link, check your inbox for the next step."); } @@ -56,6 +63,9 @@ export function AuthScreen({ mode }: { mode: AuthMode }) {

Your software factory

{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" &&

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

}
{showEmail && } {mode === "password" && } @@ -65,9 +75,9 @@ export function AuthScreen({ mode }: { mode: AuthMode }) { {notice &&

{notice}

}
); diff --git a/packages/app/src/features/auth/device.tsx b/packages/app/src/features/auth/device.tsx index 10a25e99..cfdb2073 100644 --- a/packages/app/src/features/auth/device.tsx +++ b/packages/app/src/features/auth/device.tsx @@ -5,11 +5,11 @@ import { useQuery, useMutation } from "@tanstack/react-query"; import { api } from "factorize-api-client"; import { messageOf } from "./session"; export function DeviceScreen() { - const search = useSearch({ strict: false }) as { user_code: string }, navigate = useNavigate(), [code, setCode] = useState(search.user_code); + const search = useSearch({ strict: false }) as { user_code: string; connection?: string }, navigate = useNavigate(), [code, setCode] = useState(search.user_code); const preview = useQuery({ queryKey: ["device", search.user_code], enabled: !!search.user_code, queryFn: async ({ signal }) => { const { data, error } = await api.POST("/api/v1/oauth/device/preview", { signal, body: { userCode: search.user_code } }); if (!data || error) throw new Error(messageOf(error)); return data; }, staleTime: 0, retry: false }); - const decision = useMutation({ retry: false, mutationFn: async (value: "allow" | "deny") => { const { data, error } = await api.POST("/api/v1/oauth/device/decision", { body: { userCode: search.user_code, decision: value } }); if (!data || error) throw new Error(messageOf(error)); return data; } }); - return

Connect a device

{decision.data ?

{decision.data.status === "approved" ? "Device connected" : "Authorization denied"}. You can close this window.

: <> -
{ e.preventDefault(); decision.reset(); void navigate({ to: "/device", search: { user_code: code } }); }}>
+ const decision = useMutation({ retry: false, mutationFn: async (value: "allow" | "deny") => { if (!preview.data) throw new Error("Review the device request first."); const { data, error } = await api.POST("/api/v1/oauth/device/decision", { body: { userCode: search.user_code, signature: preview.data!.signature, decision: value } }); if (!data || error) throw new Error(messageOf(error)); return data; } }); + return

Connect a device

Enter the code displayed by your MCP client. Only approve a request you started. If it expires, request a new code in that client.

{decision.data ?

{decision.data.status === "approved" ? "Device connected" : "Authorization denied"}. You can close this window.

: <> +
{ e.preventDefault(); decision.reset(); void navigate({ to: "/device", search: { user_code: code, connection: undefined } }); }}>
{preview.isFetching &&

Validating device code…

}{preview.data && <>

Authorize {preview.data.clientName}

Permissions: {preview.data.scopes.join(", ")} · Expires {preview.data.expiresAt}

} {[preview.error, decision.error].filter(Boolean).map((error, i) =>

{error?.message}

)}}
; diff --git a/packages/app/src/features/auth/protocol-routes.tsx b/packages/app/src/features/auth/protocol-routes.tsx index 5e428149..9e201369 100644 --- a/packages/app/src/features/auth/protocol-routes.tsx +++ b/packages/app/src/features/auth/protocol-routes.tsx @@ -1,8 +1,19 @@ +import { api } from "factorize-api-client"; +import { messageOf } from "./session"; import { createRoute, lazyRouteComponent, redirect, type AnyRootRoute } from "@tanstack/react-router"; import { queryClient } from "../../shared/query-client"; import { sessionQuery } from "./session"; export function protocolRoutes(root: AnyRootRoute) { - const guard = async ({ location }: { location: { href: string } }) => { if (!(await queryClient.ensureQueryData(sessionQuery)).authenticated) throw redirect({ to: "/auth/login", search: { returnTo: location.href, token: undefined } }); }; + const guard = async ({ location }: { location: { href: string; search: Record } }) => { + if ((await queryClient.ensureQueryData(sessionQuery)).authenticated) return; + let connection = typeof location.search.connection === "string" ? location.search.connection : undefined; + if (!connection) { + const { data, error } = await api.POST("/api/v1/auth/connections", { body: { returnTo: location.href } }); + if (!data || error) throw new Error(messageOf(error)); + connection = data.connection; + } + throw redirect({ to: "/auth/login", search: { connection } }); + }; return [createRoute({ getParentRoute: () => root, path: "/authorize", beforeLoad: guard, component: lazyRouteComponent(() => import("./consent"), "ConsentScreen") }), - createRoute({ getParentRoute: () => root, path: "/device", beforeLoad: guard, validateSearch: (s: Record) => ({ user_code: typeof s.user_code === "string" ? s.user_code.slice(0, 32) : "" }), component: lazyRouteComponent(() => import("./device"), "DeviceScreen") })]; + createRoute({ getParentRoute: () => root, path: "/device", beforeLoad: guard, validateSearch: (s: Record) => ({ connection: typeof s.connection === "string" ? s.connection : undefined, user_code: typeof s.user_code === "string" ? s.user_code.slice(0, 32) : "" }), component: lazyRouteComponent(() => import("./device"), "DeviceScreen") })]; } diff --git a/packages/app/src/features/auth/routes.tsx b/packages/app/src/features/auth/routes.tsx index 2de8dfcc..e48fe491 100644 --- a/packages/app/src/features/auth/routes.tsx +++ b/packages/app/src/features/auth/routes.tsx @@ -4,7 +4,9 @@ import { sessionQuery } from "./session"; import { queryClient } from "../../shared/query-client"; const Screen = lazyRouteComponent(() => import("./auth-screen"), "AuthScreen"); -const validateSearch = (input: Record) => ({ +const validateSearch = (input: Record): { token?: string; returnTo?: string; connection?: string; expired?: boolean } => ({ + connection: typeof input.connection === "string" ? input.connection : undefined, + expired: input.expired === "1", token: typeof input.token === "string" ? input.token : undefined, returnTo: typeof input.returnTo === "string" ? input.returnTo : undefined, }); diff --git a/packages/app/test/auth.browser.test.mjs b/packages/app/test/auth.browser.test.mjs index 35aab2a5..4b1e28e1 100644 --- a/packages/app/test/auth.browser.test.mjs +++ b/packages/app/test/auth.browser.test.mjs @@ -138,3 +138,47 @@ test("logout refreshes session identity and removes the account display", async assert.equal(await page.evaluate(() => localStorage.length), 0); await context.close(); }); + +test("MCP onboarding preserves the attempt across account links and resumes automatically after verification elsewhere", async () => { + const context = await browser.newContext(), page = await context.newPage(); + let verified = false, active = false, grants = 0; + const connection = "11111111-1111-4111-8111-111111111111"; + const returnTo = `/authorize?client_id=cli&state=original&connection=${connection}`; + await page.route("**/api/v1/session", route => route.fulfill({ json: active ? { authenticated: true, user: { id: "owner", email: "new@example.test" }, workspace: { id: "workspace", role: "owner" }, capabilities: [] } : { authenticated: false } })); + await page.route("**/api/v1/auth/connections/resume", route => { + assert.equal(route.request().postDataJSON().connection, connection); + if (verified) active = true; + return route.fulfill({ json: verified ? { ok: true, returnTo } : { ok: true, pending: true, clientName: "My MCP CLI" } }); + }); + await page.route("**/api/v1/auth/signup", route => { assert.deepEqual(route.request().postDataJSON(), { email: "new@example.test", password: "long-test-password", connection }); return route.fulfill({ status: 202, json: { ok: true } }); }); + await page.route("**/api/v1/oauth/consent/preview", route => route.fulfill({ json: { clientName: "My MCP CLI", scopes: ["flows:read"], request: "signed", signature: "signature", expiresAt: new Date(Date.now() + 600000).toISOString() } })); + await page.route("**/api/v1/oauth/consent/decision", route => { grants++; assert.equal(route.request().postDataJSON().decision, "allow"); return route.fulfill({ json: { redirectTo: origin + "/completed?code=grant" } }); }); + await page.goto(origin + `/auth/login?connection=${connection}`); + await page.getByRole("link", { name: "Create an account to connect your client" }).click(); + assert.equal(new URL(page.url()).searchParams.get("connection"), connection); + await page.getByRole("link", { name: "Resend verification" }).click(); + assert.equal(new URL(page.url()).searchParams.get("connection"), connection); + await page.goto(origin + `/auth/signup?connection=${connection}`); + await page.getByLabel("Email", { exact: true }).fill("new@example.test"); await page.getByLabel("New password").fill("long-test-password"); + await page.getByRole("button", { name: "Continue" }).click(); await waitText(page, "status", "check your inbox"); + await page.reload(); // Waiting survives refresh, including a verification in a different browser. + verified = true; + await page.getByRole("heading", { name: "Authorize My MCP CLI" }).waitFor(); + assert.equal(grants, 0); assert.equal(new URL(page.url()).searchParams.get("state"), "original"); + await page.getByRole("button", { name: "Allow", exact: true }).click(); await page.waitForURL("**/completed?code=grant"); assert.equal(grants, 1); + await context.close(); +}); + +test("verification automatically signs in and resumes consent, while other-browser verification displays return instructions", async () => { + for (const crossBrowser of [false, true]) { + const { page, context } = await pageFor("/auth/verify?token=one-time&connection=attempt"); + let active = false, verifications = 0; + await page.route("**/api/v1/session", route => route.fulfill({ json: active ? { authenticated: true, user: { id: "owner", email: "new@example.test" }, workspace: { id: "workspace", role: "owner" }, capabilities: [] } : { authenticated: false } })); + await page.route("**/api/v1/auth/email-verification/complete", route => { verifications++; active = true; assert.deepEqual(route.request().postDataJSON(), { token: "one-time" }); return route.fulfill({ json: crossBrowser ? { ok: true, crossBrowser: true } : { ok: true, returnTo: "/authorize?client_id=cli&connection=attempt" } }); }); + await page.route("**/api/v1/oauth/consent/preview", route => route.fulfill({ json: { clientName: "MCP CLI", scopes: [], request: "signed", signature: "signature", expiresAt: new Date(Date.now() + 600000).toISOString() } })); + assert.equal(verifications, 0); await page.getByRole("button", { name: "Verify email" }).click(); + if (crossBrowser) { await waitText(page, "status", "Return to the browser"); assert.equal(new URL(page.url()).pathname, "/auth/verify"); } + else await page.getByRole("heading", { name: "Authorize MCP CLI" }).waitFor(); + assert.equal(verifications, 1); await context.close(); + } +}); diff --git a/packages/app/test/protocol.browser.test.mjs b/packages/app/test/protocol.browser.test.mjs index 2f3a1b18..0a75e00d 100644 --- a/packages/app/test/protocol.browser.test.mjs +++ b/packages/app/test/protocol.browser.test.mjs @@ -16,10 +16,23 @@ test("consent refresh preserves OAuth query, scope selection and server-owned re }); test("device deep link loads metadata and approval sends no protocol tokens", async () => { const { context, page } = await setup(); let decision; - await page.route("**/api/v1/oauth/device/preview", route => route.fulfill({ json: { userCode: "ABCD-EFGH", clientName: "My CLI", scopes: ["flows:read"], expiresAt: "2026-10-09T12:00:00Z" } })); + await page.route("**/api/v1/oauth/device/preview", route => route.fulfill({ json: { userCode: "ABCD-EFGH", clientName: "My CLI", signature: "device-signature", scopes: ["flows:read"], expiresAt: "2026-10-09T12:00:00Z" } })); await page.route("**/api/v1/oauth/device/decision", route => { decision = route.request().postDataJSON(); return route.fulfill({ json: { status: "approved" } }); }); - await page.goto(origin + "/device?user_code=ABCD-EFGH"); await page.getByRole("heading", { name: "Authorize My CLI" }).waitFor(); await page.reload(); await page.getByRole("button", { name: "Allow device" }).click(); await page.getByRole("status").filter({ hasText: "Device connected" }).waitFor(); assert.deepEqual(decision, { userCode: "ABCD-EFGH", decision: "allow" }); await context.close(); + await page.goto(origin + "/device?user_code=ABCD-EFGH"); await page.getByRole("heading", { name: "Authorize My CLI" }).waitFor(); await page.reload(); await page.getByRole("button", { name: "Allow device" }).click(); await page.getByRole("status").filter({ hasText: "Device connected" }).waitFor(); assert.deepEqual(decision, { userCode: "ABCD-EFGH", signature: "device-signature", decision: "allow" }); await context.close(); }); test("expired device authorization is a safe visible error", async () => { const { context, page } = await setup(); await page.route("**/api/v1/oauth/device/preview", route => route.fulfill({ status: 400, json: { error: { code: "invalid_request", message: "Invalid or expired device code." } } })); await page.goto(origin + "/device?user_code=EXPIRED"); await page.getByRole("alert").filter({ hasText: "Invalid or expired device code." }).waitFor(); assert.equal(await page.getByRole("button", { name: "Allow device" }).count(), 0); await context.close(); }); + +test("device code entry recovers from an expired attempt with a new client code and supports explicit denial", async () => { + const { context, page } = await setup(); let decision; + await page.route("**/api/v1/oauth/device/preview", route => route.request().postDataJSON().userCode === "EXPIRED" + ? route.fulfill({ status: 400, json: { error: { code: "invalid_request", message: "Expired code. Request a new code in your client." } } }) + : route.fulfill({ json: { userCode: "ABCD-2345", clientName: "New CLI", signature: "new-signature", scopes: [], expiresAt: new Date(Date.now() + 600000).toISOString() } })); + await page.route("**/api/v1/oauth/device/decision", route => { decision = route.request().postDataJSON(); return route.fulfill({ json: { status: "denied" } }); }); + await page.goto(origin + "/device?user_code=EXPIRED&connection=old-attempt"); await page.getByRole("alert").waitFor(); + await page.getByLabel("Device code").fill("abcd-2345"); await page.getByRole("button", { name: "Continue", exact: true }).click(); + await page.getByRole("heading", { name: "Authorize New CLI" }).waitFor(); assert.equal(new URL(page.url()).searchParams.get("connection"), null); + await page.getByRole("button", { name: "Deny device" }).click(); await page.getByRole("status").filter({ hasText: "Authorization denied" }).waitFor(); + assert.deepEqual(decision, { userCode: "ABCD-2345", signature: "new-signature", decision: "deny" }); await context.close(); +}); diff --git a/packages/app/test/visual/baselines/device-dark-390.png b/packages/app/test/visual/baselines/device-dark-390.png index fb5c30e6..dfb9d66c 100644 Binary files a/packages/app/test/visual/baselines/device-dark-390.png and b/packages/app/test/visual/baselines/device-dark-390.png differ diff --git a/packages/app/test/visual/baselines/device-light-390.png b/packages/app/test/visual/baselines/device-light-390.png index 4e587adb..be5faa7c 100644 Binary files a/packages/app/test/visual/baselines/device-light-390.png and b/packages/app/test/visual/baselines/device-light-390.png differ diff --git a/packages/app/test/visual/baselines/login-dark-1280.png b/packages/app/test/visual/baselines/login-dark-1280.png index d44bc5e2..57973154 100644 Binary files a/packages/app/test/visual/baselines/login-dark-1280.png and b/packages/app/test/visual/baselines/login-dark-1280.png differ diff --git a/packages/app/test/visual/baselines/login-dark-390.png b/packages/app/test/visual/baselines/login-dark-390.png index 569cf232..922fa28d 100644 Binary files a/packages/app/test/visual/baselines/login-dark-390.png and b/packages/app/test/visual/baselines/login-dark-390.png differ diff --git a/packages/app/test/visual/baselines/login-light-1280.png b/packages/app/test/visual/baselines/login-light-1280.png index 6fae9a39..d4754128 100644 Binary files a/packages/app/test/visual/baselines/login-light-1280.png and b/packages/app/test/visual/baselines/login-light-1280.png differ diff --git a/packages/app/test/visual/baselines/login-light-390.png b/packages/app/test/visual/baselines/login-light-390.png index bd714225..d07fafaa 100644 Binary files a/packages/app/test/visual/baselines/login-light-390.png and b/packages/app/test/visual/baselines/login-light-390.png differ diff --git a/packages/docs/api/authentication.mdx b/packages/docs/api/authentication.mdx index 0963a78a..8809eb02 100644 --- a/packages/docs/api/authentication.mdx +++ b/packages/docs/api/authentication.mdx @@ -7,10 +7,18 @@ Protected API and MCP requests use `Authorization: Bearer `. Browser user ## Browser accounts -Create an email/password account at `/auth/signup` and verify the email delivered by Postmark before signing in at `/auth/login`. Recovery is at `/auth/password-reset`; legacy Linear-only users use that flow to choose a password while retaining their workspace. Change your password from the account menu. Resetting/changing passwords or signing out invalidates existing sessions and delegated credentials. +Create an email/password account at `/auth/signup`. Confirm the Postmark verification link to verify your email and sign in automatically. Recovery is at `/auth/password-reset`; legacy Linear-only users use that flow to choose a password while retaining their workspace. Change your password from the account menu. Resetting/changing passwords or signing out invalidates existing sessions and delegated credentials. Linear OAuth is an integration connection available only after native sign-in. Workspace membership, not the connected Linear identity, controls authorization. +## Connecting an MCP client + +Start connecting in your MCP client, then sign in or choose **Create an account**. Signup, resend verification, and password recovery retain an individual server-stored connection, including the client, state, PKCE challenge, and validated callback. Simultaneous attempts have separate browser cookies and cannot overwrite each other. Verification signs you in, then resumes an explicit **Allow / Deny** screen. Verifying an email never grants MCP access or changes existing workspace authorization. + +Callback requests remain active for one hour from initiation; email links expire after one hour and can be used once. If you verify on another browser or device, return to the browser where you started the connection. Its waiting signup screen resumes automatically after verification. The callback is completed there, because local callback listeners and client browser state may belong to that device. The verification browser cannot approve that callback request. Device-flow requests can instead be reviewed and approved in the verification browser. + +An expired or completed request cannot be extended by resending email or recovering a password. Start a new connection in the MCP client; for device flow request a new code. Email verification can still succeed even if its associated client request expired. + ## Scopes | Scope | Allows | @@ -26,8 +34,9 @@ Authorization-code clients must use PKCE S256. Implicit and plain PKCE are disab 1. Register a public client at `POST /oauth/register` with `grant_types` containing `urn:ietf:params:oauth:grant-type:device_code` and `token_endpoint_auth_method: none`. 2. POST form data to `/oauth/device_authorization` with `client_id`, `scope`, and optional `resource`. -3. Send the user to `/device?user_code=...` and poll `/oauth/token` with the device code. +3. Display `user_code` and `verification_uri` (or open `verification_uri_complete`). The user enters the code, signs in or creates an account, verifies email if needed, and explicitly allows or denies the named client. +4. Poll `/oauth/token` with form fields `grant_type=urn:ietf:params:oauth:grant-type:device_code`, `client_id`, and `device_code`. Confidential clients must also authenticate. A successful response contains the usual OAuth tokens; the device code is consumed once. The browser displays completion and can be closed. -Device codes expire after 10 minutes and polling is rate limited. The token endpoint returns `authorization_pending`, `slow_down`, `access_denied`, or `expired_token` as appropriate. +Device codes expire after 10 minutes from issuance, including time spent signing up. Honor the returned `interval` (initially 5 seconds). Each early poll returns `slow_down` and permanently increases that request’s interval by 5 seconds; wait the new interval before polling again. Invalid client authentication never changes another client’s polling schedule. The token endpoint returns `authorization_pending`, `slow_down`, `access_denied`, or `expired_token` as appropriate. Never send Linear, exe.dev, or connection credentials to an API client. Tokens are revocable and responses omit stored secrets. diff --git a/packages/docs/integrations/oauth.mdx b/packages/docs/integrations/oauth.mdx index fb61dfb3..0e0363af 100644 --- a/packages/docs/integrations/oauth.mdx +++ b/packages/docs/integrations/oauth.mdx @@ -3,7 +3,7 @@ title: Connect your accounts description: Browser setup, resource access, and delivery verification. --- -Sign up with email/password, verify email, then open [Settings → Integrations](https://app.factorize.sh/settings). Linear OAuth connects a workspace; it does not sign you in to Factorize. +Factorize accounts own dashboard identity. Sign up with an email and password, verify your email to sign in automatically, then open [Settings → Integrations](https://app.factorize.sh/settings) to connect Linear when using Linear-backed jobs. Linear OAuth only connects the workspace; it never signs you in. Register `/auth/linear/callback`, configure issue and issue-label webhooks at `/webhooks/linear`, and store the client credentials and signing secret as Worker secrets. ClickUp is optional: register `/auth/clickup/callback`; connecting it automatically registers its task webhook. GitHub uses an installed GitHub App, while exe.dev and Cloudflare Tail connections are configured in Settings. | Account | Browser action and required access | Verification | | --- | --- | --- | diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index ee6bf20b..7d5d3f3e 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -265,7 +265,7 @@ Available states are `succeeded`, `failed`, `stopped`, and `edited`. **Edited** ## Connect your accounts Source: https://docs.factorize.sh/integrations/oauth -Sign up with email/password, verify email, then open [Settings → Integrations](https://app.factorize.sh/settings). Linear OAuth connects a workspace; it does not sign you in to Factorize. +Factorize accounts own dashboard identity. Sign up with an email and password, verify your email to sign in automatically, then open [Settings → Integrations](https://app.factorize.sh/settings) to connect Linear when using Linear-backed jobs. Linear OAuth only connects the workspace; it never signs you in. Register `/auth/linear/callback`, configure issue and issue-label webhooks at `/webhooks/linear`, and store the client credentials and signing secret as Worker secrets. ClickUp is optional: register `/auth/clickup/callback`; connecting it automatically registers its task webhook. GitHub uses an installed GitHub App, while exe.dev and Cloudflare Tail connections are configured in Settings. | Account | Browser action and required access | Verification | | --- | --- | --- | @@ -583,10 +583,18 @@ Protected API and MCP requests use `Authorization: Bearer `. Browser user ## Browser accounts -Create an email/password account at `/auth/signup` and verify the email delivered by Postmark before signing in at `/auth/login`. Recovery is at `/auth/password-reset`; legacy Linear-only users use that flow to choose a password while retaining their workspace. Change your password from the account menu. Resetting/changing passwords or signing out invalidates existing sessions and delegated credentials. +Create an email/password account at `/auth/signup`. Confirm the Postmark verification link to verify your email and sign in automatically. Recovery is at `/auth/password-reset`; legacy Linear-only users use that flow to choose a password while retaining their workspace. Change your password from the account menu. Resetting/changing passwords or signing out invalidates existing sessions and delegated credentials. Linear OAuth is an integration connection available only after native sign-in. Workspace membership, not the connected Linear identity, controls authorization. +## Connecting an MCP client + +Start connecting in your MCP client, then sign in or choose **Create an account**. Signup, resend verification, and password recovery retain an individual server-stored connection, including the client, state, PKCE challenge, and validated callback. Simultaneous attempts have separate browser cookies and cannot overwrite each other. Verification signs you in, then resumes an explicit **Allow / Deny** screen. Verifying an email never grants MCP access or changes existing workspace authorization. + +Callback requests remain active for one hour from initiation; email links expire after one hour and can be used once. If you verify on another browser or device, return to the browser where you started the connection. Its waiting signup screen resumes automatically after verification. The callback is completed there, because local callback listeners and client browser state may belong to that device. The verification browser cannot approve that callback request. Device-flow requests can instead be reviewed and approved in the verification browser. + +An expired or completed request cannot be extended by resending email or recovering a password. Start a new connection in the MCP client; for device flow request a new code. Email verification can still succeed even if its associated client request expired. + ## Scopes | Scope | Allows | @@ -602,9 +610,10 @@ Authorization-code clients must use PKCE S256. Implicit and plain PKCE are disab 1. Register a public client at `POST /oauth/register` with `grant_types` containing `urn:ietf:params:oauth:grant-type:device_code` and `token_endpoint_auth_method: none`. 2. POST form data to `/oauth/device_authorization` with `client_id`, `scope`, and optional `resource`. -3. Send the user to `/device?user_code=...` and poll `/oauth/token` with the device code. +3. Display `user_code` and `verification_uri` (or open `verification_uri_complete`). The user enters the code, signs in or creates an account, verifies email if needed, and explicitly allows or denies the named client. +4. Poll `/oauth/token` with form fields `grant_type=urn:ietf:params:oauth:grant-type:device_code`, `client_id`, and `device_code`. Confidential clients must also authenticate. A successful response contains the usual OAuth tokens; the device code is consumed once. The browser displays completion and can be closed. -Device codes expire after 10 minutes and polling is rate limited. The token endpoint returns `authorization_pending`, `slow_down`, `access_denied`, or `expired_token` as appropriate. +Device codes expire after 10 minutes from issuance, including time spent signing up. Honor the returned `interval` (initially 5 seconds). Each early poll returns `slow_down` and permanently increases that request’s interval by 5 seconds; wait the new interval before polling again. Invalid client authentication never changes another client’s polling schedule. The token endpoint returns `authorization_pending`, `slow_down`, `access_denied`, or `expired_token` as appropriate. Never send Linear, exe.dev, or connection credentials to an API client. Tokens are revocable and responses omit stored secrets. diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 560ab5ad..56ca36f1 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -1157,6 +1157,161 @@ components: schema: $ref: "#/components/schemas/Error" paths: + /api/v1/auth/connections: + post: + summary: Persist an individual validated MCP connection; sets a per-attempt browser cookie + description: Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + responses: + "200": + description: Success + headers: + X-Factorize-Webhook-Conditions: + description: Conditions-only webhook runtime deployment marker. + schema: + type: string + const: v1 + X-Factorize-Contract: + description: Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. + schema: + type: string + const: gen-2157-static-v1 + content: + application/json: + schema: + type: object + properties: + connection: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + clientName: + type: string + expiresAt: + type: string + format: date-time + pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z))$ + required: + - connection + - clientName + - expiresAt + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_auth_connections + tags: + - auth + security: [] + x-browser-auth-operation: connection-start + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + returnTo: + type: string + minLength: 1 + maxLength: 8192 + required: + - returnTo + additionalProperties: false + /api/v1/auth/connections/resume: + post: + summary: Resume verified onboarding in the initiating browser; never grants OAuth access + description: Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + responses: + "200": + description: Success + headers: + X-Factorize-Webhook-Conditions: + description: Conditions-only webhook runtime deployment marker. + schema: + type: string + const: v1 + X-Factorize-Contract: + description: Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. + schema: + type: string + const: gen-2157-static-v1 + content: + application/json: + schema: + type: object + properties: + ok: + type: boolean + const: true + returnTo: + type: string + crossBrowser: + type: boolean + pending: + type: boolean + clientName: + type: string + expiresAt: + type: string + format: date-time + pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z))$ + required: + - ok + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: post_api_v1_auth_connections_resume + tags: + - auth + security: [] + x-browser-auth-operation: connection-resume + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + connection: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + required: + - connection + additionalProperties: false /api/v1/session: get: summary: Get current browser session @@ -1339,7 +1494,11 @@ paths: writeOnly: true returnTo: type: string - maxLength: 4096 + maxLength: 8192 + connection: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ required: - email - password @@ -1414,6 +1573,10 @@ paths: minLength: 12 maxLength: 200 writeOnly: true + connection: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ required: - email - password @@ -1483,12 +1646,16 @@ paths: maxLength: 320 format: email pattern: ^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$ + connection: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ required: - email additionalProperties: false /api/v1/auth/email-verification/complete: post: - summary: Complete email verification + summary: Verify email, establish an owner session, and resume explicit consent; callbacks stay in the initiating browser description: Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. responses: "200": @@ -1512,6 +1679,18 @@ paths: ok: type: boolean const: true + returnTo: + type: string + crossBrowser: + type: boolean + pending: + type: boolean + clientName: + type: string + expiresAt: + type: string + format: date-time + pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z))$ required: - ok additionalProperties: false @@ -1619,12 +1798,16 @@ paths: maxLength: 320 format: email pattern: ^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$ + connection: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ required: - email additionalProperties: false /api/v1/auth/password-reset/complete: post: - summary: Complete password reset + summary: Complete password reset and resume onboarding description: Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. responses: "200": @@ -1648,6 +1831,18 @@ paths: ok: type: boolean const: true + returnTo: + type: string + crossBrowser: + type: boolean + pending: + type: boolean + clientName: + type: string + expiresAt: + type: string + format: date-time + pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z))$ required: - ok additionalProperties: false @@ -1843,11 +2038,14 @@ paths: type: string expiresAt: type: string + signature: + type: string required: - userCode - clientName - scopes - expiresAt + - signature additionalProperties: false "400": $ref: "#/components/responses/Error400" @@ -1945,6 +2143,10 @@ paths: type: string minLength: 1 maxLength: 32 + signature: + type: string + minLength: 1 + maxLength: 256 decision: type: string enum: @@ -1952,6 +2154,7 @@ paths: - deny required: - userCode + - signature - decision additionalProperties: false /api/v1/oauth/consent/preview: diff --git a/scripts/hosting-runtime.test.mjs b/scripts/hosting-runtime.test.mjs index bcff75e4..686ce27f 100644 --- a/scripts/hosting-runtime.test.mjs +++ b/scripts/hosting-runtime.test.mjs @@ -3,6 +3,9 @@ import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { createServer } from "node:net"; import https from "node:https"; +import pg from "pg"; +import { randomUUID } from "node:crypto"; +import { readdir, readFile } from "node:fs/promises"; function read(port, path, method = "GET", headers = {}) { return new Promise((resolve, reject) => { @@ -17,6 +20,15 @@ test("actual Cloudflare local runtime enforces static/API/protocol ownership, he const socket = createServer(); await new Promise(resolve => socket.listen(0, "127.0.0.1", resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve)); const databaseUrl = new URL(process.env.AUTH_TEST_DATABASE_URL ?? "postgresql://postgres@localhost/factorize_test"); if (!databaseUrl.password) databaseUrl.password = "local-runtime-only"; + let admin, databaseName; + if (process.env.AUTH_TEST_DATABASE_URL) { + admin = new pg.Client({ connectionString: databaseUrl.href }); await admin.connect(); + databaseName = "hosting_test_" + randomUUID().replaceAll("-", ""); + await admin.query(`CREATE DATABASE "${databaseName}"`); databaseUrl.pathname = "/" + databaseName; + const migrated = new pg.Client({ connectionString: databaseUrl.href }); await migrated.connect(); + try { for (const file of (await readdir("packages/api/migrations")).filter(file => file.endsWith(".sql")).sort()) await migrated.query(await readFile("packages/api/migrations/" + file, "utf8")); } + finally { await migrated.end(); } + } const database = databaseUrl.href; assert.ok(["localhost", "127.0.0.1"].includes(new URL(database).hostname), "Hosting runtime requires a local database URL"); const child = spawn("npm", ["exec", "--workspace=factorize", "--", "wrangler", "dev", "--local", "--local-protocol", "https", "--port", String(port), "--var", `APP_ORIGIN:https://localhost:${port}`], { env: { ...process.env, CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE: database }, detached: true, stdio: ["ignore", "pipe", "pipe"] }); @@ -39,10 +51,12 @@ test("actual Cloudflare local runtime enforces static/API/protocol ownership, he for (const [path, method, expected] of [["/api/v1/unknown", "GET", 401], ["/api/v1/jobs", "PATCH", 401], ["/oauth/unknown", "GET", 404], ["/auth/unknown", "GET", 404], ["/internal/unknown", "GET", 404], ["/webhooks/unknown", "GET", 404], ["/mcp", "GET", 401], ["/unknown", "GET", 404], ["/assets/missing.js", "GET", 404], ["/jobs", "POST", 404], ["/auth/logout", "GET", 404]]) { const result = await read(port, path, method); assert.equal(result.status, expected, path); assert.ok(!result.headers["content-type"]?.includes("text/html"), path); assert.equal(result.headers["cache-control"], "no-store", path); } - for (const path of ["/authorize?client_id=client", "/device?user_code=ABCD-2345"]) { const result = await read(port, path); assert.equal(result.status, 302); assert.equal(result.headers.location, `https://localhost:${port}/auth/login`); assert.ok(result.headers["set-cookie"].some(cookie => cookie.startsWith("factorize_oauth_return="))); } + // Unknown protocol requests fail validation before onboarding; they cannot become return cookies. + for (const path of ["/authorize?client_id=client", ...(admin ? ["/device?user_code=ABCD-2345"] : [])]) { const result = await read(port, path); assert.equal(result.status, 400, path + ": " + result.body); assert.equal(result.headers["set-cookie"], undefined); } const csrf = await read(port, "/api/v1/auth/login", "POST", { Origin: "https://untrusted.test", "Content-Type": "application/json" }); assert.equal(csrf.status, 403); const metadata = await read(port, "/.well-known/oauth-authorization-server"); assert.equal(metadata.status, 200); assert.equal(JSON.parse(metadata.body).issuer, `https://localhost:${port}`); assert.equal(JSON.parse(metadata.body).device_authorization_endpoint, `https://localhost:${port}/oauth/device_authorization`); } finally { try { process.kill(-child.pid, "SIGTERM"); } catch (error) { if (error.code !== "ESRCH") throw error; } await new Promise(resolve => { if (child.exitCode !== null || child.signalCode !== null) resolve(); else child.once("exit", resolve); }); + if (admin) { await admin.query(`DROP DATABASE IF EXISTS "${databaseName}" WITH (FORCE)`); await admin.end(); } } }); diff --git a/scripts/oauth-runtime.test.mjs b/scripts/oauth-runtime.test.mjs index 0b8c2158..c93bd020 100644 --- a/scripts/oauth-runtime.test.mjs +++ b/scripts/oauth-runtime.test.mjs @@ -48,7 +48,9 @@ test('local OAuth consent and device grants authorize REST/MCP and respect revoc assert.equal(registration.status, 201, registration.text); const clientId = registration.json.client_id; const verifier = randomBytes(32).toString('base64url'), challenge = createHash('sha256').update(verifier).digest('base64url'); const authorizationQuery = new URLSearchParams({ response_type: 'code', client_id: clientId, redirect_uri: 'http://127.0.0.1/callback', scope: 'flows:read', state: 'fixture-state', code_challenge: challenge, code_challenge_method: 'S256', resource: origin+'/mcp' }).toString(); - const screen = await send('/authorize?'+authorizationQuery, 'GET', undefined, owner); assert.equal(screen.status, 200); assert.match(screen.text, /\/assets\//); + const screen = await send('/authorize?'+authorizationQuery, 'GET', undefined, owner); assert.equal(screen.status, 302); + const connectionCookie = screen.headers['set-cookie'][0].split(';')[0]; + const connectedScreen = await send(new URL(screen.headers.location).pathname + new URL(screen.headers.location).search, 'GET', undefined, { ...owner, Cookie: cookie + '; ' + connectionCookie }); assert.equal(connectedScreen.status, 200); assert.match(connectedScreen.text, /\/assets\//); const preview = await json('/api/v1/oauth/consent/preview', { authorizationQuery }, owner); assert.equal(preview.status, 200, preview.text); const decision = { request: preview.json.request, signature: preview.json.signature, decision: 'allow', scopes: ['flows:read'] }; assert.equal((await json('/api/v1/oauth/consent/decision', decision, { ...owner, Origin: 'https://evil.test' })).status, 403); @@ -76,8 +78,10 @@ test('local OAuth consent and device grants authorize REST/MCP and respect revoc const device = await form('/oauth/device_authorization', { client_id: deviceClient.json.client_id, scope: 'flows:read', resource: origin+'/mcp' }); assert.equal(device.status, 200, device.text); const poll = { grant_type: 'urn:ietf:params:oauth:grant-type:device_code', client_id: deviceClient.json.client_id, device_code: device.json.device_code }; assert.equal((await form('/oauth/token', poll)).json.error, 'authorization_pending'); - assert.equal((await json('/api/v1/oauth/device/preview', { userCode: device.json.user_code }, owner)).status, 200); - const approval = await json('/api/v1/oauth/device/decision', { userCode: device.json.user_code, decision: 'allow' }, owner); assert.equal(approval.status, 200, approval.text); + const devicePreview = await json('/api/v1/oauth/device/preview', { userCode: device.json.user_code }, owner); assert.equal(devicePreview.status, 200); + const approval = await json('/api/v1/oauth/device/decision', { userCode: device.json.user_code, signature: devicePreview.json.signature, decision: 'allow' }, owner); assert.equal(approval.status, 200, approval.text); + assert.equal((await form('/oauth/token', poll)).json.error, 'slow_down'); + await db.query("UPDATE app.oauth_device_authorizations SET record=jsonb_set(record,'{lastPolledAt}',to_jsonb(extract(epoch from now())::bigint-20)) WHERE device_code=$1", [device.json.device_code]); const deviceToken = await form('/oauth/token', poll); assert.equal(deviceToken.status, 200, deviceToken.text); assert.deepEqual((await rpc('tools/call', { name: 'list_jobs', arguments: {} }, 6, { Authorization: 'Bearer '+deviceToken.json.access_token })).result.structuredContent.items, []); assert.equal((await form('/oauth/token', poll)).json.error, 'expired_token');