Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

siwc.ts

463 lines14.3 KB

1import { openaiByok } from './byok'
2​
3/**
4 * Sign in with ChatGPT (SIWC) for BYOK. The user signs in with their ChatGPT
5 * account and the access token bills their ChatGPT plan instead of an API key.
6 *
7 * OpenAI allows this only for open-source and locally hosted apps, and only
8 * with a `http://127.0.0.1:<port>/auth/callback` redirect.
9 * https://developers.openai.com/siwc/token-sharing-open-source
10 *
11 * The access token goes into the `openai` BYOK slot, so the relay reads it
12 * like an API key. The refresh credential goes into a second slot that no
13 * send ever attaches, so the refresh token stays in the browser.
14 */
15​
16const ISSUER = 'https://auth.openai.com'
17const AUTHORIZE_URL = `${ISSUER}/api/accounts/authorize`
18const TOKEN_URL = `${ISSUER}/api/accounts/oauth/token`
19const RESOURCE = 'https://api.openai.com/v1'
20const SCOPE =
21 'openid profile email offline_access resource.invoke chatgpt.tokens.use.direct'
22const PLAN_SCOPE = 'chatgpt.tokens.use.direct'
23const DYNAMIC_CLIENT_ID = 'dynamic_agent_client'
24const CALLBACK_PATH = '/auth/callback'
25const PENDING_STORAGE_KEY = 'byok:openai:siwc:pending:v1'
26const HOST_STORAGE_KEY = 'byok:openai:siwc:host:v1'
27/** Keyring slot for the refresh credential. Never sent to the relay. */
28const CREDENTIAL_ID = 'openai-chatgpt'
29const REFRESH_SKEW_MS = 5 * 60 * 1000
30​
31/**
32 * Duck-typed BYOK store. `ByokClient` from `defineByok` matches this.
33 */
34export interface ChatGptByokStore {
35 keys: () => Record<string, string | undefined>
36 update: (provider: string, key: string) => void | Promise<void>
37 clear: (provider?: string) => void | Promise<void>
39​
40export interface StartChatGptSignInOptions {
41 /** Your app's name. OpenAI shows it on the consent screen. */
42 agentName: string
43 /**
44 * Defaults to `<origin>/auth/callback`, with `localhost` swapped for
45 * `127.0.0.1`. The host must be `127.0.0.1`.
46 */
47 redirectUri?: string
48 navigate?: (url: string) => void
50​
51export interface CompleteChatGptSignInOptions {
52 /** Defaults to `location.href`. */
53 url?: string
54 fetchImpl?: typeof fetch
55 navigate?: (url: string) => void
57​
58export interface RefreshChatGptSignInOptions {
59 fetchImpl?: typeof fetch
61​
62interface Pending {
63 state: string
64 nonce: string
65 codeVerifier: string
66 redirectUri: string
67 clientId: string
69​
70interface HostRecord {
71 hostId: string
72 clientId?: string
74​
75interface Credential {
76 clientId: string
77 refreshToken: string
78 expiresAt: number
80​
81/** A finished sign-in. Hold it in memory until you save it. */
82export interface ChatGptSignIn extends Credential {
83 accessToken: string
85​
86interface TokenResponse {
87 access_token: string
88 refresh_token: string
89 expires_in: number
90 scope: string
91 id_token?: string
93​
94function base64UrlEncode(bytes: Uint8Array): string {
95 let binary = ''
96 for (const byte of bytes) binary += String.fromCharCode(byte)
97 return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
99​
100function randomToken(): string {
101 return base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)))
103​
104async function s256(verifier: string): Promise<string> {
105 const digest = await crypto.subtle.digest(
106 'SHA-256',
107 new TextEncoder().encode(verifier),
108 )
109 return base64UrlEncode(new Uint8Array(digest))
111​
112function readJson(storage: Storage | undefined, key: string): unknown {
113 const raw = storage?.getItem(key)
114 if (!raw) return null
115 try {
116 return JSON.parse(raw)
117 } catch {
118 return null
119 }
121​
122function isRecord(value: unknown): value is Record<string, unknown> {
123 return typeof value === 'object' && value !== null
125​
126function readHost(): HostRecord {
127 const stored = readJson(globalThis.localStorage, HOST_STORAGE_KEY)
128 if (isRecord(stored) && typeof stored.hostId === 'string') {
129 return {
130 hostId: stored.hostId,
131 ...(typeof stored.clientId === 'string' && { clientId: stored.clientId }),
132 }
133 }
134 // One stable id per browser profile, created before the first sign-in.
135 const host = { hostId: `urn:uuid:${crypto.randomUUID()}` }
136 globalThis.localStorage.setItem(HOST_STORAGE_KEY, JSON.stringify(host))
137 return host
139​
140function readPending(): Pending | null {
141 const stored = readJson(globalThis.sessionStorage, PENDING_STORAGE_KEY)
142 if (!isRecord(stored)) return null
143 const { state, nonce, codeVerifier, redirectUri, clientId } = stored
144 if (
145 typeof state !== 'string' ||
146 typeof nonce !== 'string' ||
147 typeof codeVerifier !== 'string' ||
148 typeof redirectUri !== 'string' ||
149 typeof clientId !== 'string'
150 ) {
151 return null
152 }
153 return { state, nonce, codeVerifier, redirectUri, clientId }
155​
156function readCredential(store: ChatGptByokStore): Credential | null {
157 const raw = store.keys()[CREDENTIAL_ID]
158 if (!raw) return null
159 try {
160 const parsed: unknown = JSON.parse(raw)
161 if (
162 isRecord(parsed) &&
163 typeof parsed.clientId === 'string' &&
164 typeof parsed.refreshToken === 'string' &&
165 typeof parsed.expiresAt === 'number'
166 ) {
167 return {
168 clientId: parsed.clientId,
169 refreshToken: parsed.refreshToken,
170 expiresAt: parsed.expiresAt,
171 }
172 }
173 } catch {
174 // fall through
175 }
176 return null
178​
179function decodeJwtPayload(token: string): Record<string, unknown> {
180 const part = token.split('.')[1]
181 if (!part) throw new Error('ChatGPT sign-in returned a malformed ID token')
182 const base64 = part.replace(/-/g, '+').replace(/_/g, '/')
183 const parsed: unknown = JSON.parse(atob(base64))
184 if (!isRecord(parsed)) {
185 throw new Error('ChatGPT sign-in returned a malformed ID token')
186 }
187 return parsed
189​
190/**
191 * The ID token comes straight from the token endpoint over TLS, so OIDC Core
192 * 3.1.3.7 lets us skip the signature check. We still bind it to this attempt.
193 */
194function checkIdToken(idToken: string, clientId: string, nonce: string): void {
195 const claims = decodeJwtPayload(idToken)
196 const aud = claims.aud
197 const audOk = Array.isArray(aud) ? aud.includes(clientId) : aud === clientId
198 if (claims.iss !== ISSUER || !audOk || claims.nonce !== nonce) {
199 throw new Error('ChatGPT sign-in returned an ID token for another request')
200 }
202​
203class TokenRequestError extends Error {
204 constructor(
205 message: string,
206 readonly status: number,
207 ) {
208 super(message)
209 }
211​
212async function postToken(
213 body: Record<string, string>,
214 fetchImpl: typeof fetch,
215): Promise<TokenResponse> {
216 const response = await fetchImpl(TOKEN_URL, {
217 method: 'POST',
218 headers: { 'content-type': 'application/x-www-form-urlencoded' },
219 body: new URLSearchParams({ ...body, resource: RESOURCE }).toString(),
220 })
221 const data: unknown = await response.json().catch(() => null)
222 if (!response.ok) {
223 const detail =
224 isRecord(data) && typeof data.error === 'string'
225 ? data.error
226 : `${response.status} ${response.statusText}`
227 throw new TokenRequestError(
228 `ChatGPT token request failed: ${detail}`,
229 response.status,
230 )
231 }
232 if (
233 !isRecord(data) ||
234 typeof data.access_token !== 'string' ||
235 typeof data.refresh_token !== 'string' ||
236 typeof data.expires_in !== 'number'
237 ) {
238 throw new Error('ChatGPT token response is missing tokens')
239 }
240 return {
241 access_token: data.access_token,
242 refresh_token: data.refresh_token,
243 expires_in: data.expires_in,
244 scope: typeof data.scope === 'string' ? data.scope : '',
245 ...(typeof data.id_token === 'string' && { id_token: data.id_token }),
246 }
248​
249function toSignIn(clientId: string, tokens: TokenResponse): ChatGptSignIn {
250 return {
251 clientId,
252 accessToken: tokens.access_token,
253 refreshToken: tokens.refresh_token,
254 expiresAt: Date.now() + tokens.expires_in * 1000,
255 }
257​
258/**
259 * Open the ChatGPT consent page. Call it from a click handler.
260 *
261 * The first sign-in registers a client for your app. Later sign-ins reuse the
262 * client id saved in `localStorage`.
263 *
264 * ChatGPT accepts only a `127.0.0.1` redirect. On `localhost`, the redirect
265 * goes to `127.0.0.1` on the same port, and {@link completeChatGptSignIn}
266 * sends the browser back to `localhost` to finish.
267 */
268export async function startChatGptSignIn(
269 options: StartChatGptSignInOptions,
270): Promise<void> {
271 const redirect = new URL(
272 options.redirectUri ?? new URL(CALLBACK_PATH, globalThis.location.origin),
273 )
274 if (!options.redirectUri && redirect.hostname === 'localhost') {
275 redirect.hostname = '127.0.0.1'
276 }
277 const redirectUri = redirect.toString()
278 if (
279 redirect.hostname !== '127.0.0.1' ||
280 redirect.pathname !== CALLBACK_PATH
281 ) {
282 throw new Error(
283 `Sign in with ChatGPT needs a http://127.0.0.1:<port>${CALLBACK_PATH} redirect. Run the app on localhost or 127.0.0.1.`,
284 )
285 }
286 const host = readHost()
287 const clientId = host.clientId ?? DYNAMIC_CLIENT_ID
288 const pending: Pending = {
289 state: randomToken(),
290 nonce: randomToken(),
291 codeVerifier: randomToken(),
292 redirectUri,
293 clientId,
294 }
295 globalThis.sessionStorage.setItem(
296 PENDING_STORAGE_KEY,
297 JSON.stringify(pending),
298 )
299​
300 const url = new URL(AUTHORIZE_URL)
301 url.searchParams.set('client_id', clientId)
302 if (clientId === DYNAMIC_CLIENT_ID) {
303 url.searchParams.set('agent_name_hint', options.agentName)
304 }
305 url.searchParams.set('ext_agent_host_id', host.hostId)
306 url.searchParams.set('response_type', 'code')
307 url.searchParams.set('redirect_uri', redirectUri)
308 url.searchParams.set('scope', SCOPE)
309 url.searchParams.set('resource', RESOURCE)
310 url.searchParams.set('state', pending.state)
311 url.searchParams.set('nonce', pending.nonce)
312 url.searchParams.set('code_challenge_method', 'S256')
313 url.searchParams.set('code_challenge', await s256(pending.codeVerifier))
314​
315 const navigate =
316 options.navigate ?? ((next: string) => globalThis.location.assign(next))
317 navigate(url.toString())
319​
320/**
321 * Finish the sign-in on your `/auth/callback` page: check the callback and
322 * exchange the code. Pass the result to {@link saveChatGptSignIn}.
323 *
324 * Returns `null` when the URL is not a sign-in callback. Also returns `null`
325 * when the sign-in started on `localhost`: it then reopens this URL there.
326 */
327export async function completeChatGptSignIn(
328 options: CompleteChatGptSignInOptions = {},
329): Promise<ChatGptSignIn | null> {
330 const here = new URL(options.url ?? globalThis.location.href)
331 const params = here.searchParams
332 const state = params.get('state')
333 if (!state || (!params.has('code') && !params.has('error'))) return null
334​
335 const pending = readPending()
336 if (!pending && here.hostname === '127.0.0.1') {
337 // Started on localhost. Its sessionStorage holds the PKCE verifier.
338 here.hostname = 'localhost'
339 const navigate =
340 options.navigate ?? ((next: string) => globalThis.location.replace(next))
341 navigate(here.toString())
342 return null
343 }
344 if (!pending || pending.state !== state) {
345 throw new Error('ChatGPT sign-in expired or did not start here. Try again.')
346 }
347 globalThis.sessionStorage.removeItem(PENDING_STORAGE_KEY)
348​
349 const error = params.get('error')
350 if (error) {
351 const description = params.get('error_description')
352 throw new Error(
353 `ChatGPT sign-in failed: ${description ? `${error}: ${description}` : error}`,
354 )
355 }
356​
357 const returnedClientId = params.get('client_id')
358 let clientId = pending.clientId
359 if (clientId === DYNAMIC_CLIENT_ID) {
360 if (!returnedClientId) {
361 throw new Error('ChatGPT sign-in did not return a client id')
362 }
363 clientId = returnedClientId
364 } else if (returnedClientId && returnedClientId !== clientId) {
365 throw new Error('ChatGPT sign-in returned a different client id')
366 }
367​
368 const tokens = await postToken(
369 {
370 grant_type: 'authorization_code',
371 client_id: clientId,
372 code: params.get('code') ?? '',
373 code_verifier: pending.codeVerifier,
374 redirect_uri: pending.redirectUri,
375 },
376 options.fetchImpl ?? fetch,
377 )
378 if (!tokens.id_token) throw new Error('ChatGPT sign-in returned no ID token')
379 checkIdToken(tokens.id_token, clientId, pending.nonce)
380 if (!tokens.scope.split(' ').includes(PLAN_SCOPE)) {
381 throw new Error('ChatGPT plan use was not allowed for this app')
382 }
383​
384 globalThis.localStorage.setItem(
385 HOST_STORAGE_KEY,
386 JSON.stringify({ ...readHost(), clientId }),
387 )
388 return toSignIn(clientId, tokens)
390​
391/**
392 * Save a sign-in into the BYOK keyring: the access token under `openai`, the
393 * refresh credential in a slot that no send attaches. With passkey storage,
394 * call it from a click handler, before any other `await`.
395 */
396export async function saveChatGptSignIn(
397 store: ChatGptByokStore,
398 signIn: ChatGptSignIn,
399): Promise<void> {
400 const { accessToken, ...credential } = signIn
401 await store.update(CREDENTIAL_ID, JSON.stringify(credential))
402 await store.update(openaiByok.id, accessToken)
404​
405const inFlight = new WeakMap<ChatGptByokStore, Promise<void>>()
406​
407/**
408 * Refresh the ChatGPT access token when it expires in under five minutes.
409 * Call it before each send. It does nothing when the user did not sign in
410 * with ChatGPT or the keyring is locked.
411 *
412 * Refresh tokens rotate, so calls on the same store share one request.
413 */
414export function refreshChatGptSignIn(
415 store: ChatGptByokStore,
416 options: RefreshChatGptSignInOptions = {},
417): Promise<void> {
418 const running = inFlight.get(store)
419 if (running) return running
420 const next = refresh(store, options.fetchImpl ?? fetch).finally(() =>
421 inFlight.delete(store),
422 )
423 inFlight.set(store, next)
424 return next
426​
427async function refresh(
428 store: ChatGptByokStore,
429 fetchImpl: typeof fetch,
430): Promise<void> {
431 const credential = readCredential(store)
432 if (!credential) return
433 // The user removed the `openai` key: drop the refresh token too.
434 if (!store.keys()[openaiByok.id]) {
435 await store.clear(CREDENTIAL_ID)
436 return
437 }
438 if (credential.expiresAt - Date.now() > REFRESH_SKEW_MS) return
439 // ponytail: tabs do not coordinate. Two tabs refreshing at once lose one
440 // rotation and that tab asks the user to sign in again.
441 try {
442 const tokens = await postToken(
443 {
444 grant_type: 'refresh_token',
445 client_id: credential.clientId,
446 refresh_token: credential.refreshToken,
447 },
448 fetchImpl,
449 )
450 await saveChatGptSignIn(store, toSignIn(credential.clientId, tokens))
451 } catch (error) {
452 // A rejected refresh token cannot recover. Clear both so the app asks the
453 // user to sign in again. Network and server errors keep the credential.
454 if (
455 error instanceof TokenRequestError &&
456 (error.status === 400 || error.status === 401)
457 ) {
458 await store.clear(CREDENTIAL_ID)
459 await store.clear(openaiByok.id)
460 }
461 throw error
462 }