askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
toolbar: Back and Forward are greyed out when there's nowhere to go
cc08c7a
1 week, 2 days ago
History
mcp-oauth.ts · 15.1 KB · 322 lines
| 1 | /** |
| 2 | * Signing in to an MCP server with OAuth, the way a desktop app should: authorization code with PKCE (S256), a |
| 3 | * loopback listener for the redirect, and no client secret. Main process only: tokens never reach a page or the chrome UI. |
| 4 | * |
| 5 | * 1. discover — the server's protected-resource document names its authorization server; that one names the endpoints |
| 6 | * 2. register — once per server (dynamic client registration), keeping the client id |
| 7 | * 3. authorize — open the person's own browser on the consent page; wait for the redirect on 127.0.0.1 |
| 8 | * 4. exchange — trade the code for an access token (short-lived) and a refresh token |
| 9 | * 5. refresh — quietly, shortly before the access token runs out |
| 10 | * |
| 11 | * Everything that touches the network goes through an injectable `fetch`, so the whole flow is tested without one. |
| 12 | */ |
| 13 | |
| 14 | import { createHash, randomBytes } from "node:crypto"; |
| 15 | import { createServer, type Server } from "node:http"; |
| 16 | import type { AddressInfo } from "node:net"; |
| 17 | |
| 18 | export type Fetch = (url: string, init?: { method?: string; headers?: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<{ |
| 19 | ok: boolean; |
| 20 | status: number; |
| 21 | headers: { get(name: string): string | null }; |
| 22 | text(): Promise<string>; |
| 23 | }>; |
| 24 | |
| 25 | export class OAuthError extends Error { |
| 26 | readonly code: "discovery" | "registration" | "denied" | "timeout" | "state" | "token" | "refresh" | "no-port" | "unsafe" | "scope"; |
| 27 | constructor(code: OAuthError["code"], message: string) { |
| 28 | super(message); |
| 29 | this.name = "OAuthError"; |
| 30 | this.code = code; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | /** Ports the redirect listener may use. All are registered up front, because a server matches redirect addresses exactly. */ |
| 35 | export const REDIRECT_PORTS = [53682, 53683, 53684, 53685, 53686]; |
| 36 | export const redirectUri = (port: number) => `http://127.0.0.1:${port}/callback`; |
| 37 | |
| 38 | export interface ServerMeta { |
| 39 | resource: string; |
| 40 | issuer: string; |
| 41 | authorizationEndpoint: string; |
| 42 | tokenEndpoint: string; |
| 43 | registrationEndpoint?: string; |
| 44 | revocationEndpoint?: string; |
| 45 | scopes: string[]; |
| 46 | } |
| 47 | |
| 48 | export interface Tokens { |
| 49 | access: string; |
| 50 | refresh?: string; |
| 51 | /** Epoch milliseconds. */ |
| 52 | expiresAt: number; |
| 53 | scope?: string; |
| 54 | } |
| 55 | |
| 56 | const MAX_DOC = 100_000; |
| 57 | |
| 58 | /** https anywhere; plain http only to this machine (a server under test). Nothing else may be asked for a token. */ |
| 59 | export function assertSafeEndpoint(u: string, what: string): URL { |
| 60 | let url: URL; |
| 61 | try { |
| 62 | url = new URL(u); |
| 63 | } catch { |
| 64 | throw new OAuthError("unsafe", `${what} is not an address`); |
| 65 | } |
| 66 | const loop = url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]"; |
| 67 | if (url.username || url.password || !(url.protocol === "https:" || (url.protocol === "http:" && loop))) throw new OAuthError("unsafe", `${what} must be https (or http to this machine): ${url.origin}`); |
| 68 | return url; |
| 69 | } |
| 70 | |
| 71 | async function getJson(f: Fetch, url: string, what: string): Promise<Record<string, unknown>> { |
| 72 | assertSafeEndpoint(url, what); |
| 73 | let res; |
| 74 | try { |
| 75 | res = await f(url, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(15_000) }); |
| 76 | } catch (e) { |
| 77 | throw new OAuthError("discovery", `could not reach ${new URL(url).host} for ${what}: ${(e as Error).message}`); |
| 78 | } |
| 79 | if (!res.ok) throw new OAuthError("discovery", `${what} answered ${res.status}`); |
| 80 | const text = await res.text(); |
| 81 | if (text.length > MAX_DOC) throw new OAuthError("discovery", `${what} is too large`); |
| 82 | try { |
| 83 | const j = JSON.parse(text) as unknown; |
| 84 | if (j && typeof j === "object" && !Array.isArray(j)) return j as Record<string, unknown>; |
| 85 | } catch { |
| 86 | /* fall through */ |
| 87 | } |
| 88 | throw new OAuthError("discovery", `${what} is not a JSON object`); |
| 89 | } |
| 90 | |
| 91 | const str = (v: unknown): string | undefined => (typeof v === "string" && v ? v : undefined); |
| 92 | |
| 93 | /** Find the authorization server of an MCP server, and its endpoints. */ |
| 94 | export async function discover(mcpUrl: string, f: Fetch): Promise<ServerMeta> { |
| 95 | const base = assertSafeEndpoint(mcpUrl, "the server address"); |
| 96 | const path = base.pathname === "/" ? "" : base.pathname; |
| 97 | let prm: Record<string, unknown> | null = null; |
| 98 | for (const candidate of [`${base.origin}/.well-known/oauth-protected-resource${path}`, `${base.origin}/.well-known/oauth-protected-resource`]) { |
| 99 | try { |
| 100 | prm = await getJson(f, candidate, "the server's protected-resource document"); |
| 101 | break; |
| 102 | } catch (e) { |
| 103 | if (e instanceof OAuthError && e.code === "unsafe") throw e; |
| 104 | } |
| 105 | } |
| 106 | if (!prm) throw new OAuthError("discovery", `${base.host} does not publish how to sign in (no protected-resource document)`); |
| 107 | const servers = Array.isArray(prm.authorization_servers) ? prm.authorization_servers.filter((x): x is string => typeof x === "string") : []; |
| 108 | const issuer = servers[0] ?? base.origin; |
| 109 | const iss = assertSafeEndpoint(issuer, "the authorization server"); |
| 110 | const ipath = iss.pathname === "/" ? "" : iss.pathname; |
| 111 | let as: Record<string, unknown> | null = null; |
| 112 | for (const candidate of [`${iss.origin}/.well-known/oauth-authorization-server${ipath}`, `${iss.origin}/.well-known/openid-configuration${ipath}`]) { |
| 113 | try { |
| 114 | as = await getJson(f, candidate, "the authorization server's document"); |
| 115 | break; |
| 116 | } catch (e) { |
| 117 | if (e instanceof OAuthError && e.code === "unsafe") throw e; |
| 118 | } |
| 119 | } |
| 120 | if (!as) throw new OAuthError("discovery", `${iss.host} does not publish its sign-in endpoints`); |
| 121 | const authorizationEndpoint = str(as.authorization_endpoint); |
| 122 | const tokenEndpoint = str(as.token_endpoint); |
| 123 | if (!authorizationEndpoint || !tokenEndpoint) throw new OAuthError("discovery", "the authorization server did not name its endpoints"); |
| 124 | assertSafeEndpoint(authorizationEndpoint, "the authorization endpoint"); |
| 125 | assertSafeEndpoint(tokenEndpoint, "the token endpoint"); |
| 126 | const methods = Array.isArray(as.code_challenge_methods_supported) ? as.code_challenge_methods_supported : null; |
| 127 | if (methods && !methods.includes("S256")) throw new OAuthError("discovery", "the server does not support PKCE with S256"); |
| 128 | const reg = str(as.registration_endpoint); |
| 129 | const rev = str(as.revocation_endpoint); |
| 130 | if (reg) assertSafeEndpoint(reg, "the registration endpoint"); |
| 131 | if (rev) assertSafeEndpoint(rev, "the revocation endpoint"); |
| 132 | const scopes = Array.isArray(prm.scopes_supported) ? prm.scopes_supported.filter((x): x is string => typeof x === "string") : Array.isArray(as.scopes_supported) ? as.scopes_supported.filter((x): x is string => typeof x === "string") : []; |
| 133 | return { |
| 134 | resource: str(prm.resource) ?? mcpUrl, |
| 135 | issuer, |
| 136 | authorizationEndpoint, |
| 137 | tokenEndpoint, |
| 138 | ...(reg ? { registrationEndpoint: reg } : {}), |
| 139 | ...(rev ? { revocationEndpoint: rev } : {}), |
| 140 | scopes, |
| 141 | }; |
| 142 | } |
| 143 | |
| 144 | /** Register this app with the server (public client, loopback redirects). Returns the client id. */ |
| 145 | export async function register(meta: ServerMeta, f: Fetch, appName: string): Promise<string> { |
| 146 | if (!meta.registrationEndpoint) throw new OAuthError("registration", "this server does not offer registration, so there is no way to sign in without a client id"); |
| 147 | let res; |
| 148 | try { |
| 149 | res = await f(meta.registrationEndpoint, { |
| 150 | method: "POST", |
| 151 | headers: { "content-type": "application/json", accept: "application/json" }, |
| 152 | body: JSON.stringify({ |
| 153 | client_name: appName, |
| 154 | redirect_uris: REDIRECT_PORTS.map(redirectUri), |
| 155 | grant_types: ["authorization_code", "refresh_token"], |
| 156 | response_types: ["code"], |
| 157 | token_endpoint_auth_method: "none", |
| 158 | ...(meta.scopes.length ? { scope: meta.scopes.join(" ") } : {}), |
| 159 | }), |
| 160 | signal: AbortSignal.timeout(20_000), |
| 161 | }); |
| 162 | } catch (e) { |
| 163 | throw new OAuthError("registration", `could not register: ${(e as Error).message}`); |
| 164 | } |
| 165 | const text = await res.text(); |
| 166 | if (!res.ok) throw new OAuthError("registration", `registration was refused (${res.status})`); |
| 167 | let id: string | undefined; |
| 168 | try { |
| 169 | id = str((JSON.parse(text) as Record<string, unknown>).client_id); |
| 170 | } catch { |
| 171 | /* handled below */ |
| 172 | } |
| 173 | if (!id) throw new OAuthError("registration", "registration did not return a client id"); |
| 174 | return id; |
| 175 | } |
| 176 | |
| 177 | // ---- PKCE ---------------------------------------------------------------------------------------------------------- |
| 178 | |
| 179 | const b64url = (b: Buffer) => b.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); |
| 180 | export function newPkce(): { verifier: string; challenge: string } { |
| 181 | const verifier = b64url(randomBytes(48)); |
| 182 | return { verifier, challenge: b64url(createHash("sha256").update(verifier).digest()) }; |
| 183 | } |
| 184 | export const newState = () => b64url(randomBytes(24)); |
| 185 | |
| 186 | export function authorizeUrl(meta: ServerMeta, clientId: string, redirect: string, challenge: string, state: string): string { |
| 187 | const u = new URL(meta.authorizationEndpoint); |
| 188 | u.searchParams.set("response_type", "code"); |
| 189 | u.searchParams.set("client_id", clientId); |
| 190 | u.searchParams.set("redirect_uri", redirect); |
| 191 | u.searchParams.set("code_challenge", challenge); |
| 192 | u.searchParams.set("code_challenge_method", "S256"); |
| 193 | u.searchParams.set("state", state); |
| 194 | if (meta.scopes.length) u.searchParams.set("scope", meta.scopes.join(" ")); |
| 195 | u.searchParams.set("resource", meta.resource); |
| 196 | return u.href; |
| 197 | } |
| 198 | |
| 199 | // ---- the redirect listener --------------------------------------------------------------------------------------- |
| 200 | |
| 201 | export const DONE_PAGE = (ok: boolean) => |
| 202 | `<!doctype html><meta charset="utf-8"><title>${ok ? "Signed in" : "Not signed in"}</title><body style="font:16px system-ui;padding:48px;max-width:32em;margin:auto"><h2>${ok ? "You are signed in." : "Sign-in did not finish."}</h2><p>${ok ? "You can close this tab and go back to the browser." : "Go back to the browser and try again."}</p>`; |
| 203 | |
| 204 | export interface Callback { |
| 205 | port: number; |
| 206 | redirectUri: string; |
| 207 | /** Resolves with the code once the right redirect arrives; rejects on denial, timeout or cancel. */ |
| 208 | code: Promise<string>; |
| 209 | cancel(): void; |
| 210 | } |
| 211 | |
| 212 | /** Listen on 127.0.0.1 only, on the first free registered port. Wrong state or host is ignored, so a stray request cannot end the flow. */ |
| 213 | export async function listenForCode(state: string, opts: { timeoutMs?: number; ports?: number[] } = {}): Promise<Callback> { |
| 214 | const ports = opts.ports ?? REDIRECT_PORTS; |
| 215 | let server: Server | undefined; |
| 216 | let chosen = 0; |
| 217 | let resolveCode!: (c: string) => void; |
| 218 | let rejectCode!: (e: Error) => void; |
| 219 | const code = new Promise<string>((res, rej) => { |
| 220 | resolveCode = res; |
| 221 | rejectCode = rej; |
| 222 | }); |
| 223 | code.catch(() => {}); // the caller handles it; never an unhandled rejection |
| 224 | const stop = () => { |
| 225 | clearTimeout(timer); |
| 226 | server?.close(); |
| 227 | server?.closeAllConnections?.(); |
| 228 | }; |
| 229 | const timer: NodeJS.Timeout = setTimeout(() => { |
| 230 | stop(); |
| 231 | rejectCode(new OAuthError("timeout", "nobody approved the sign-in in time")); |
| 232 | }, opts.timeoutMs ?? 300_000); |
| 233 | for (const port of ports) { |
| 234 | const s = createServer((req, res) => { |
| 235 | const actual = (s.address() as AddressInfo).port; |
| 236 | const u = new URL(req.url ?? "/", `http://127.0.0.1:${actual}`); |
| 237 | const hostOk = req.headers.host === `127.0.0.1:${actual}` || req.headers.host === `localhost:${actual}`; |
| 238 | if (!hostOk || req.method !== "GET" || u.pathname !== "/callback") { |
| 239 | res.writeHead(404).end(); |
| 240 | return; |
| 241 | } |
| 242 | if (u.searchParams.get("state") !== state) { |
| 243 | res.writeHead(400, { "content-type": "text/html" }).end(DONE_PAGE(false)); |
| 244 | return; |
| 245 | } |
| 246 | const err = u.searchParams.get("error"); |
| 247 | const c = u.searchParams.get("code"); |
| 248 | res.writeHead(err || !c ? 400 : 200, { "content-type": "text/html", "cache-control": "no-store" }).end(DONE_PAGE(!err && !!c)); |
| 249 | stop(); |
| 250 | if (err) rejectCode(new OAuthError("denied", err === "access_denied" ? "sign-in was declined" : `the server refused the sign-in (${err.slice(0, 60)})`)); |
| 251 | else if (c) resolveCode(c); |
| 252 | else rejectCode(new OAuthError("denied", "the server sent no code")); |
| 253 | }); |
| 254 | const ok = await new Promise<boolean>((resolve) => { |
| 255 | s.once("error", () => resolve(false)); |
| 256 | s.listen(port, "127.0.0.1", () => resolve(true)); |
| 257 | }); |
| 258 | if (ok) { |
| 259 | server = s; |
| 260 | chosen = (s.address() as AddressInfo).port; // the same as `port`, except for port 0 (any free one), which tests use |
| 261 | break; |
| 262 | } |
| 263 | } |
| 264 | if (!server) { |
| 265 | clearTimeout(timer); |
| 266 | throw new OAuthError("no-port", `none of the ports ${ports[0]}–${ports[ports.length - 1]} is free for the sign-in redirect`); |
| 267 | } |
| 268 | return { port: chosen, redirectUri: redirectUri(chosen), code, cancel: () => (stop(), rejectCode(new OAuthError("denied", "sign-in was cancelled"))) }; |
| 269 | } |
| 270 | |
| 271 | // ---- tokens ------------------------------------------------------------------------------------------------------ |
| 272 | |
| 273 | async function tokenRequest(meta: ServerMeta, f: Fetch, params: Record<string, string>, code: "token" | "refresh", now: number): Promise<Tokens> { |
| 274 | let res; |
| 275 | try { |
| 276 | res = await f(meta.tokenEndpoint, { |
| 277 | method: "POST", |
| 278 | headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" }, |
| 279 | body: new URLSearchParams(params).toString(), |
| 280 | signal: AbortSignal.timeout(20_000), |
| 281 | }); |
| 282 | } catch (e) { |
| 283 | throw new OAuthError(code, `could not reach the token endpoint: ${(e as Error).message}`); |
| 284 | } |
| 285 | const text = await res.text(); |
| 286 | let j: Record<string, unknown> = {}; |
| 287 | try { |
| 288 | j = JSON.parse(text) as Record<string, unknown>; |
| 289 | } catch { |
| 290 | /* handled below */ |
| 291 | } |
| 292 | if (!res.ok) throw new OAuthError(code, `the server refused (${res.status}${typeof j.error === "string" ? `: ${j.error.slice(0, 60)}` : ""})`); |
| 293 | const access = str(j.access_token); |
| 294 | if (!access) throw new OAuthError(code, "the server returned no access token"); |
| 295 | const expires = typeof j.expires_in === "number" && j.expires_in > 0 ? j.expires_in : 3600; |
| 296 | return { access, ...(str(j.refresh_token) ? { refresh: str(j.refresh_token) as string } : {}), expiresAt: now + expires * 1000, ...(str(j.scope) ? { scope: str(j.scope) as string } : {}) }; |
| 297 | } |
| 298 | |
| 299 | export const exchangeCode = (meta: ServerMeta, f: Fetch, a: { clientId: string; code: string; verifier: string; redirect: string }, now = Date.now()) => |
| 300 | tokenRequest(meta, f, { grant_type: "authorization_code", code: a.code, redirect_uri: a.redirect, client_id: a.clientId, code_verifier: a.verifier, resource: meta.resource }, "token", now); |
| 301 | |
| 302 | /** A refresh may or may not return a new refresh token; when it does not, the old one stays good. */ |
| 303 | export async function refreshTokens(meta: ServerMeta, f: Fetch, a: { clientId: string; refresh: string }, now = Date.now()): Promise<Tokens> { |
| 304 | const t = await tokenRequest(meta, f, { grant_type: "refresh_token", refresh_token: a.refresh, client_id: a.clientId, resource: meta.resource }, "refresh", now); |
| 305 | return t.refresh ? t : { ...t, refresh: a.refresh }; |
| 306 | } |
| 307 | |
| 308 | /** Best effort: tell the server to forget a token. Never throws. */ |
| 309 | export async function revoke(meta: ServerMeta, f: Fetch, clientId: string, token: string): Promise<boolean> { |
| 310 | if (!meta.revocationEndpoint) return false; |
| 311 | try { |
| 312 | const res = await f(meta.revocationEndpoint, { |
| 313 | method: "POST", |
| 314 | headers: { "content-type": "application/x-www-form-urlencoded" }, |
| 315 | body: new URLSearchParams({ token, client_id: clientId }).toString(), |
| 316 | signal: AbortSignal.timeout(10_000), |
| 317 | }); |
| 318 | return res.ok; |
| 319 | } catch { |
| 320 | return false; |
| 321 | } |
| 322 | } |