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-._~'
9
10export type OpenRouterPkceChallengeMethod = 'S256'
11
12export interface OpenRouterPkcePending {
13 codeVerifier: string
14 codeChallengeMethod: OpenRouterPkceChallengeMethod
15 callbackUrl: string
16}
17
18export interface OpenRouterAuthUrlOptions {
19 callbackUrl: string
20 codeChallenge?: string
21 codeChallengeMethod?: OpenRouterPkceChallengeMethod
22}
23
24export interface StartOpenRouterPkceOptions {
25 callbackUrl?: string
26 navigate?: (url: string) => void
27}
28
29export interface ExchangeOpenRouterCodeOptions {
30 code: string
31 codeVerifier?: string
32 codeChallengeMethod?: OpenRouterPkceChallengeMethod
33 fetchImpl?: typeof fetch
34}
35
36export interface CompleteOpenRouterPkceFromUrlOptions {
37 url?: string
38 fetchImpl?: typeof fetch
39 clearPending?: boolean
40 cleanUrl?: boolean
41}
42
43/**
44 * Duck-typed BYOK store. `ByokClient.update` matches this. The slug is always
45 * {@link openrouterByok.id}.
46 */
47export interface OpenRouterByokStore {
48 update: (provider: string, key: string) => void | Promise<void>
49}
50
51function getSessionStorage(): Storage | null {
52 if (typeof globalThis.sessionStorage === 'undefined') return null
53 return globalThis.sessionStorage
54}
55
56function base64UrlEncode(bytes: Uint8Array): string {
57 let binary = ''
58 for (const byte of bytes) {
59 binary += String.fromCharCode(byte)
60 }
61 const base64 =
62 typeof btoa === 'function'
63 ? btoa(binary)
64 : Buffer.from(bytes).toString('base64')
65 return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
66}
67
68export function generateCodeVerifier(length = 64): string {
69 const size = Math.min(128, Math.max(43, length))
70 const bytes = crypto.getRandomValues(new Uint8Array(size))
71 let out = ''
72 for (const byte of bytes) {
73 const ch = VERIFIER_CHARS[byte % VERIFIER_CHARS.length]
74 out += ch ?? 'A'
75 }
76 return out
77}
78
79export async function createS256CodeChallenge(
80 codeVerifier: string,
81): Promise<string> {
82 const digest = await crypto.subtle.digest(
83 'SHA-256',
84 new TextEncoder().encode(codeVerifier),
85 )
86 return base64UrlEncode(new Uint8Array(digest))
87}
88
89export function buildOpenRouterAuthUrl(
90 options: OpenRouterAuthUrlOptions,
91): string {
92 const url = new URL(AUTH_PATH, AUTH_ORIGIN)
93 url.searchParams.set('callback_url', options.callbackUrl)
94 if (options.codeChallenge) {
95 url.searchParams.set('code_challenge', options.codeChallenge)
96 url.searchParams.set(
97 'code_challenge_method',
98 options.codeChallengeMethod ?? 'S256',
99 )
100 }
101 return url.toString()
102}
103
104export function storeOpenRouterPkcePending(
105 pending: OpenRouterPkcePending,
106): void {
107 getSessionStorage()?.setItem(PENDING_STORAGE_KEY, JSON.stringify(pending))
108}
109
110export function loadOpenRouterPkcePending(): OpenRouterPkcePending | null {
111 const raw = getSessionStorage()?.getItem(PENDING_STORAGE_KEY)
112 if (!raw) return null
113 try {
114 const parsed: unknown = JSON.parse(raw)
115 if (typeof parsed !== 'object' || parsed === null) return null
116 if (!('codeVerifier' in parsed) || !('codeChallengeMethod' in parsed)) {
117 return null
118 }
119 if (!('callbackUrl' in parsed)) return null
120 const { codeVerifier, codeChallengeMethod, callbackUrl } = parsed
121 if (typeof codeVerifier !== 'string') return null
122 if (codeChallengeMethod !== 'S256') return null
123 if (typeof callbackUrl !== 'string') return null
124 return { codeVerifier, codeChallengeMethod, callbackUrl }
125 } catch {
126 return null
127 }
128}
129
130export function clearOpenRouterPkcePending(): void {
131 getSessionStorage()?.removeItem(PENDING_STORAGE_KEY)
132}
133
134export function defaultOpenRouterCallbackUrl(): string {
135 if (typeof globalThis.location === 'undefined') return ''
136 return `${globalThis.location.origin}${globalThis.location.pathname}`
137}
138
139export async function startOpenRouterPkceLogin(
140 options: StartOpenRouterPkceOptions = {},
141): Promise<void> {
142 const callbackUrl = options.callbackUrl ?? defaultOpenRouterCallbackUrl()
143 if (!callbackUrl) {
144 throw new Error('OpenRouter PKCE login requires a callbackUrl')
145 }
146 const codeVerifier = generateCodeVerifier()
147 const codeChallenge = await createS256CodeChallenge(codeVerifier)
148 storeOpenRouterPkcePending({
149 codeVerifier,
150 codeChallengeMethod: 'S256',
151 callbackUrl,
152 })
153 const authUrl = buildOpenRouterAuthUrl({
154 callbackUrl,
155 codeChallenge,
156 codeChallengeMethod: 'S256',
157 })
158 const navigate =
159 options.navigate ??
160 ((url) => {
161 globalThis.location.assign(url)
162 })
163 navigate(authUrl)
164}
165
166export async function exchangeOpenRouterCode(
167 options: ExchangeOpenRouterCodeOptions,
168): Promise<string> {
169 const fetchImpl = options.fetchImpl ?? fetch
170 const body: Record<string, string> = { code: options.code }
171 if (options.codeVerifier) {
172 body.code_verifier = options.codeVerifier
173 if (options.codeChallengeMethod) {
174 body.code_challenge_method = options.codeChallengeMethod
175 }
176 }
177 const response = await fetchImpl(KEYS_URL, {
178 method: 'POST',
179 headers: { 'content-type': 'application/json' },
180 body: JSON.stringify(body),
181 })
182 if (!response.ok) {
183 let detail = `${response.status} ${response.statusText}`
184 try {
185 const err: unknown = await response.json()
186 if (typeof err === 'object' && err !== null && 'error' in err) {
187 detail = String(err.error)
188 }
189 } catch {
190 // keep status text
191 }
192 throw new Error(`OpenRouter PKCE exchange failed: ${detail}`)
193 }
194 const data: unknown = await response.json()
195 if (
196 typeof data !== 'object' ||
197 data === null ||
198 !('key' in data) ||
199 typeof data.key !== 'string' ||
200 data.key.length === 0
201 ) {
202 throw new Error('OpenRouter PKCE exchange returned no key')
203 }
204 return data.key
205}
206
207export function stripOpenRouterCodeFromUrl(href?: string): void {
208 if (typeof globalThis.history === 'undefined') return
209 const base = href ?? globalThis.location.href
210 const url = new URL(base)
211 if (!url.searchParams.has('code')) return
212 url.searchParams.delete('code')
213 const next = `${url.pathname}${url.search}${url.hash}`
214 globalThis.history.replaceState({}, '', next)
215}
216
217export async function completeOpenRouterPkceFromUrl(
218 options: CompleteOpenRouterPkceFromUrlOptions = {},
219): Promise<string | null> {
220 const href =
221 options.url ??
222 (typeof globalThis.location !== 'undefined' ? globalThis.location.href : '')
223 if (!href) return null
224 const code = new URL(href).searchParams.get('code')
225 if (!code) return null
226 const pending = loadOpenRouterPkcePending()
227 if (!pending) {
228 throw new Error(
229 'OpenRouter authorization code present but PKCE session expired — try signing in again',
230 )
231 }
232 const key = await exchangeOpenRouterCode({
233 code,
234 codeVerifier: pending.codeVerifier,
235 codeChallengeMethod: pending.codeChallengeMethod,
236 fetchImpl: options.fetchImpl,
237 })
238 if (options.clearPending !== false) clearOpenRouterPkcePending()
239 if (options.cleanUrl !== false) stripOpenRouterCodeFromUrl(href)
240 return key
241}
242
243/**
244 * Finish the OpenRouter PKCE callback and save the key under
245 * {@link openrouterByok.id}.
246 */
247export async function completeOpenRouterPkceIntoByok(
248 byok: OpenRouterByokStore,
249 options: CompleteOpenRouterPkceFromUrlOptions = {},
250): Promise<string | null> {
251 const key = await completeOpenRouterPkceFromUrl(options)
252 if (!key) return null
253 await byok.update(openrouterByok.id, key)
254 return key
255}