Open History to see the last commit
1import { openrouterByok } from './byok'
2
3const AUTH_ORIGIN = 'https://openrouter.ai'
4const AUTH_PATH = '/auth'
5const KEYS_URL = `${AUTH_ORIGIN}/api/v1/auth/keys`
6const PENDING_STORAGE_KEY = 'byok:openrouter:pkce:v1'
7const VERIFIER_CHARS =
8 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'
9const SIGN_IN_TIMEOUT_MS = 10 * 60_000
10const SIGNED_IN_PAGE =
11 '<!doctype html><title>Signed in</title><p>You are signed in to OpenRouter. You can close this tab.</p>'
12const SIGN_IN_FAILED_PAGE =
13 '<!doctype html><title>Sign-in failed</title><p>OpenRouter sign-in failed. You can close this tab and try again.</p>'
14
15export type OpenRouterPkceChallengeMethod = 'S256'
16
17export interface OpenRouterPkcePending {
18 codeVerifier: string
19 codeChallengeMethod: OpenRouterPkceChallengeMethod
20 callbackUrl: string
21}
22
23export interface OpenRouterAuthUrlOptions {
24 callbackUrl: string
25 codeChallenge?: string
26 codeChallengeMethod?: OpenRouterPkceChallengeMethod
27}
28
29export interface StartOpenRouterPkceOptions {
30 callbackUrl?: string
31 navigate?: (url: string) => void
32}
33
34export interface ExchangeOpenRouterCodeOptions {
35 code: string
36 codeVerifier?: string
37 codeChallengeMethod?: OpenRouterPkceChallengeMethod
38 fetchImpl?: typeof fetch
39}
40
41export interface CompleteOpenRouterPkceFromUrlOptions {
42 url?: string
43 fetchImpl?: typeof fetch
44 clearPending?: boolean
45 cleanUrl?: boolean
46}
47
48export interface OpenRouterSignInOptions {
49 /** How long to wait for the browser to come back. Default: 10 minutes. */
50 timeoutMs?: number
51 fetchImpl?: typeof fetch
52}
53
54/**
55 * Duck-typed BYOK store. `ByokClient.update` matches this. The slug is always
56 * {@link openrouterByok.id}.
57 */
58export interface OpenRouterByokStore {
59 update: (provider: string, key: string) => void | Promise<void>
60}
61
62function getSessionStorage(): Storage | null {
63 if (typeof globalThis.sessionStorage === 'undefined') return null
64 return globalThis.sessionStorage
65}
66
67function base64UrlEncode(bytes: Uint8Array): string {
68 let binary = ''
69 for (const byte of bytes) {
70 binary += String.fromCharCode(byte)
71 }
72 const base64 =
73 typeof btoa === 'function'
74 ? btoa(binary)
75 : Buffer.from(bytes).toString('base64')
76 return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
77}
78
79export function generateCodeVerifier(length = 64): string {
80 const size = Math.min(128, Math.max(43, length))
81 const bytes = crypto.getRandomValues(new Uint8Array(size))
82 let out = ''
83 for (const byte of bytes) {
84 const ch = VERIFIER_CHARS[byte % VERIFIER_CHARS.length]
85 out += ch ?? 'A'
86 }
87 return out
88}
89
90export async function createS256CodeChallenge(
91 codeVerifier: string,
92): Promise<string> {
93 const digest = await crypto.subtle.digest(
94 'SHA-256',
95 new TextEncoder().encode(codeVerifier),
96 )
97 return base64UrlEncode(new Uint8Array(digest))
98}
99
100export function buildOpenRouterAuthUrl(
101 options: OpenRouterAuthUrlOptions,
102): string {
103 const url = new URL(AUTH_PATH, AUTH_ORIGIN)
104 url.searchParams.set('callback_url', options.callbackUrl)
105 if (options.codeChallenge) {
106 url.searchParams.set('code_challenge', options.codeChallenge)
107 url.searchParams.set(
108 'code_challenge_method',
109 options.codeChallengeMethod ?? 'S256',
110 )
111 }
112 return url.toString()
113}
114
115export function storeOpenRouterPkcePending(
116 pending: OpenRouterPkcePending,
117): void {
118 getSessionStorage()?.setItem(PENDING_STORAGE_KEY, JSON.stringify(pending))
119}
120
121export function loadOpenRouterPkcePending(): OpenRouterPkcePending | null {
122 const raw = getSessionStorage()?.getItem(PENDING_STORAGE_KEY)
123 if (!raw) return null
124 try {
125 const parsed: unknown = JSON.parse(raw)
126 if (typeof parsed !== 'object' || parsed === null) return null
127 if (!('codeVerifier' in parsed) || !('codeChallengeMethod' in parsed)) {
128 return null
129 }
130 if (!('callbackUrl' in parsed)) return null
131 const { codeVerifier, codeChallengeMethod, callbackUrl } = parsed
132 if (typeof codeVerifier !== 'string') return null
133 if (codeChallengeMethod !== 'S256') return null
134 if (typeof callbackUrl !== 'string') return null
135 return { codeVerifier, codeChallengeMethod, callbackUrl }
136 } catch {
137 return null
138 }
139}
140
141export function clearOpenRouterPkcePending(): void {
142 getSessionStorage()?.removeItem(PENDING_STORAGE_KEY)
143}
144
145export function defaultOpenRouterCallbackUrl(): string {
146 if (typeof globalThis.location === 'undefined') return ''
147 return `${globalThis.location.origin}${globalThis.location.pathname}`
148}
149
150export async function startOpenRouterPkceLogin(
151 options: StartOpenRouterPkceOptions = {},
152): Promise<void> {
153 const callbackUrl = options.callbackUrl ?? defaultOpenRouterCallbackUrl()
154 if (!callbackUrl) {
155 throw new Error('OpenRouter PKCE login requires a callbackUrl')
156 }
157 const codeVerifier = generateCodeVerifier()
158 const codeChallenge = await createS256CodeChallenge(codeVerifier)
159 storeOpenRouterPkcePending({
160 codeVerifier,
161 codeChallengeMethod: 'S256',
162 callbackUrl,
163 })
164 const authUrl = buildOpenRouterAuthUrl({
165 callbackUrl,
166 codeChallenge,
167 codeChallengeMethod: 'S256',
168 })
169 const navigate =
170 options.navigate ??
171 ((url) => {
172 globalThis.location.assign(url)
173 })
174 navigate(authUrl)
175}
176
177export async function exchangeOpenRouterCode(
178 options: ExchangeOpenRouterCodeOptions,
179): Promise<string> {
180 const fetchImpl = options.fetchImpl ?? fetch
181 const body: Record<string, string> = { code: options.code }
182 if (options.codeVerifier) {
183 body.code_verifier = options.codeVerifier
184 if (options.codeChallengeMethod) {
185 body.code_challenge_method = options.codeChallengeMethod
186 }
187 }
188 const response = await fetchImpl(KEYS_URL, {
189 method: 'POST',
190 headers: { 'content-type': 'application/json' },
191 body: JSON.stringify(body),
192 })
193 if (!response.ok) {
194 let detail = `${response.status} ${response.statusText}`
195 try {
196 const err: unknown = await response.json()
197 if (typeof err === 'object' && err !== null && 'error' in err) {
198 detail = String(err.error)
199 }
200 } catch {
201 // keep status text
202 }
203 throw new Error(`OpenRouter PKCE exchange failed: ${detail}`)
204 }
205 const data: unknown = await response.json()
206 if (
207 typeof data !== 'object' ||
208 data === null ||
209 !('key' in data) ||
210 typeof data.key !== 'string' ||
211 data.key.length === 0
212 ) {
213 throw new Error('OpenRouter PKCE exchange returned no key')
214 }
215 return data.key
216}
217
218export function stripOpenRouterCodeFromUrl(href?: string): void {
219 if (typeof globalThis.history === 'undefined') return
220 const base = href ?? globalThis.location.href
221 const url = new URL(base)
222 if (!url.searchParams.has('code')) return
223 url.searchParams.delete('code')
224 const next = `${url.pathname}${url.search}${url.hash}`
225 globalThis.history.replaceState({}, '', next)
226}
227
228export async function completeOpenRouterPkceFromUrl(
229 options: CompleteOpenRouterPkceFromUrlOptions = {},
230): Promise<string | null> {
231 const href =
232 options.url ??
233 (typeof globalThis.location !== 'undefined' ? globalThis.location.href : '')
234 if (!href) return null
235 const code = new URL(href).searchParams.get('code')
236 if (!code) return null
237 const pending = loadOpenRouterPkcePending()
238 if (!pending) {
239 throw new Error(
240 'OpenRouter authorization code present but PKCE session expired — try signing in again',
241 )
242 }
243 const key = await exchangeOpenRouterCode({
244 code,
245 codeVerifier: pending.codeVerifier,
246 codeChallengeMethod: pending.codeChallengeMethod,
247 fetchImpl: options.fetchImpl,
248 })
249 if (options.clearPending !== false) clearOpenRouterPkcePending()
250 if (options.cleanUrl !== false) stripOpenRouterCodeFromUrl(href)
251 return key
252}
253
254/**
255 * Finish the OpenRouter PKCE callback and save the key under
256 * {@link openrouterByok.id}.
257 */
258export async function completeOpenRouterPkceIntoByok(
259 byok: OpenRouterByokStore,
260 options: CompleteOpenRouterPkceFromUrlOptions = {},
261): Promise<string | null> {
262 const key = await completeOpenRouterPkceFromUrl(options)
263 if (!key) return null
264 await byok.update(openrouterByok.id, key)
265 return key
266}
267
268/**
269 * OpenRouter sign-in for a local app, such as a CLI. The user signs in with a
270 * browser and the app gets an API key (PKCE with S256), so nobody copies a
271 * key by hand.
272 *
273 * The returned `signIn` starts a one-time listener on `127.0.0.1`, calls
274 * `open` with the OpenRouter sign-in URL, and waits for the browser to come
275 * back. Then it trades the code for a key and resolves with the key. The
276 * listener closes when `signIn` settles. A different callback path is ignored.
277 * `signIn` rejects when that callback has no code, when the key exchange
278 * fails, after `timeoutMs`, or when `signal` aborts.
279 *
280 * `node:http` loads only when `signIn` runs, so this module stays safe to
281 * import in a browser.
282 *
283 * @example
284 * const signIn = openrouterSignIn()
285 * const key = await signIn({ open: (url) => console.log(`Open ${url}`) })
286 */
287export function openrouterSignIn(
288 options: OpenRouterSignInOptions = {},
289): (ctx: {
290 open: (url: string) => void | Promise<void>
291 signal?: AbortSignal
292}) => Promise<string> {
293 return async (ctx) => {
294 const { createServer } = await import('node:http')
295 const codeVerifier = generateCodeVerifier()
296 const codeChallenge = await createS256CodeChallenge(codeVerifier)
297 // The state goes in the callback path, so only our own redirect matches.
298 const state = base64UrlEncode(crypto.getRandomValues(new Uint8Array(16)))
299 const server = createServer()
300 // Aborts the token POST and the caller's abort listener when `signIn` ends.
301 const settled = new AbortController()
302 const fetchSignal =
303 ctx.signal === undefined
304 ? settled.signal
305 : AbortSignal.any([settled.signal, ctx.signal])
306 const fetchImpl: typeof fetch = (input, init) =>
307 (options.fetchImpl ?? fetch)(input, { ...init, signal: fetchSignal })
308 let done = false
309 try {
310 await new Promise<void>((resolve, reject) => {
311 server.once('error', reject)
312 server.listen(0, '127.0.0.1', () => {
313 server.off('error', reject)
314 resolve()
315 })
316 })
317 const address = server.address()
318 if (address === null || typeof address !== 'object') {
319 throw new Error('OpenRouter sign-in failed to bind a TCP port.')
320 }
321 const { port } = address
322 const callbackPath = `/callback/${state}`
323 const callbackUrl = `http://127.0.0.1:${port}${callbackPath}`
324 return await new Promise<string>((resolve, reject) => {
325 const settle = (finish: () => void) => {
326 if (done) return
327 done = true
328 finish()
329 }
330 const { signal } = ctx
331 if (signal?.aborted) {
332 settle(() => reject(signal.reason))
333 return
334 }
335 signal?.addEventListener(
336 'abort',
337 () => settle(() => reject(signal.reason)),
338 { signal: settled.signal },
339 )
340 const timer = setTimeout(
341 () =>
342 settle(() => reject(new Error('OpenRouter sign-in timed out.'))),
343 options.timeoutMs ?? SIGN_IN_TIMEOUT_MS,
344 )
345 settled.signal.addEventListener('abort', () => clearTimeout(timer))
346 let answered = false
347 server.on('request', (req, res) => {
348 const url = new URL(req.url ?? '/', callbackUrl)
349 // A wrong path, a repeat, or a late request after sign-in ended.
350 if (url.pathname !== callbackPath || answered || done) {
351 res.writeHead(404).end()
352 return
353 }
354 answered = true
355 const page = (signedIn: boolean) => {
356 try {
357 res
358 .writeHead(signedIn ? 200 : 400, {
359 'content-type': 'text/html; charset=utf-8',
360 // The browser does not keep the connection, so the listener can close.
361 connection: 'close',
362 })
363 .end(signedIn ? SIGNED_IN_PAGE : SIGN_IN_FAILED_PAGE)
364 } catch {
365 // The listener may already be closing.
366 }
367 }
368 const code = url.searchParams.get('code')
369 if (!code) {
370 page(false)
371 settle(() =>
372 reject(
373 new Error(
374 'OpenRouter sign-in failed: the callback has no code.',
375 ),
376 ),
377 )
378 return
379 }
380 // The wait for the browser is over. A slow exchange still returns the key.
381 clearTimeout(timer)
382 exchangeOpenRouterCode({
383 code,
384 codeVerifier,
385 codeChallengeMethod: 'S256',
386 fetchImpl,
387 }).then(
388 (key) => {
389 if (done) return
390 page(true)
391 settle(() => resolve(key))
392 },
393 (error: unknown) => {
394 if (done) return
395 page(false)
396 settle(() => reject(error))
397 },
398 )
399 })
400 Promise.resolve(
401 ctx.open(
402 buildOpenRouterAuthUrl({
403 callbackUrl,
404 codeChallenge,
405 codeChallengeMethod: 'S256',
406 }),
407 ),
408 ).catch((error: unknown) => {
409 settle(() => reject(error))
410 })
411 })
412 } finally {
413 settled.abort()
414 server.close()
415 server.closeIdleConnections()
416 }
417 }
418}