/** * OAuth 2.1 for Cotton MCP on the personal object, so claude.ai's custom * connectors and Claude Desktop, which cannot send a pasted bearer, connect * by URL alone (MCP authorization, 2025-06-18). The flow the retired Rust * server ran for the relay (crates/cotton-server/src/oauth/), on the object: * * POST /mcp with no token → 401 + `WWW-Authenticate: Bearer resource_metadata="…"` * GET the protected-resource document (RFC 9728) → the authorization server * GET its metadata (RFC 8414) → where to register, authorize and redeem * POST /oauth/register (RFC 7591) → a client id; registering buys nothing * GET /oauth/authorize → the owner's phone, the object's own code, the code * POST /oauth/token → a `ctn_` token (an `mcp_token` row, scope owner) and a * refresh token that rotates both * * Every URL is derived from the URL the client reached: the origin plus the * `/b/` prefix when that named the object (the Worker says which on * PREFIX_HEADER), so the issuer and resource always equal what the person * typed, on workers.dev and on a named host alike. Only the owner's phone * passes the sign-in; a member or a stranger who proves their own code is * refused. Codes and refresh tokens are rows of the personal package's * `oauth_code` and `oauth_refresh` tables, kept only as their sha256 (the * row's id); each names its database (`ctc__…`, `ctr__…`), so the * open host routes it with nothing remembered. * * THE OPEN HOST (owner, 6 Nov 2026: one address for everyone, cottondb.com/mcp) * names no object until the person types their number, so a client cannot * live in one: there the clients are the directory's (src/directory.ts), and * the door (src/open.ts) answers the documents and registration itself, finds * the number's database, and hands this same authorize and token code the * rest. On a named host or a `/b/` prefix the clients are the object's * own `oauth_client` rows, as they always were. */ import { issueCode, proveCode, provenAlready } from "./auth.ts"; import { directory } from "./directory.ts"; import type { Engine, Outcome } from "./engine.ts"; import { keyDefault, type Env } from "./env.ts"; import { json, randomToken, Refused, sha256Hex } from "./http.ts"; import { normalizePhone } from "./protocol.ts"; import { col, type Store, type StoredRow } from "./store.ts"; import { mintSecret, TOKEN_TABLE } from "./tokens.ts"; import { allowOf, DEFAULT_ALLOW, stored, type Allow } from "./key_allow.ts"; /** The path prefix that named the object ("" on a named host), set by the Worker on every forwarded request. */ export const PREFIX_HEADER = "x-cotton-prefix"; /** The paths this file answers, inside the object. */ export const OAUTH_PATH = /^\/(\.well-known\/oauth-(protected-resource|authorization-server)(\/mcp)?|oauth\/(register|authorize|token))$/; const CLIENTS = "oauth_client"; const CODES = "oauth_code"; export const REFRESHES = "oauth_refresh"; const SCOPE = "owner"; const CODE_TTL_MS = 10 * 60_000; export const ACCESS_TTL_SECONDS = 30 * 86_400; const REFRESH_TTL_MS = 180 * 86_400_000; const REGISTRATIONS_PER_HOUR = 30; const MAX_REDIRECTS = 10; const MAX_NAME = 200; /** The most clients one object holds, ever: anyone may register on a named object, and its rows sync to the owner's phones (ROUTES-AUDIT 14). */ export const MAX_CLIENTS_HELD = 20; /** Control characters and the bidirectional overrides that would make a client's name read as something else on the consent page. */ // eslint-disable-next-line no-control-regex -- control characters are what it refuses const UNSHOWABLE = /[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/; /** A registered client: what it calls itself and where it may return. */ export interface Client { id: string; name: string | null; redirectUris: string[]; } /** Where clients live: the object's own rows on a named host, the directory's on the open host. */ export interface Clients { get(id: string): Promise; /** The new client, or null when this hour's registrations are spent. */ add(client: Omit): Promise; } /** What the object lends this file: its env, its store, a write inside one transaction with a fresh version, and its clients. */ export interface OAuthHost { env: Env; store: Store; write(fn: (engine: Engine, version: number, outcome: Outcome) => T): T; clients: Clients; /** Reached through the open host's door, where any number signs in to its own database. */ door: boolean; /** A connection was ended (a replayed refresh token): its unlock windows end with it, in the same write. */ connectionEnded?(engine: Engine, connectionId: string, version: number, outcome: Outcome): void; /** * Your Claude's member key travels with the pair (src/agent.ts): asked * before the write, with the new pair's strings (and, on a refresh, the * refresh token presented); answers what to write inside it, or null. */ carry?(pair: { access: string; accessHash: string; refresh: string; refreshHash: string }, clientName: string, presented: { token: string; hash: string } | null, redirect?: string | null): Promise<(() => void) | null>; /** The owner's code proved on the connect page: a database prepared at /v1/code (AUDIT F) has its kit laid now, as sign-in lays it. */ ownerProved?(): void; /** After a pair is written: the connection it made (its access token's row and hash) may file Your Claude's card. */ connected?(tokenId: string, accessHash: string, clientName: string): void; } /** * Whether a request reached the object through the open host's door: the open * host with no `/b/` prefix is routed to the door alone (src/index.ts), * and both are the Worker's own facts, never a caller's. */ export function throughDoor(request: Request, env: Env): boolean { return Boolean(env.OPEN_HOST) && new URL(request.url).hostname.toLowerCase() === env.OPEN_HOST && (request.headers.get(PREFIX_HEADER) ?? "") === ""; } /** The object's own clients: its `oauth_client` rows, at most REGISTRATIONS_PER_HOUR made an hour and MAX_CLIENTS_HELD in all. */ export function storeClients(store: Store, write: OAuthHost["write"]): Clients { return { get: (id) => Promise.resolve(clientOf(store.get(CLIENTS, id))), add: (client) => { const hourAgo = new Date(Date.now() - 3_600_000).toISOString(); if (store.count(CLIENTS, [{ sql: `COALESCE(CAST(${col("created")} AS TEXT), '') > ?`, args: [hourAgo] }]) >= REGISTRATIONS_PER_HOUR) return Promise.resolve(null); if (store.count(CLIENTS, []) >= MAX_CLIENTS_HELD) return Promise.resolve(null); const id = newClientId(); write((engine, version, outcome) => engine.create(CLIENTS, { client_id: id, client_name: client.name, redirect_uris: client.redirectUris, created: new Date().toISOString() }, version, outcome, 0, { id })); return Promise.resolve({ id, ...client }); }, }; } /** The open host's clients, in the directory: one registration serves every person; `ip` is counted against the hour. */ export function directoryClients(env: Env, ip: string): Clients { return { get: (id) => directory(env).client(id), add: async (client) => { const answer = await directory(env).register({ id: newClientId(), ...client }, ip); return "ok" in answer ? answer.ok : null; }, }; } function clientOf(row: StoredRow | null): Client | null { if (!row) return null; return { id: row.id, name: typeof row.data.client_name === "string" && row.data.client_name ? row.data.client_name : null, redirectUris: Array.isArray(row.data.redirect_uris) ? (row.data.redirect_uris as string[]) : [] }; } function newClientId(): string { return `cc_${randomToken(18)}`; } interface Urls { issuer: string; resource: string; resourceMetadata: string; authorize: string; token: string; register: string; } export function urlsOf(request: Request): Urls { const origin = new URL(request.url).origin; const prefix = request.headers.get(PREFIX_HEADER) ?? ""; const issuer = `${origin}${prefix}`; return { issuer, resource: `${issuer}/mcp`, // RFC 9728 §3.1: the well-known segment goes before the resource's path. The Worker routes this form and the prefixed one alike. resourceMetadata: `${origin}/.well-known/oauth-protected-resource${prefix}/mcp`, authorize: `${issuer}/oauth/authorize`, token: `${issuer}/oauth/token`, register: `${issuer}/oauth/register`, }; } /** The 401 at /mcp, carrying where to learn how to sign in; `presented` says a token came and was no good. */ export function challenge(response: Response, request: Request, presented: boolean): Response { const parts = [...(presented ? ['error="invalid_token"'] : []), `resource_metadata="${urlsOf(request).resourceMetadata}"`, `scope="${SCOPE}"`]; response.headers.set("www-authenticate", `Bearer ${parts.join(", ")}`); return response; } /** Every OAuth route, on the personal object only (the caller checks that). */ export async function handleOAuth(request: Request, path: string, host: OAuthHost): Promise { const method = request.method; const documents = oauthDocument(request, path); if (documents) return documents; if (method === "POST" && path === "/oauth/register") return cors(await register(request, host.clients)); if (method === "POST" && path === "/oauth/token") return cors(await token(request, host)); if (path === "/oauth/authorize" && (method === "GET" || method === "POST")) return authorize(request, host, urlsOf(request)); return notAnswered(method, path); } /** A preflight or one of the two documents, which need no object; null for the endpoints. */ export function oauthDocument(request: Request, path: string): Response | null { // The machine documents and endpoints are reachable from any origin: nothing on them rides a cookie. if (request.method === "OPTIONS") return cors(new Response(null, { status: 204 })); if (request.method !== "GET") return null; if (path.startsWith("/.well-known/oauth-protected-resource")) return cors(metadata(protectedResource(urlsOf(request)))); if (path.startsWith("/.well-known/oauth-authorization-server")) return cors(metadata(authorizationServer(urlsOf(request)))); return null; } export function notAnswered(method: string, path: string): Response { return json({ code: "method_not_allowed", message: `${method} ${path} is not answered` }, 405); } // ── the documents ──────────────────────────────────────────────────────── function protectedResource(urls: Urls): Record { return { resource: urls.resource, authorization_servers: [urls.issuer], scopes_supported: [SCOPE], bearer_methods_supported: ["header"], resource_name: "Cotton", }; } function authorizationServer(urls: Urls): Record { return { issuer: urls.issuer, authorization_endpoint: urls.authorize, token_endpoint: urls.token, registration_endpoint: urls.register, response_types_supported: ["code"], grant_types_supported: ["authorization_code", "refresh_token"], code_challenge_methods_supported: ["S256"], token_endpoint_auth_methods_supported: ["none", "client_secret_post"], scopes_supported: [SCOPE], }; } function metadata(doc: Record): Response { return json(doc, 200, { "cache-control": "public, max-age=300" }); } export function cors(response: Response): Response { response.headers.set("access-control-allow-origin", "*"); response.headers.set("access-control-allow-methods", "GET, POST, OPTIONS"); response.headers.set("access-control-allow-headers", "authorization, content-type, mcp-protocol-version"); response.headers.set("access-control-max-age", "600"); return response; } export function oauthError(error: string, description: string, status = 400): Response { return json({ error, error_description: description }, status, { pragma: "no-cache" }); } // ── registration (RFC 7591) ────────────────────────────────────────────── /** https, or http on loopback (RFC 8252); never a fragment. The stored form and the asked form go through this one function. */ export function redirectUri(raw: unknown): string | null { if (typeof raw !== "string" || raw.includes("#") || /\s/.test(raw) || [...raw].some((c) => c.charCodeAt(0) < 0x20 || c.charCodeAt(0) === 0x7f)) return null; let url: URL; try { url = new URL(raw); } catch { return null; } const loopback = url.hostname === "localhost" || url.hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(url.hostname); if (url.protocol === "https:" && url.hostname) return url.toString(); if (url.protocol === "http:" && loopback) return url.toString(); return null; } export async function register(request: Request, clients: Clients): Promise { let body: Record; try { const parsed: unknown = JSON.parse(await request.text()); if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return oauthError("invalid_client_metadata", "the registration body must be a JSON object"); body = parsed as Record; } catch { return oauthError("invalid_client_metadata", "the registration body must be JSON"); } const raw = body.redirect_uris; if (!Array.isArray(raw) || !raw.length || raw.length > MAX_REDIRECTS) return oauthError("invalid_redirect_uri", `redirect_uris must be an array of 1 to ${MAX_REDIRECTS} URIs`); const redirects: string[] = []; for (const uri of raw) { const normalized = redirectUri(uri); if (!normalized) return oauthError("invalid_redirect_uri", `${JSON.stringify(uri)} is not a usable redirect URI: use https://, or http:// on localhost`); if (!redirects.includes(normalized)) redirects.push(normalized); } if (body.client_name !== undefined && body.client_name !== null && typeof body.client_name !== "string") return oauthError("invalid_client_metadata", "client_name must be a string"); const name = typeof body.client_name === "string" ? body.client_name.trim() : ""; if (name.length > MAX_NAME) return oauthError("invalid_client_metadata", `client_name must be ${MAX_NAME} characters or fewer`); if (UNSHOWABLE.test(name)) return oauthError("invalid_client_metadata", "client_name must be plain text, with no control or direction characters"); // Judged by whether it can run the code grant; a grant or response type this server does not offer (claude.ai declares jwt-bearer) is ignored, not fatal. if (Array.isArray(body.grant_types) && !body.grant_types.includes("authorization_code")) return oauthError("invalid_client_metadata", "grant_types must include authorization_code"); if (Array.isArray(body.response_types) && !body.response_types.includes("code")) return oauthError("invalid_client_metadata", 'response_types must include "code"'); // Anyone may register, so registrations are bounded: a disk-space bound, not an access one. const created = new Date(); const client = await clients.add({ name: name || null, redirectUris: redirects }); if (!client) return oauthError("invalid_client_metadata", "too many registrations; try again later", 429); return json( { client_id: client.id, client_id_issued_at: Math.floor(created.getTime() / 1000), client_name: name || undefined, redirect_uris: redirects, grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none", }, 201, ); } // ── authorize: the owner's phone and code ──────────────────────────────── export interface AuthorizeAsk { client: Client; clientName: string; redirectUri: string; state: string | null; codeChallenge: string; scope: string; resource: string | null; /** Asked on the open host, where any number signs in to its own database. */ door: boolean; } /** The asked-for authorization, or the answer refusing it: a bad client or redirect is said on the page, anything else goes back to the client. */ export async function readAsk(params: URLSearchParams, clients: Clients, urls: Urls, door: boolean): Promise { const clientId = params.get("client_id") ?? ""; const client = clientId ? await clients.get(clientId) : null; if (!client) return page("Cannot connect", `

This assistant is not registered here. Start the connection again from the assistant.

`, 400); const asked = redirectUri(params.get("redirect_uri")); if (!asked || !client.redirectUris.includes(asked)) return page("Cannot connect", `

The assistant asked to return somewhere it did not register. Start the connection again from the assistant.

`, 400); const state = params.get("state"); const back = (error: string, description: string) => redirect(asked, { error, error_description: description, state }); if (params.get("response_type") !== "code") return back("unsupported_response_type", "response_type must be code"); const codeChallenge = params.get("code_challenge") ?? ""; if (params.get("code_challenge_method") !== "S256" || !/^[A-Za-z0-9_-]{43}$/.test(codeChallenge)) return back("invalid_request", "PKCE with S256 is required"); const resource = params.get("resource"); if (resource && !sameResource(resource, urls.resource)) return back("invalid_target", `this server issues tokens only for ${urls.resource}`); return { client, clientName: client.name || "An assistant", redirectUri: asked, state, codeChallenge, scope: SCOPE, resource, door }; } /** The authorize page's fields: the query of a GET, the form of a POST, or null when the form cannot be read. */ export async function authorizeParams(request: Request): Promise { return request.method === "GET" ? new URL(request.url).searchParams : await form(request); } export const UNREADABLE_FORM = "

The form could not be read.

"; export const BAD_PHONE = "Use an international phone number starting with +."; function notOwner(phone: string): Response { return page("Not allowed", `

${esc(phone)} does not own this database. Only its owner can connect an assistant to it.

`, 403); } async function authorize(request: Request, host: OAuthHost, urls: Urls): Promise { const params = await authorizeParams(request); if (!params) return page("Cannot connect", UNREADABLE_FORM, 400); const ask = await readAsk(params, host.clients, urls, host.door); if (ask instanceof Response) return ask; const step = request.method === "GET" ? "start" : params.get("step"); const now = new Date(); try { if (step === "phone") { const phone = normalizePhone(params.get("phone") ?? ""); if (!phone) return phonePage(ask, urls, params, BAD_PHONE); // ROUTES-AUDIT 1 (23 Nov 2026): only the owner connects an assistant, so only the owner's number is sent a code. // Any other number gets nothing: no code, no challenge in the page to present to /v1/sign-in. if (phone !== host.store.meta("owner_phone")) return notOwner(phone); const deviceId = `oauth:${randomToken(12)}`; const { challenge_id } = await issueCode(host.env, host.store, now, phone, deviceId); return codePage(ask, urls, params, { phone, challenge: challenge_id, device: deviceId, database: host.store.meta("database_id") ?? "" }); } if (step === "code") { const challengeId = params.get("challenge_id") ?? ""; const deviceId = params.get("device_id") ?? ""; const phone = params.get("phone") ?? ""; let proven: string; try { // The same form sent twice: the second copy is answered as the first was, with its own fresh grant. const again = await provenAlready(host.store, now, challengeId, params.get("code") ?? "", deviceId); if (again !== null) console.warn("cottondb: connect page code sent again"); proven = again ?? (await proveCode(host.env, host.store, now, challengeId, params.get("code") ?? "", deviceId)); } catch (error) { if (error instanceof Refused) return codePage(ask, urls, params, { phone, challenge: challengeId, device: deviceId, database: params.get("database_id") ?? "" }, sentence(error.message)); throw error; } if (proven !== host.store.meta("owner_phone")) return notOwner(proven); host.ownerProved?.(); const code = `ctc_${host.store.meta("database_id") ?? ""}_${randomToken(32)}`; const codeHash = await sha256Hex(code); host.write((engine, version, outcome) => engine.create( CODES, { client_id: ask.client.id, redirect_uri: ask.redirectUri, code_challenge: ask.codeChallenge, scope: ask.scope, expires_at: new Date(now.getTime() + CODE_TTL_MS).toISOString() }, version, outcome, 0, { id: codeHash }, ), ); return redirect(ask.redirectUri, { code, state: ask.state }); } return phonePage(ask, urls, params); } catch (error) { if (error instanceof Refused) return phonePage(ask, urls, params, sentence(error.message)); throw error; } } function redirect(to: string, params: Record): Response { const url = new URL(to); for (const [k, v] of Object.entries(params)) if (v !== null && v !== "") url.searchParams.set(k, v); return new Response(null, { status: 302, headers: { location: url.toString(), "cache-control": "no-store" } }); } function sameResource(a: string, b: string): boolean { return a.replace(/\/+$/, "") === b.replace(/\/+$/, ""); } export async function form(request: Request): Promise { const type = (request.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase(); if (type !== "application/x-www-form-urlencoded") return null; return new URLSearchParams(new TextDecoder().decode(await request.arrayBuffer())); } export function sentence(message: string): string { const s = message.charAt(0).toUpperCase() + message.slice(1); return /[.!?]$/.test(s) ? s : `${s}.`; } // ── the pages ──────────────────────────────────────────────────────────── // Plain HTML with the browser's own defaults. This is NOT a design surface: // it is the one page an assistant's sign-in opens, readable and nothing more. const CARRIED = ["client_id", "redirect_uri", "response_type", "code_challenge", "code_challenge_method", "state", "scope", "resource"]; export function esc(value: string): string { return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); } function hidden(fields: Record): string { return Object.entries(fields) .map(([k, v]) => ``) .join("\n"); } function carried(params: URLSearchParams): Record { const out: Record = {}; for (const k of CARRIED) { const v = params.get(k); if (v !== null) out[k] = v; } return out; } function intro(ask: AuthorizeAsk): string { return `

${esc(ask.clientName)} is asking to connect to your Cotton as you, with owner access to your whole personal database. It will return you to ${esc(new URL(ask.redirectUri).host)}.

`; } export function phonePage(ask: AuthorizeAsk, urls: Urls, params: URLSearchParams, problem?: string, status = 400): Response { return page( "Connect to Cotton", `${intro(ask)}

${ask.door ? "Enter your phone number and Cotton sends it a code." : "Only the owner's phone number can allow it."}

${problem ? `

${esc(problem)}

` : ""}
${hidden({ ...carried(params), step: "phone" })}

`, problem ? status : 200, ); } function codePage(ask: AuthorizeAsk, urls: Urls, params: URLSearchParams, sent: { phone: string; challenge: string; device: string; database: string }, problem?: string): Response { return page( "Connect to Cotton", `${intro(ask)}

Enter the code sent to ${esc(sent.phone)}.

${problem ? `

${esc(problem)}

` : ""}
${hidden({ ...carried(params), step: "code", phone: sent.phone, challenge_id: sent.challenge, device_id: sent.device, database_id: sent.database })}

${ problem ? `
${hidden({ ...carried(params), step: "phone", phone: sent.phone })}

` : "" }`, problem ? 401 : 200, ); } export function page(title: string, body: string, status = 200): Response { const html = ` ${esc(title)}

${esc(title)}

${body} `; return new Response(html, { status, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "x-frame-options": "DENY", "content-security-policy": "default-src 'none'; frame-ancestors 'none'", "referrer-policy": "no-referrer", }, }); } // ── the token endpoint ─────────────────────────────────────────────────── async function token(request: Request, host: OAuthHost): Promise { const params = await form(request); if (!params) return oauthError("invalid_request", "the body must be application/x-www-form-urlencoded"); const clientId = clientIdOf(request, params); const client = clientId ? await host.clients.get(clientId) : null; if (!client) return oauthError("invalid_client", "unknown client", 401); const grant = params.get("grant_type"); if (grant === "authorization_code") return redeemCode(params, client, host, urlsOf(request)); if (grant === "refresh_token") return refresh(params, client, host); return oauthError("unsupported_grant_type", "grant_type is authorization_code or refresh_token"); } /** The client a token request names: in the form, or as the Basic user a public client may still send (RFC 6749 §2.3.1); there is no secret to check. */ export function clientIdOf(request: Request, params: URLSearchParams): string | null { return params.get("client_id") ?? basicClientId(request); } function basicClientId(request: Request): string | null { const m = /^Basic\s+(\S+)$/i.exec(request.headers.get("authorization") ?? ""); if (!m) return null; try { const user = atob(m[1]!).split(":")[0] ?? ""; return decodeURIComponent(user.replace(/\+/g, " ")) || null; } catch { return null; } } /** BASE64URL(SHA256(verifier)), the S256 challenge a verifier makes. */ export async function s256(verifier: string): Promise { const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))); let s = ""; for (const b of digest) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function sameText(a: string, b: string): boolean { if (a.length !== b.length) return false; let diff = 0; for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); return diff === 0; } interface Pair { access: string; accessHash: string; refresh: string; refreshHash: string; } async function newPair(host: OAuthHost): Promise { // Where no database is, the pair is made as for one and never kept (every write there is rolled back), so a stranger's // redemption is refused as invalid_grant either way. const databaseId = host.store.meta("database_id") ?? (host.store.meta("kind") === null ? "00000000-0000-0000-0000-000000000000" : null); if (!databaseId) throw new Refused(503, "no_database_id", "the personal database has no database_id yet"); const { token: access, hash: accessHash } = await mintSecret(databaseId); const refresh = `ctr_${databaseId}_${randomToken(32)}`; return { access, accessHash, refresh, refreshHash: await sha256Hex(refresh) }; } /** The connection a token belongs to: its connection_id, else the token itself (one minted before tokens named their connection). */ function connectionOfToken(host: OAuthHost, tokenId: unknown): string | null { if (typeof tokenId !== "string" || !tokenId) return null; const said = host.store.get(TOKEN_TABLE, tokenId)?.data.connection_id; return typeof said === "string" && said ? said : tokenId; } /** * The pair's two rows: an owner `mcp_token` named after the client, and its * refresh token. The token names its connection: a new one at the code's * redemption, the same one at every refresh, so an unlock window bound to the * connection stands across refreshes. */ /** A new connection's allow (ADMIN KEYS 3, the KEY_DEFAULT switch): none while it says "today", as before allows. */ function newConnectionAllow(env: Env): Allow | null { return keyDefault(env) === "today" ? null : DEFAULT_ALLOW; } function writePair(engine: Engine, version: number, outcome: Outcome, client: Client, pair: Pair, scope: string, connection: string, allow: Allow | null): StoredRow { const now = Date.now(); const name = client.name || "OAuth client"; // ADMIN KEYS 2: a new connection's key carries newConnectionAllow (the switch); a refresh carries its connection's as it // stood (none for a connection made before allows: as it was, until the owner narrows it). const row = engine.create(TOKEN_TABLE, { name, scopes: [SCOPE], token_hash: pair.accessHash, expires_at: new Date(now + ACCESS_TTL_SECONDS * 1000).toISOString(), connection_id: connection, ...(allow ? { allow: stored(allow) } : {}) }, version, outcome); engine.create(REFRESHES, { client_id: client.id, token: row.id, scope, expires_at: new Date(now + REFRESH_TTL_MS).toISOString() }, version, outcome, 0, { id: pair.refreshHash }); return row; } function revokeToken(engine: Engine, host: OAuthHost, id: unknown, version: number, outcome: Outcome): void { const row = typeof id === "string" && id ? host.store.get(TOKEN_TABLE, id) : null; if (row && !row.data.revoked_at) engine.update(row, { revoked_at: new Date().toISOString() }, version, outcome); } function tokens(pair: Pair, scope: string): Response { return json({ access_token: pair.access, token_type: "Bearer", expires_in: ACCESS_TTL_SECONDS, refresh_token: pair.refresh, scope }, 200, { pragma: "no-cache" }); } async function redeemCode(params: URLSearchParams, client: Client, host: OAuthHost, urls: Urls): Promise { const code = params.get("code"); const asked = params.get("redirect_uri"); const verifier = params.get("code_verifier") ?? ""; if (!code || !asked || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) return oauthError("invalid_request", "code, redirect_uri and code_verifier are required"); const resource = params.get("resource"); if (resource && !sameResource(resource, urls.resource)) return oauthError("invalid_target", `this server issues tokens only for ${urls.resource}`); // Everything asynchronous first: the claim and the mint below are one synchronous transaction, so two redemptions cannot both win. const codeHash = await sha256Hex(code); const challenge = await s256(verifier); const pair = await newPair(host); // The redirect the code goes back to: a waiting Connect Claude is claimed only by Claude's own (AUDIT C 5). const carried = host.carry ? await host.carry(pair, client.name ?? "", null, asked) : null; let mintedId = ""; const verdict = host.write((engine, version, outcome): "ok" | "invalid" => { const row = host.store.get(CODES, codeHash); if (!row) return "invalid"; if (row.data.used_at) { // A code presented twice is a leaked code: the token it was redeemed for dies too. revokeToken(engine, host, row.data.token, version, outcome); return "invalid"; } // Spent before it is judged: a code that fails a check is gone all the same. const spent = engine.update(row, { used_at: new Date().toISOString() }, version, outcome); const d = row.data; if (String(d.expires_at) <= new Date().toISOString()) return "invalid"; if (d.client_id !== client.id) return "invalid"; if (redirectUri(asked) !== d.redirect_uri) return "invalid"; if (!sameText(challenge, String(d.code_challenge))) return "invalid"; const minted = writePair(engine, version, outcome, client, pair, String(d.scope ?? SCOPE), crypto.randomUUID(), newConnectionAllow(host.env)); engine.update(spent, { token: minted.id }, version, outcome); carried?.(); mintedId = minted.id; return "ok"; }); // Which check failed is the attacker's question, not the client's: every refusal is the same sentence. if (verdict !== "ok") return oauthError("invalid_grant", "authorization code is not valid"); host.connected?.(mintedId, pair.accessHash, client.name ?? ""); return tokens(pair, SCOPE); } async function refresh(params: URLSearchParams, client: Client, host: OAuthHost): Promise { const presented = params.get("refresh_token"); if (!presented) return oauthError("invalid_request", "refresh_token is required"); const hash = await sha256Hex(presented); const pair = await newPair(host); // Only a live, unspent refresh token of this client carries its member on; anything else is refused below and the prepared carriers are dropped unused. const held = host.store.get(REFRESHES, hash); const carried = host.carry && held && !held.data.used_at && held.data.client_id === client.id ? await host.carry(pair, client.name ?? "", { token: presented, hash }) : null; let mintedId = ""; const verdict = host.write((engine, version, outcome): "ok" | "invalid" | "replayed" => { const row = host.store.get(REFRESHES, hash); if (!row || row.data.client_id !== client.id) return "invalid"; if (row.data.used_at) { // Spent twice: whoever holds the live successor may not be the client, so it dies. let live: StoredRow | null = row; for (let i = 0; live?.data.replaced_by && i < 1000; i++) live = host.store.get(REFRESHES, String(live.data.replaced_by)); if (live && live !== row) { revokeToken(engine, host, live.data.token, version, outcome); const connection = connectionOfToken(host, live.data.token); if (connection) host.connectionEnded?.(engine, connection, version, outcome); if (!live.data.used_at) engine.update(live, { used_at: new Date().toISOString() }, version, outcome); } return "replayed"; } if (String(row.data.expires_at) <= new Date().toISOString()) return "invalid"; const before = typeof row.data.token === "string" ? host.store.get(TOKEN_TABLE, row.data.token) : null; // ADMIN KEYS 4 / AUDIT C 1: a refresh token whose access token is revoked is spent, whatever its own row says. Every // refresh revokes the token it replaces in the same write, so a spent row put back to unspent (an undo, a restore) // still names a revoked token; and the owner revoking a connection's token ends the connection, not just one call. if (before?.data.revoked_at) return "invalid"; mintedId = writePair(engine, version, outcome, client, pair, String(row.data.scope ?? SCOPE), connectionOfToken(host, row.data.token) ?? crypto.randomUUID(), before ? allowOf(before.data) : newConnectionAllow(host.env)).id; engine.update(row, { used_at: new Date().toISOString(), replaced_by: pair.refreshHash }, version, outcome); revokeToken(engine, host, row.data.token, version, outcome); carried?.(); return "ok"; }); if (verdict === "ok" && carried) host.connected?.(mintedId, pair.accessHash, client.name ?? ""); if (verdict === "replayed") return oauthError("invalid_grant", "this refresh token was already used, so the connection was ended; connect again"); if (verdict !== "ok") return oauthError("invalid_grant", "refresh token is not valid"); return tokens(pair, SCOPE); }