{"version":3,"file":"openrouter.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/openrouter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AA6RvF,eAAO,MAAM,eAAe,EAAE,SAU7B,CAAC","sourcesContent":["/**\n * OpenRouter OAuth PKCE flow.\n *\n * OpenRouter exchanges an authorization code for a permanent, user-controlled\n * API key rather than an expiring access/refresh token pair. The callback is\n * handled by a one-shot loopback server on an ephemeral port, raced against a\n * manual prompt so remote/headless sessions can paste the redirect URL when\n * the browser cannot reach the loopback server.\n *\n * NOTE: This module uses Node.js http.createServer for the OAuth callback server.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport { createServer, type Server, type ServerResponse } from \"node:http\";\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst AUTHORIZE_URL = \"https://openrouter.ai/auth\";\nconst TOKEN_URL = \"https://openrouter.ai/api/v1/auth/keys\";\nconst LOGIN_TIMEOUT_MS = 5 * 60 * 1000;\nconst TOKEN_EXCHANGE_TIMEOUT_MS = 30_000;\n\nfunction getCallbackHost(): string {\n\treturn getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\n}\n\ntype JsonObject = Record<string, unknown>;\n\ntype OpenRouterCallbackServer = {\n\tcallbackUrl: string;\n\t/** Stop listening and release timers without settling `waitForCredential`. */\n\tclose: () => void;\n\t/** Hand the login over to manual code entry unless a callback already claimed the exchange. */\n\tcancelWait: () => void;\n\t/**\n\t * Resolves with the credential once a browser callback completes the key\n\t * exchange, or with null once `cancelWait` hands the login over to manual\n\t * code entry. Rejects on timeout, cancellation, or a failed exchange.\n\t */\n\twaitForCredential: () => Promise<OAuthCredential | null>;\n};\n\nfunction sendHtml(response: ServerResponse, status: number, html: string): void {\n\tresponse.statusCode = status;\n\tresponse.setHeader(\"content-type\", \"text/html; charset=utf-8\");\n\tresponse.setHeader(\"cache-control\", \"no-store\");\n\tresponse.end(html);\n}\n\nfunction parseAuthorizationInput(input: string): string | undefined {\n\tconst value = input.trim();\n\tif (!value) return undefined;\n\n\ttry {\n\t\treturn new URL(value).searchParams.get(\"code\") ?? undefined;\n\t} catch {\n\t\t// not a URL\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\treturn new URLSearchParams(value).get(\"code\") ?? undefined;\n\t}\n\n\treturn value;\n}\n\nfunction errorDetail(body: JsonObject): string | undefined {\n\tif (typeof body.error_description === \"string\") return body.error_description;\n\tif (typeof body.message === \"string\") return body.message;\n\tif (typeof body.error === \"string\") return body.error;\n\tif (body.error && typeof body.error === \"object\" && !Array.isArray(body.error)) {\n\t\tconst message = (body.error as JsonObject).message;\n\t\tif (typeof message === \"string\") return message;\n\t}\n\treturn undefined;\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tif (signal.aborted) throw new Error(\"Login cancelled\");\n\tconst controller = new AbortController();\n\tconst onAbort = () => controller.abort(signal.reason);\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\tconst timeout = setTimeout(\n\t\t() => controller.abort(new Error(\"OpenRouter OAuth token exchange timed out\")),\n\t\tTOKEN_EXCHANGE_TIMEOUT_MS,\n\t);\n\n\tlet response: Response;\n\tlet body: JsonObject = {};\n\ttry {\n\t\tresponse = await fetch(TOKEN_URL, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({ code, code_verifier: verifier, code_challenge_method: \"S256\" }),\n\t\t\tsignal: controller.signal,\n\t\t});\n\t\ttry {\n\t\t\tconst parsed = (await response.json()) as unknown;\n\t\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) body = parsed as JsonObject;\n\t\t} catch {\n\t\t\tif (response.ok) throw new Error(\"OpenRouter OAuth returned invalid JSON\");\n\t\t}\n\t} catch (error) {\n\t\tif (signal.aborted) throw new Error(\"Login cancelled\");\n\t\tif (controller.signal.aborted) throw new Error(\"OpenRouter OAuth token exchange timed out\");\n\t\tthrow error;\n\t} finally {\n\t\tclearTimeout(timeout);\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n\n\tif (!response.ok) {\n\t\tconst detail = errorDetail(body);\n\t\tthrow new Error(`OpenRouter OAuth key exchange failed (HTTP ${response.status})${detail ? `: ${detail}` : \"\"}`);\n\t}\n\n\tif (typeof body.key !== \"string\" || body.key.length === 0) {\n\t\tthrow new Error('OpenRouter OAuth response carries no \"key\"');\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess: body.key,\n\t\trefresh: \"\",\n\t\texpires: Number.MAX_SAFE_INTEGER,\n\t};\n}\n\nasync function startCallbackServer(\n\tcallbackPath: string,\n\tverifier: string,\n\tsignal: AbortSignal,\n): Promise<OpenRouterCallbackServer> {\n\tif (signal.aborted) throw new Error(\"Login cancelled\");\n\tconst callbackHost = getCallbackHost();\n\tlet resolveCredential: (credential: OAuthCredential | null) => void = () => {};\n\tlet rejectCredential: (error: Error) => void = () => {};\n\tconst credential = new Promise<OAuthCredential | null>((resolve, reject) => {\n\t\tresolveCredential = resolve;\n\t\trejectCredential = reject;\n\t});\n\n\tlet server: Server;\n\tlet claimed = false;\n\tlet settled = false;\n\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\tlet onAbort: (() => void) | undefined;\n\n\tconst close = (): void => {\n\t\tif (timeout) clearTimeout(timeout);\n\t\tif (onAbort) signal.removeEventListener(\"abort\", onAbort);\n\t\tserver.close();\n\t};\n\n\tconst finish = (result: { credential: OAuthCredential | null } | { error: Error }): void => {\n\t\tif (settled) return;\n\t\tsettled = true;\n\t\tclose();\n\t\tif (\"credential\" in result) resolveCredential(result.credential);\n\t\telse rejectCredential(result.error);\n\t};\n\n\tserver = createServer((request, response) => {\n\t\tvoid (async () => {\n\t\t\tconst requestUrl = new URL(request.url ?? \"/\", `http://${callbackHost}`);\n\t\t\tif (request.method !== \"GET\" || requestUrl.pathname !== callbackPath) {\n\t\t\t\tsendHtml(response, 404, oauthErrorHtml(\"OAuth callback route not found.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (claimed || settled) {\n\t\t\t\tsendHtml(response, 409, oauthErrorHtml(\"This OAuth callback has already been used.\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst oauthError = requestUrl.searchParams.get(\"error\");\n\t\t\tif (oauthError) {\n\t\t\t\tconst description = requestUrl.searchParams.get(\"error_description\") ?? oauthError;\n\t\t\t\tsendHtml(response, 400, oauthErrorHtml(\"OpenRouter authorization was denied.\", description));\n\t\t\t\tfinish({ error: new Error(`OpenRouter authorization failed: ${description}`) });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst code = requestUrl.searchParams.get(\"code\");\n\t\t\tif (!code) {\n\t\t\t\tsendHtml(response, 400, oauthErrorHtml(\"OpenRouter returned no authorization code.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tclaimed = true;\n\n\t\t\ttry {\n\t\t\t\tconst result = await exchangeAuthorizationCode(code, verifier, signal);\n\t\t\t\tsendHtml(response, 200, oauthSuccessHtml(\"Signed in to OpenRouter. You may now close this page.\"));\n\t\t\t\tfinish({ credential: result });\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : \"Unknown token exchange error\";\n\t\t\t\tsendHtml(response, 502, oauthErrorHtml(\"OpenRouter key exchange failed.\", message));\n\t\t\t\tfinish({ error: error instanceof Error ? error : new Error(message) });\n\t\t\t}\n\t\t})();\n\t});\n\n\tawait new Promise<void>((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(0, callbackHost, () => {\n\t\t\tserver.removeListener(\"error\", reject);\n\t\t\tresolve();\n\t\t});\n\t});\n\n\tserver.on(\"error\", (error) => finish({ error }));\n\tonAbort = () => finish({ error: new Error(\"Login cancelled\") });\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\tif (signal.aborted) {\n\t\tclose();\n\t\tthrow new Error(\"Login cancelled\");\n\t}\n\ttimeout = setTimeout(() => finish({ error: new Error(\"OpenRouter OAuth login timed out\") }), LOGIN_TIMEOUT_MS);\n\n\tconst address = server.address();\n\tif (!address || typeof address === \"string\") {\n\t\tclose();\n\t\tthrow new Error(\"Could not determine the OpenRouter OAuth callback port\");\n\t}\n\n\treturn {\n\t\tcallbackUrl: `http://${callbackHost}:${address.port}${callbackPath}`,\n\t\tclose,\n\t\t// A claimed callback is already exchanging its code; let that exchange settle the login.\n\t\tcancelWait: () => {\n\t\t\tif (!claimed) finish({ credential: null });\n\t\t},\n\t\twaitForCredential: () => credential,\n\t};\n}\n\nasync function loginOpenRouter(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst callbackPath = `/oauth/callback/${crypto.randomUUID()}`;\n\tconst callback = await startCallbackServer(callbackPath, verifier, interaction.signal);\n\tconst manualAbort = new AbortController();\n\tlet manualInput: string | undefined;\n\tlet manualError: Error | undefined;\n\n\ttry {\n\t\tconst authorizeUrl = new URL(AUTHORIZE_URL);\n\t\tauthorizeUrl.search = new URLSearchParams({\n\t\t\tcallback_url: callback.callbackUrl,\n\t\t\tcode_challenge: challenge,\n\t\t\tcode_challenge_method: \"S256\",\n\t\t}).toString();\n\n\t\tinteraction.notify({\n\t\t\ttype: \"progress\",\n\t\t\tmessage: `Listening for OpenRouter OAuth callback on ${callback.callbackUrl}`,\n\t\t});\n\t\tinteraction.notify({\n\t\t\ttype: \"auth_url\",\n\t\t\turl: authorizeUrl.toString(),\n\t\t\tinstructions:\n\t\t\t\t\"Complete sign-in in your browser. If the browser is on another machine, paste the final redirect URL here.\",\n\t\t});\n\n\t\tconst manualPromise = interaction\n\t\t\t.prompt({\n\t\t\t\ttype: \"manual_code\",\n\t\t\t\tmessage: \"Complete sign-in in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\t\tplaceholder: callback.callbackUrl,\n\t\t\t\tsignal: manualAbort.signal,\n\t\t\t})\n\t\t\t.then((input) => {\n\t\t\t\tmanualInput = input;\n\t\t\t\tcallback.cancelWait();\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tmanualError = error instanceof Error ? error : new Error(String(error));\n\t\t\t\tcallback.cancelWait();\n\t\t\t});\n\n\t\tconst credential = await callback.waitForCredential();\n\t\tif (manualError) throw manualError;\n\t\tif (credential) return credential;\n\n\t\tawait manualPromise;\n\t\tif (manualError) throw manualError;\n\t\tconst code = manualInput ? parseAuthorizationInput(manualInput) : undefined;\n\t\tif (!code) throw new Error(\"Missing authorization code\");\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for an API key...\" });\n\t\treturn await exchangeAuthorizationCode(code, verifier, interaction.signal);\n\t} finally {\n\t\tmanualAbort.abort();\n\t\tcallback.close();\n\t}\n}\n\nexport const openRouterOAuth: OAuthAuth = {\n\tname: \"OpenRouter OAuth\",\n\tloginLabel: \"Sign in with OpenRouter\",\n\tlogin: loginOpenRouter,\n\tasync refresh(credential, _signal) {\n\t\treturn credential;\n\t},\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}