/** * 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/<slug>` 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_<id>_…`, `ctr_<id>_…`), 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/<slug>` 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";importtype { Engine, Outcome } from"./engine.ts";import { keyDefault, typeEnv } from"./env.ts";import { json, randomToken, Refused, sha256Hex } from"./http.ts";import { normalizePhone } from"./protocol.ts";import { col, typeStore, typeStoredRow } from"./store.ts";import { mintSecret, TOKEN_TABLE } from"./tokens.ts";import { allowOf, DEFAULT_ALLOW, stored, typeAllow } from"./key_allow.ts";/** The path prefix that named the object ("" on a named host), set by the Worker on every forwarded request. */exportconst PREFIX_HEADER = "x-cotton-prefix";/** The paths this file answers, inside the object. */exportconst OAUTH_PATH = /^\/(\.well-known\/oauth-(protected-resource|authorization-server)(\/mcp)?|oauth\/(register|authorize|token))$/;const CLIENTS = "oauth_client";const CODES = "oauth_code";exportconst REFRESHES = "oauth_refresh";const SCOPE = "owner";const CODE_TTL_MS = 10 * 60_000;exportconst 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). */exportconst 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 refusesconst UNSHOWABLE = /[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/;/** A registered client: what it calls itself and where it may return. */exportinterfaceClient { 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. */exportinterfaceClients {get(id: string): Promise<Client | null>;/** The new client, or null when this hour's registrations are spent. */ add(client: Omit<Client, "id">): Promise<Client | null>;}/** What the object lends this file: its env, its store, a write inside one transaction with a fresh version, and its clients. */exportinterface OAuthHost { env: Env; store: Store; write<T>(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/<slug>` prefix is routed to the door alone (src/index.ts), * and both are the Worker's own facts, never a caller's. */exportfunction throughDoor(request: Request, env: Env): boolean {returnBoolean(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. */exportfunction storeClients(store: Store, write: OAuthHost["write"]): Clients {return {get: (id) => Promise.resolve(clientOf(store.get(CLIENTS, id))), add: (client) => {const hourAgo = newDate(Date.now() - 3_600_000).toISOString();if (store.count(CLIENTS, [{ sql: `COALESCE(CAST(${col("created")} AS TEXT), '') > ?`, args: [hourAgo] }]) >= REGISTRATIONS_PER_HOUR) returnPromise.resolve(null);if (store.count(CLIENTS, []) >= MAX_CLIENTS_HELD) returnPromise.resolve(null);const id = newClientId(); write((engine, version, outcome) => engine.create(CLIENTS, { client_id: id, client_name: client.name, redirect_uris: client.redirectUris, created: newDate().toISOString() }, version, outcome, 0, { id }));returnPromise.resolve({ id, ...client }); }, };}/** The open host's clients, in the directory: one registration serves every person; `ip` is counted against the hour. */exportfunction 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) returnnull;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)}`;}interfaceUrls { issuer: string; resource: string; resourceMetadata: string; authorize: string; token: string; register: string;}exportfunction 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. */exportfunction 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). */exportasyncfunction handleOAuth(request: Request, path: string, host: OAuthHost): Promise<Response> {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. */exportfunction 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(newResponse(null, { status: 204 }));if (request.method !== "GET") returnnull;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))));returnnull;}exportfunction 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<string, unknown> {return { resource: urls.resource, authorization_servers: [urls.issuer], scopes_supported: [SCOPE], bearer_methods_supported: ["header"], resource_name: "Cotton", };}function authorizationServer(urls: Urls): Record<string, unknown> {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<string, unknown>): Response {return json(doc, 200, { "cache-control": "public, max-age=300" });}exportfunction 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;}exportfunction 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. */exportfunction 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)) returnnull;let url: URL;try { url = new URL(raw); } catch {returnnull; }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();returnnull;}exportasyncfunction register(request: Request, clients: Clients): Promise<Response> {let body: Record<string, unknown>;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 asRecord<string, unknown>; } 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 = newDate();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 ────────────────────────────────exportinterfaceAuthorizeAsk { 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. */exportasyncfunction readAsk(params: URLSearchParams, clients: Clients, urls: Urls, door: boolean): Promise<AuthorizeAsk | Response> {const clientId = params.get("client_id") ?? "";const client = clientId ? await clients.get(clientId) : null;if (!client) return page("Cannot connect", `<p>This assistant is not registered here. Start the connection again from the assistant.</p>`, 400);const asked = redirectUri(params.get("redirect_uri"));if (!asked || !client.redirectUris.includes(asked)) return page("Cannot connect", `<p>The assistant asked to return somewhere it did not register. Start the connection again from the assistant.</p>`, 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. */exportasyncfunction authorizeParams(request: Request): Promise<URLSearchParams | null> {return request.method === "GET" ? new URL(request.url).searchParams : await form(request);}exportconst UNREADABLE_FORM = "<p>The form could not be read.</p>";exportconst BAD_PHONE = "Use an international phone number starting with +.";function notOwner(phone: string): Response {return page("Not allowed", `<p>${esc(phone)} does not own this database. Only its owner can connect an assistant to it.</p>`, 403);}asyncfunction authorize(request: Request, host: OAuthHost, urls: Urls): Promise<Response> {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 instanceofResponse) return ask;const step = request.method === "GET" ? "start" : params.get("step");const now = newDate();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 instanceofRefused) 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: newDate(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 instanceofRefused) return phonePage(ask, urls, params, sentence(error.message));throw error; }}function redirect(to: string, params: Record<string, string | null>): Response {const url = new URL(to);for (const [k, v] ofObject.entries(params)) if (v !== null && v !== "") url.searchParams.set(k, v);returnnewResponse(null, { status: 302, headers: { location: url.toString(), "cache-control": "no-store" } });}function sameResource(a: string, b: string): boolean {return a.replace(/\/+$/, "") === b.replace(/\/+$/, "");}exportasyncfunction form(request: Request): Promise<URLSearchParams | null> {consttype = (request.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase();if (type !== "application/x-www-form-urlencoded") returnnull;returnnew URLSearchParams(newTextDecoder().decode(await request.arrayBuffer()));}exportfunction 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"];exportfunction esc(value: string): string {return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");}function hidden(fields: Record<string, string>): string {returnObject.entries(fields) .map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`) .join("\n");}function carried(params: URLSearchParams): Record<string, string> {const out: Record<string, string> = {};for (const k of CARRIED) {const v = params.get(k);if (v !== null) out[k] = v; }return out;}function intro(ask: AuthorizeAsk): string {return`<p><strong>${esc(ask.clientName)}</strong> 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)}.</p>`;}exportfunction phonePage(ask: AuthorizeAsk, urls: Urls, params: URLSearchParams, problem?: string, status = 400): Response {return page("Connect to Cotton",`${intro(ask)}<p>${ask.door ? "Enter your phone number and Cotton sends it a code." : "Only the owner's phone number can allow it."}</p>${problem ? `<p role="alert">${esc(problem)}</p>` : ""}<form method="post" action="${esc(urls.authorize)}">${hidden({ ...carried(params), step: "phone" })}<p><label>Phone number<br><input type="tel" name="phone" autocomplete="tel" placeholder="+91…" required autofocus></label></p><p><button type="submit">Send code</button></p></form>`, 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)}<p>Enter the code sent to ${esc(sent.phone)}.</p>${problem ? `<p role="alert">${esc(problem)}</p>` : ""}<form method="post" action="${esc(urls.authorize)}">${hidden({ ...carried(params), step: "code", phone: sent.phone, challenge_id: sent.challenge, device_id: sent.device, database_id: sent.database })}<p><label>Code<br><input type="text" name="code" inputmode="numeric" autocomplete="one-time-code" required autofocus></label></p><p><button type="submit">Connect</button></p></form>${ problem ? `<form method="post" action="${esc(urls.authorize)}">${hidden({ ...carried(params), step: "phone", phone: sent.phone })}<p><button type="submit">Send a new code</button></p></form>` : "" }`, problem ? 401 : 200, );}exportfunction page(title: string, body: string, status = 200): Response {const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${esc(title)}</title></head><body><h1>${esc(title)}</h1>${body}</body></html>`;returnnewResponse(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 ───────────────────────────────────────────────────asyncfunction token(request: Request, host: OAuthHost): Promise<Response> {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. */exportfunction 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) returnnull;try {const user = atob(m[1]!).split(":")[0] ?? "";return decodeURIComponent(user.replace(/\+/g, " ")) || null; } catch {returnnull; }}/** BASE64URL(SHA256(verifier)), the S256 challenge a verifier makes. */exportasyncfunction s256(verifier: string): Promise<string> {const digest = newUint8Array(await crypto.subtle.digest("SHA-256", newTextEncoder().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) returnfalse;let diff = 0;for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);return diff === 0;}interfacePair { access: string; accessHash: string; refresh: string; refreshHash: string;}asyncfunction newPair(host: OAuthHost): Promise<Pair> {// 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) thrownewRefused(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) returnnull;const said = host.store.get(TOKEN_TABLE, tokenId)?.data.connection_id;returntypeof 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: newDate(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: newDate(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: newDate().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" });}asyncfunction redeemCode(params: URLSearchParams, client: Client, host: OAuthHost, urls: Urls): Promise<Response> {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: newDate().toISOString() }, version, outcome);const d = row.data;if (String(d.expires_at) <= newDate().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);}asyncfunction refresh(params: URLSearchParams, client: Client, host: OAuthHost): Promise<Response> {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: newDate().toISOString() }, version, outcome); }return"replayed"; }if (String(row.data.expires_at) <= newDate().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: newDate().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);}