From e1c9562da42ac2cb6f351ceb1cb10c42d2fac473 Mon Sep 17 00:00:00 2001 From: Brendan Date: Mon, 14 Sep 2026 14:11:31 +0000 Subject: [PATCH] Support OAuth device authorization --- README.md | 4 +- src/device-oauth.ts | 239 ++++++++++++++++++++++++++++++++++++++ src/index.ts | 2 +- src/worker.ts | 26 ++++- test/device-oauth.test.ts | 99 ++++++++++++++++ 5 files changed, 363 insertions(+), 7 deletions(-) create mode 100644 src/device-oauth.ts create mode 100644 test/device-oauth.test.ts diff --git a/README.md b/README.md index 74540d27..a3d661fb 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ GitHub Actions runs `npm run check` on every push and pull request. ## REST API and OAuth -API clients use OAuth 2.1 authorization code flow with PKCE S256. Factorize publishes authorization-server and protected-resource discovery metadata, supports Client ID Metadata Documents, and retains dynamic client registration at `/oauth/register` for older clients. Access tokens last one hour and may be refreshed for up to 30 days; RFC 7009 revocation is advertised by discovery metadata. +API clients use OAuth 2.1 authorization code flow with PKCE S256 or the OAuth 2.0 Device Authorization Grant for headless environments. Factorize publishes authorization-server and protected-resource discovery metadata, supports Client ID Metadata Documents, and retains dynamic client registration at `/oauth/register` for older clients. Access tokens last one hour and may be refreshed for up to 30 days; RFC 7009 revocation is advertised by discovery metadata. Available scopes are `flows:read`, `flows:write`, `runs:read`, and `runs:write`. The resource owner must sign in through the normal Linear-backed Factorize session and explicitly approve the requested scopes. Factorize rechecks owner membership and session version on every service call. @@ -157,6 +157,8 @@ https://app.factorize.sh/mcp The client discovers OAuth automatically, opens Factorize in a browser, completes Linear sign-in if necessary, requests consent, and returns to the client after PKCE authorization. No Linear or exe.dev credential is copied into the MCP client. The server is stateless Streamable HTTP and exposes flow CRUD, projects/options, run inspection/filtering, webhook activity, and active-run stopping tools. +Factorize also supports the OAuth 2.0 Device Authorization Grant (RFC 8628) for headless clients. Discovery advertises `device_authorization_endpoint`; clients obtain a code from `POST /oauth/device_authorization`, direct the user to `/device`, and poll `/oauth/token` with grant type `urn:ietf:params:oauth:grant-type:device_code`. Device codes expire after ten minutes, polling is rate-limited, and approved grants use the same scoped access and refresh tokens, tenant checks, and revocation behavior as browser PKCE authorization. + ## Security - Linear and exe.dev credentials, issue prompts, and agent results are AES-GCM encrypted at rest in the Durable Object. diff --git a/src/device-oauth.ts b/src/device-oauth.ts new file mode 100644 index 00000000..5edc7906 --- /dev/null +++ b/src/device-oauth.ts @@ -0,0 +1,239 @@ +import type { AuthRequest } from "@cloudflare/workers-oauth-provider"; +import { hmac } from "./crypto"; +import type { Env, OAuthProps } from "./types"; + +export const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"; +const DEVICE_TTL = 600; +const DEFAULT_INTERVAL = 5; +const alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; + +type OAuthClient = { clientId: string; clientName?: string; redirectUris: string[]; tokenEndpointAuthMethod?: string }; +type OAuthHelpers = { + lookupClient(clientId: string): Promise; + completeAuthorization(options: { request: AuthRequest; userId: string; metadata: unknown; scope: string[]; props: OAuthProps; revokeExistingGrants?: boolean }): Promise<{ redirectTo: string }>; +}; +type DeviceStatus = "pending" | "approved" | "denied"; +type DeviceRecord = { + clientId: string; + clientName: string; + tokenEndpointAuthMethod: string; + scope: string[]; + resource: string; + redirectUri: string; + codeChallenge: string; + createdAt: number; + expiresAt: number; + interval: number; + lastPolledAt?: number; + status: DeviceStatus; + authorizationCode?: string; +}; + +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); +const random = (bytes = 32) => { + const value = crypto.getRandomValues(new Uint8Array(bytes)); + return btoa(String.fromCharCode(...value)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +}; +const normalizeUserCode = (value: string) => value.toUpperCase().replace(/[^A-Z0-9]/g, ""); +const displayUserCode = (value: string) => `${value.slice(0, 4)}-${value.slice(4)}`; +const deviceKey = (code: string) => `device:${code}`; +const userKey = (code: string) => `device-user:${normalizeUserCode(code)}`; +const verifier = (deviceCode: string, secret: string) => hmac(`device-code:${deviceCode}`, secret); +async function challenge(value: string): Promise { + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))); + return btoa(String.fromCharCode(...digest)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +} +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 { + 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); + return difference === 0; +} +function basicCredentials(request: Request): { clientId: string; clientSecret: string } | null { + const header = request.headers.get("Authorization"); + if (!header?.toLowerCase().startsWith("basic ")) return null; + try { + const decoded = atob(header.slice(6).trim()); + const separator = decoded.indexOf(":"); + if (separator < 0) return null; + return { clientId: decodeURIComponent(decoded.slice(0, separator)), clientSecret: decodeURIComponent(decoded.slice(separator + 1)) }; + } catch { return null; } +} +async function authenticateDeviceClient(request: Request, env: Env, form: FormData, client: OAuthClient): Promise { + if ((client.tokenEndpointAuthMethod ?? "none") === "none") return true; + const basic = basicCredentials(request); + const clientId = basic?.clientId ?? String(form.get("client_id") ?? ""); + const clientSecret = basic?.clientSecret ?? String(form.get("client_secret") ?? ""); + if (clientId !== client.clientId || !clientSecret || !env.OAUTH_KV) return false; + const stored = await env.OAUTH_KV.get<{ clientSecret?: string }>(`client:${client.clientId}`, "json"); + return Boolean(stored?.clientSecret && safeEqual(await sha256Hex(clientSecret), stored.clientSecret)); +} +async function readDevice(env: Env, code: string): Promise { + return env.OAUTH_KV?.get(deviceKey(code), "json") ?? null; +} + +export async function deviceAuthorization(request: Request, env: Env, oauth: OAuthHelpers, supportedScopes: string[]): Promise { + if (request.method !== "POST") return new Response("Method not allowed", { status: 405, headers: { Allow: "POST" } }); + if (!env.OAUTH_KV) return oauthError("server_error", "OAuth storage is unavailable.", 500); + const form = await request.formData(); + const basic = basicCredentials(request); + const clientId = basic?.clientId ?? String(form.get("client_id") ?? ""); + if (!clientId) return oauthError("invalid_request", "client_id is required."); + const client = await oauth.lookupClient(clientId); + if (!client) return oauthError("invalid_client", "The OAuth client is unknown.", 401); + if (!await authenticateDeviceClient(request, env, form, client)) return oauthError("invalid_client", "Client authentication failed.", 401); + if (!client.redirectUris.length) return oauthError("unauthorized_client", "The client must have a registered redirect URI."); + const requested = String(form.get("scope") ?? "").split(/\s+/).filter(Boolean); + const invalidScope = requested.find(value => !supportedScopes.includes(value)); + if (invalidScope) return oauthError("invalid_scope", `Unsupported scope: ${invalidScope}`); + const resource = String(form.get("resource") ?? `${env.APP_ORIGIN}/mcp`); + if (resource !== `${env.APP_ORIGIN}/mcp`) return oauthError("invalid_target", "The resource must be the Factorize MCP endpoint."); + + const deviceCode = random(); + const codeVerifier = await verifier(deviceCode, env.SESSION_SIGNING_SECRET); + let compactUserCode = ""; + for (let attempt = 0; attempt < 8; attempt++) { + compactUserCode = Array.from(crypto.getRandomValues(new Uint8Array(8)), value => alphabet[value % alphabet.length]).join(""); + if (!await env.OAUTH_KV.get(userKey(compactUserCode))) break; + compactUserCode = ""; + } + if (!compactUserCode) return oauthError("server_error", "Could not allocate a user code.", 500); + const now = Math.floor(Date.now() / 1000); + const record: DeviceRecord = { + clientId, clientName: client.clientName ?? "this client", tokenEndpointAuthMethod: client.tokenEndpointAuthMethod ?? "none", scope: requested, resource, + redirectUri: client.redirectUris[0], codeChallenge: await challenge(codeVerifier), + createdAt: now, expiresAt: now + DEVICE_TTL, interval: DEFAULT_INTERVAL, status: "pending", + }; + await Promise.all([ + env.OAUTH_KV.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: DEVICE_TTL }), + env.OAUTH_KV.put(userKey(compactUserCode), deviceCode, { expirationTtl: DEVICE_TTL }), + ]); + const verificationUri = `${env.APP_ORIGIN}/device`; + const userCode = displayUserCode(compactUserCode); + return json({ + device_code: deviceCode, + user_code: userCode, + verification_uri: verificationUri, + verification_uri_complete: `${verificationUri}?user_code=${encodeURIComponent(userCode)}`, + expires_in: DEVICE_TTL, + interval: DEFAULT_INTERVAL, + }); +} + +export async function deviceToken(request: Request, env: Env, oauthProvider: { fetch(request: Request, env: Env, ctx: ExecutionContext): Promise }, ctx: ExecutionContext): Promise { + if (!env.OAUTH_KV) return oauthError("server_error", "OAuth storage is unavailable.", 500); + const form = await request.formData(); + const deviceCode = String(form.get("device_code") ?? ""); + 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") { + if (record.lastPolledAt && now - record.lastPolledAt < record.interval) { + record.interval += 5; + record.lastPolledAt = now; + await env.OAUTH_KV.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: Math.max(1, record.expiresAt - now) }); + return oauthError("slow_down", "Polling is too frequent."); + } + record.lastPolledAt = now; + await env.OAUTH_KV.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: Math.max(1, record.expiresAt - now) }); + 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) await env.OAUTH_KV.delete(deviceKey(deviceCode)); + return response; +} + +export async function deviceVerification(request: Request, env: Env, oauth: OAuthHelpers, session: { tenantId: string; userId: string; email: string; sessionVersion: number }): Promise { + if (!env.OAUTH_KV) return new Response("OAuth storage is unavailable", { status: 500 }); + const url = new URL(request.url); + const form = request.method === "POST" ? await request.formData() : null; + const suppliedCode = String(form?.get("user_code") ?? url.searchParams.get("user_code") ?? ""); + const normalized = normalizeUserCode(suppliedCode); + const deviceCode = normalized.length === 8 ? await env.OAUTH_KV.get(userKey(normalized)) : null; + const record = deviceCode ? await readDevice(env, deviceCode) : null; + const valid = record && record.status === "pending" && record.expiresAt > Math.floor(Date.now() / 1000); + if (request.method === "GET") { + const detail = valid ? `

Authorize ${escapeHtml(record.clientName)}

Signed in as ${escapeHtml(session.email)}.

This client is requesting: ${record.scope.length ? record.scope.map(escapeHtml).join(", ") : "basic access"}.

` : `

Connect a device

Enter the code shown by your application.

`; + return new Response(`Connect a device — Factorize
${detail}

${valid ? ` ` : ``}

`, { headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" } }); + } + if (request.method !== "POST") return new Response("Method not allowed", { status: 405, headers: { Allow: "GET, POST" } }); + if (!valid || !deviceCode || !record) return new Response("Invalid or expired device code", { status: 400 }); + if (form?.get("decision") === "deny") { + record.status = "denied"; + await Promise.all([env.OAUTH_KV.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: Math.max(1, record.expiresAt - Math.floor(Date.now() / 1000)) }), env.OAUTH_KV.delete(userKey(normalized))]); + return confirmation("Authorization denied", "You can close this window."); + } + if (form?.get("decision") !== "allow") return Response.redirect(`${env.APP_ORIGIN}/device?user_code=${encodeURIComponent(displayUserCode(normalized))}`, 303); + const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: record.scope }; + const authRequest: AuthRequest = { responseType: "code", clientId: record.clientId, redirectUri: record.redirectUri, scope: record.scope, state: "", codeChallenge: record.codeChallenge, codeChallengeMethod: "S256", resource: record.resource, issuer: env.APP_ORIGIN }; + const result = await oauth.completeAuthorization({ request: authRequest, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: record.scope, props, revokeExistingGrants: false }); + record.status = "approved"; + record.authorizationCode = new URL(result.redirectTo).searchParams.get("code") ?? undefined; + if (!record.authorizationCode) return new Response("Could not complete device authorization", { status: 500 }); + await Promise.all([env.OAUTH_KV.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: Math.max(1, record.expiresAt - Math.floor(Date.now() / 1000)) }), env.OAUTH_KV.delete(userKey(normalized))]); + return confirmation("Device connected", "Authorization is complete. You can close this window."); +} + +export async function addDeviceMetadata(response: Response, appOrigin: string): Promise { + if (!response.ok) return response; + const metadata = await response.json() as Record; + metadata.device_authorization_endpoint = `${appOrigin}/oauth/device_authorization`; + const grants = Array.isArray(metadata.grant_types_supported) ? metadata.grant_types_supported as string[] : []; + metadata.grant_types_supported = [...new Set([...grants, DEVICE_GRANT])]; + return json(metadata); +} + +export async function deviceClientRegistration(request: Request, env: Env, oauthProvider: { fetch(request: Request, env: Env, ctx: ExecutionContext): Promise }, ctx: ExecutionContext): Promise { + if (request.method !== "POST" || !request.headers.get("Content-Type")?.toLowerCase().includes("application/json")) return oauthProvider.fetch(request, env, ctx); + let registration: Record; + try { registration = await request.clone().json() as Record; } + catch { return oauthProvider.fetch(request, env, ctx); } + const grants = Array.isArray(registration.grant_types) ? registration.grant_types.map(String) : []; + if (!grants.includes(DEVICE_GRANT)) return oauthProvider.fetch(request, env, ctx); + const originallyHadAuthorizationCode = grants.includes("authorization_code"); + const originalRedirectUris = Array.isArray(registration.redirect_uris) ? registration.redirect_uris.map(String) : []; + const translated = { + ...registration, + grant_types: [...new Set([...grants.filter(value => value !== DEVICE_GRANT), "authorization_code"])], + response_types: [...new Set([...(Array.isArray(registration.response_types) ? registration.response_types.map(String) : []), "code"])], + redirect_uris: originalRedirectUris.length ? originalRedirectUris : [`${env.APP_ORIGIN}/oauth/device/callback`], + }; + const headers = new Headers(request.headers); + headers.set("Content-Type", "application/json"); + const response = await oauthProvider.fetch(new Request(request.url, { method: "POST", headers, body: JSON.stringify(translated) }), env, ctx); + if (!response.ok) return response; + const result = await response.json() as Record; + const returnedGrants = Array.isArray(result.grant_types) ? result.grant_types.map(String) : []; + result.grant_types = [...new Set([...returnedGrants.filter(value => originallyHadAuthorizationCode || value !== "authorization_code"), DEVICE_GRANT])]; + if (!originallyHadAuthorizationCode) result.response_types = []; + result.redirect_uris = originalRedirectUris; + return json(result, response.status); +} + +function escapeHtml(value: string): string { return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """); } +function confirmation(title: string, message: string): Response { + return new Response(`${escapeHtml(title)} — Factorize

${escapeHtml(title)}

${escapeHtml(message)}

`, { headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" } }); +} diff --git a/src/index.ts b/src/index.ts index be2c439a..f83dc3f9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -88,7 +88,7 @@ app.get("/auth/linear/callback", async (c) => { const lifetime = 60 * 60 * 24 * 7; setCookie(c, "factorize_session", await signSession({ tenantId: organization.id, userId: viewer.id, email: viewer.email, exp: Math.floor(Date.now() / 1000) + lifetime, sessionVersion: member.session_version }, c.env.SESSION_SIGNING_SECRET), { httpOnly: true, secure: new URL(c.env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/", maxAge: lifetime }); const oauthReturn = getCookie(c, "factorize_oauth_return"); - if (oauthReturn?.startsWith("/authorize?")) { deleteCookie(c, "factorize_oauth_return", { path: "/" }); return c.redirect(oauthReturn); } + if (oauthReturn?.startsWith("/authorize?") || oauthReturn?.startsWith("/device")) { deleteCookie(c, "factorize_oauth_return", { path: "/" }); return c.redirect(oauthReturn); } return c.redirect("/flows/new"); }); diff --git a/src/worker.ts b/src/worker.ts index 47d4c3c7..adcbe84a 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -1,7 +1,8 @@ -import { OAuthProvider, AuthorizationError, type AuthRequest } from "@cloudflare/workers-oauth-provider"; +import { OAuthProvider, AuthorizationError, getOAuthApi, type AuthRequest, type OAuthProviderOptions } from "@cloudflare/workers-oauth-provider"; import app, { readSession } from "./index"; import { ProtectedApiHandler } from "./protected-api"; import { hmac } from "./crypto"; +import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceToken, deviceVerification } from "./device-oauth"; import type { Env, OAuthProps } from "./types"; const scopes = ["flows:read", "flows:write", "runs:read", "runs:write"]; @@ -31,7 +32,7 @@ function oauthError(error: AuthorizationError): Response { const defaultHandler: ExportedHandler = { async fetch(request, env, ctx) { const url = new URL(request.url); - if (url.pathname !== "/authorize") return app.fetch(request, env, ctx); + if (url.pathname !== "/authorize" && url.pathname !== "/device") return app.fetch(request, env, ctx); try { const session = await currentOwner(request, env); if (!session) { @@ -39,6 +40,7 @@ const defaultHandler: ExportedHandler = { response.headers.append("Set-Cookie", `factorize_oauth_return=${encodeURIComponent(url.pathname + url.search)}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=600`); return response; } + if (url.pathname === "/device") return deviceVerification(request, env, env.OAUTH_PROVIDER!, session); if (request.method === "GET") { const parsed = await env.OAUTH_PROVIDER!.parseAuthRequest(request); const client = await env.OAUTH_PROVIDER!.lookupClient(parsed.clientId); @@ -64,14 +66,28 @@ const defaultHandler: ExportedHandler = { }, }; -function provider(env: Env) { return new OAuthProvider({ +function providerOptions(env: Env): OAuthProviderOptions { return { apiRoute: ["/api/v1", "/mcp"], apiHandler: ProtectedApiHandler, defaultHandler, authorizeEndpoint: "/authorize", tokenEndpoint: "/oauth/token", clientRegistrationEndpoint: "/oauth/register", scopesSupported: scopes, allowImplicitFlow: false, allowPlainPKCE: false, accessTokenTTL: 3600, refreshTokenTTL: 2_592_000, clientIdMetadataDocumentEnabled: true, resourceMetadata: { resource: `${env.APP_ORIGIN}/mcp`, authorization_servers: [env.APP_ORIGIN], scopes_supported: scopes, bearer_methods_supported: ["header"], resource_name: "Factorize flows" }, -}); } +}; } +function provider(env: Env) { return new OAuthProvider(providerOptions(env)); } export { Tenant, GitHubInstallationRegistry } from "./index"; -export default { fetch: (request: Request, env: Env, ctx: ExecutionContext) => provider(env).fetch(request, env, ctx) } satisfies ExportedHandler; +export default { async fetch(request: Request, env: Env, ctx: ExecutionContext) { + const oauth = provider(env); + const url = new URL(request.url); + if (url.pathname === "/oauth/device_authorization") return deviceAuthorization(request, env, getOAuthApi(providerOptions(env), env), scopes); + if (url.pathname === "/oauth/register") return deviceClientRegistration(request, env, oauth, ctx); + if (url.pathname === "/oauth/token" && request.method === "POST") { + const clone = request.clone(); + const form = await clone.formData().catch(() => null); + if (form?.get("grant_type") === DEVICE_GRANT) return deviceToken(request, env, oauth, ctx); + } + const response = await oauth.fetch(request, env, ctx); + if (url.pathname === "/.well-known/oauth-authorization-server") return addDeviceMetadata(response, env.APP_ORIGIN); + return response; +} } satisfies ExportedHandler; diff --git a/test/device-oauth.test.ts b/test/device-oauth.test.ts new file mode 100644 index 00000000..304bd408 --- /dev/null +++ b/test/device-oauth.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it, vi } from "vitest"; +import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceToken, deviceVerification } from "../src/device-oauth"; +import type { Env } from "../src/types"; + +class MemoryKv { + values = new Map(); + async get(key: string, type?: string): Promise { + const value = this.values.get(key); + if (value === undefined) return null; + return (type === "json" ? JSON.parse(value) : value) as T; + } + async put(key: string, value: string): Promise { this.values.set(key, value); } + async delete(key: string): Promise { this.values.delete(key); } +} + +function environment(kv: MemoryKv): Env { + return { + APP_ORIGIN: "https://factorize.test", + SESSION_SIGNING_SECRET: "session-secret", + OAUTH_KV: kv as unknown as KVNamespace, + } as Env; +} + +const publicClient = { clientId: "client-1", clientName: "Codex", redirectUris: ["http://127.0.0.1/callback"], tokenEndpointAuthMethod: "none" }; + +describe("OAuth device authorization", () => { + 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", { + method: "POST", body: new URLSearchParams({ client_id: "client-1", scope: "runs:read", resource: "https://factorize.test/mcp" }), + }), env, { lookupClient: vi.fn().mockResolvedValue(publicClient), completeAuthorization: vi.fn() }, ["flows:read", "runs:read"]); + expect(response.status).toBe(200); + const body = await response.json() as any; + expect(body.device_code).toBeTruthy(); + expect(body.user_code).toMatch(/^[A-Z2-9]{4}-[A-Z2-9]{4}$/); + expect(body.verification_uri).toBe("https://factorize.test/device"); + expect(body.verification_uri_complete).toContain(encodeURIComponent(body.user_code)); + expect(body.expires_in).toBe(600); + expect(body.interval).toBe(5); + }); + + it("rejects unsupported scopes and resources", async () => { + const env = environment(new MemoryKv()); + const oauth = { lookupClient: vi.fn().mockResolvedValue(publicClient), completeAuthorization: vi.fn() }; + const badScope = await deviceAuthorization(new Request("https://factorize.test/oauth/device_authorization", { method: "POST", body: new URLSearchParams({ client_id: "client-1", scope: "runs:write" }) }), env, oauth, ["flows:read", "runs:read"]); + await expect(badScope.json()).resolves.toMatchObject({ error: "invalid_scope" }); + const badResource = await deviceAuthorization(new Request("https://factorize.test/oauth/device_authorization", { method: "POST", body: new URLSearchParams({ client_id: "client-1", resource: "https://other.test/mcp" }) }), env, oauth, ["flows:read", "runs:read"]); + await expect(badResource.json()).resolves.toMatchObject({ error: "invalid_target" }); + }); + + it("returns authorization_pending and slow_down while approval is outstanding", 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" }); + }); + + it("approves a code and exchanges it through the normal PKCE token endpoint", async () => { + const kv = new MemoryKv(), env = environment(kv); + const completeAuthorization = vi.fn(async ({ request }: any) => ({ redirectTo: `${request.redirectUri}?code=authorization-code` })); + 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", body: new URLSearchParams({ user_code: issued.user_code, 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) => { + const body = await request.formData(); + expect(body.get("grant_type")).toBe("authorization_code"); + expect(body.get("code")).toBe("authorization-code"); + expect(body.get("code_verifier")).toBeTruthy(); + return Response.json({ access_token: "access", token_type: "bearer", expires_in: 3600 }); + }); + const token = await deviceToken(new Request("https://factorize.test/oauth/token", { method: "POST", body: new URLSearchParams({ grant_type: DEVICE_GRANT, client_id: "client-1", device_code: issued.device_code }) }), env, { fetch: providerFetch }, {} as ExecutionContext); + await expect(token.json()).resolves.toMatchObject({ access_token: "access" }); + expect(providerFetch).toHaveBeenCalledOnce(); + }); + + it("advertises the device endpoint and grant", async () => { + const response = await addDeviceMetadata(Response.json({ grant_types_supported: ["authorization_code", "refresh_token"] }), "https://factorize.test"); + await expect(response.json()).resolves.toMatchObject({ device_authorization_endpoint: "https://factorize.test/oauth/device_authorization", grant_types_supported: ["authorization_code", "refresh_token", DEVICE_GRANT] }); + }); + + it("adapts dynamic registration for device-only clients", async () => { + const env = environment(new MemoryKv()); + const providerFetch = vi.fn(async (request: Request) => { + const body = await request.json() as any; + expect(body.grant_types).toEqual(["authorization_code"]); + expect(body.response_types).toEqual(["code"]); + expect(body.redirect_uris).toEqual(["https://factorize.test/oauth/device/callback"]); + return Response.json({ client_id: "registered", grant_types: body.grant_types, response_types: body.response_types, redirect_uris: body.redirect_uris }, { status: 201 }); + }); + const response = await deviceClientRegistration(new Request("https://factorize.test/oauth/register", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ grant_types: [DEVICE_GRANT], token_endpoint_auth_method: "none" }) }), env, { fetch: providerFetch }, {} as ExecutionContext); + expect(response.status).toBe(201); + await expect(response.json()).resolves.toMatchObject({ client_id: "registered", grant_types: [DEVICE_GRANT], response_types: [], redirect_uris: [] }); + }); +});