Open History to see the last commit
1import { base64url } from './utils'
2import type { Credential } from '@tanstack/ai/byok'
3
4/** An OAuth 2 app: where to send the user, and where to get tokens. */
5export interface OAuthConfig {
6 authorizationUrl: string
7 tokenUrl: string
8 /** The device authorization endpoint (RFC 8628), for logins without a browser here. */
9 deviceUrl?: string
10 clientId: string
11 /** Only for confidential clients. A CLI is a public client and has none. */
12 clientSecret?: string
13 scopes?: ReadonlyArray<string>
14 /**
15 * The issuer of the authorization server. When the server sends `iss` with
16 * the code (RFC 9207), `loopbackLogin` refuses a code from another issuer.
17 */
18 issuer?: string
19}
20
21type Fetch = typeof fetch
22
23const encoder = new TextEncoder()
24
25function randomString(bytes = 32) {
26 return base64url(crypto.getRandomValues(new Uint8Array(bytes)))
27}
28
29/**
30 * Resolve after `ms`, or at once when `signal` aborts. The timer is not
31 * unref'd: it is the wait of a device sign-in, and a script that only waits
32 * for that sign-in must not exit.
33 */
34function wait(ms: number, signal?: AbortSignal) {
35 return new Promise<void>((resolve) => {
36 if (signal?.aborted) return resolve()
37 const done = () => {
38 clearTimeout(timer)
39 signal?.removeEventListener('abort', done)
40 resolve()
41 }
42 const timer = setTimeout(done, ms)
43 signal?.addEventListener('abort', done, { once: true })
44 })
45}
46
47/** A PKCE pair with the S256 method (RFC 7636). */
48export async function createPkce() {
49 const verifier = randomString(32)
50 const digest = await crypto.subtle.digest('SHA-256', encoder.encode(verifier))
51 return { verifier, challenge: base64url(new Uint8Array(digest)) }
52}
53
54/** The URL that starts a browser sign-in. */
55export function buildAuthorizationUrl(
56 config: OAuthConfig,
57 options: { redirectUri: string; state: string; challenge: string },
58) {
59 const url = new URL(config.authorizationUrl)
60 url.searchParams.set('response_type', 'code')
61 url.searchParams.set('client_id', config.clientId)
62 url.searchParams.set('redirect_uri', options.redirectUri)
63 url.searchParams.set('state', options.state)
64 url.searchParams.set('code_challenge', options.challenge)
65 url.searchParams.set('code_challenge_method', 'S256')
66 if (config.scopes?.length)
67 url.searchParams.set('scope', config.scopes.join(' '))
68 return url.toString()
69}
70
71async function tokenRequest(
72 config: OAuthConfig,
73 body: Record<string, string>,
74 options: { fetch?: Fetch; signal?: AbortSignal },
75) {
76 const doFetch = options.fetch ?? fetch
77 const response = await doFetch(config.tokenUrl, {
78 method: 'POST',
79 headers: {
80 'Content-Type': 'application/x-www-form-urlencoded',
81 Accept: 'application/json',
82 },
83 body: new URLSearchParams({
84 client_id: config.clientId,
85 ...(config.clientSecret ? { client_secret: config.clientSecret } : {}),
86 ...body,
87 }),
88 signal: options.signal,
89 })
90 const parsed: unknown = await response.json().catch(() => ({}))
91 if (typeof parsed !== 'object' || parsed === null) {
92 throw new Error(`OAuth token request failed (${response.status}).`)
93 }
94 // An OAuth token endpoint answers with a flat JSON object.
95 return parsed as Record<string, unknown>
96}
97
98function credentialFrom(
99 response: Record<string, unknown>,
100 previous?: Credential,
101): Credential {
102 if (typeof response.access_token !== 'string') {
103 const reason =
104 typeof response.error === 'string' ? response.error : 'no access_token'
105 throw new Error(`OAuth token request failed: ${reason}`)
106 }
107 const refreshToken =
108 typeof response.refresh_token === 'string'
109 ? response.refresh_token
110 : previous?.type === 'oauth'
111 ? previous.refreshToken
112 : undefined
113 return {
114 type: 'oauth',
115 accessToken: response.access_token,
116 ...(refreshToken ? { refreshToken } : {}),
117 ...(typeof response.expires_in === 'number'
118 ? { expiresAt: Date.now() + response.expires_in * 1000 }
119 : {}),
120 ...(typeof response.scope === 'string'
121 ? { scopes: response.scope.split(/[ ,]/).filter(Boolean) }
122 : {}),
123 // A refresh keeps the client the tokens belong to: the next refresh
124 // needs it too.
125 ...(previous?.type === 'oauth' && previous.client
126 ? { client: previous.client }
127 : {}),
128 }
129}
130
131/**
132 * Trade an authorization code for tokens. When `signal` aborts, the request
133 * stops and the call rejects with the reason of the signal.
134 */
135export async function exchangeCode(
136 config: OAuthConfig,
137 options: {
138 code: string
139 verifier: string
140 redirectUri: string
141 fetch?: Fetch
142 signal?: AbortSignal
143 },
144) {
145 const response = await tokenRequest(
146 config,
147 {
148 grant_type: 'authorization_code',
149 code: options.code,
150 code_verifier: options.verifier,
151 redirect_uri: options.redirectUri,
152 },
153 options,
154 )
155 return credentialFrom(response)
156}
157
158/** True when an OAuth credential expires within `skewMs`. */
159export function isExpired(credential: Credential, skewMs = 60_000) {
160 return (
161 credential.type === 'oauth' &&
162 credential.expiresAt !== undefined &&
163 credential.expiresAt - skewMs <= Date.now()
164 )
165}
166
167/**
168 * Get a new access token with the refresh token. `fetch` replaces the global
169 * `fetch`. When `signal` aborts, the request stops and the call rejects with
170 * the reason of the signal.
171 *
172 * @example
173 * ```ts
174 * const fresh = await refreshCredential(config, credential, { signal })
175 * ```
176 */
177export async function refreshCredential(
178 config: OAuthConfig,
179 credential: Credential,
180 options: { fetch?: Fetch; signal?: AbortSignal } = {},
181) {
182 if (credential.type !== 'oauth' || !credential.refreshToken) {
183 throw new Error('This credential has no refresh token.')
184 }
185 const response = await tokenRequest(
186 config,
187 { grant_type: 'refresh_token', refresh_token: credential.refreshToken },
188 options,
189 )
190 return credentialFrom(response, credential)
191}
192
193const DONE_PAGE =
194 '<!doctype html><title>Signed in</title><p>You are signed in. You can close this tab.</p>'
195
196/**
197 * A one-time receiver for an OAuth redirect on `127.0.0.1` (RFC 8252). Use it
198 * when another library runs the OAuth flow and you only need the code back:
199 * register `redirectUri`, send the user to the authorization URL, then await
200 * `waitForCode(state)`. It answers one callback, then stops listening.
201 *
202 * `waitForCode` resolves with the code and the `iss` the server sent with it
203 * (RFC 9207). Pass `iss` on to the library: a server that sends it can refuse
204 * a code without it.
205 *
206 * A request to the callback path with no `code` and no `state` gets a 400,
207 * and the sign-in goes on. `close()` stops listening, and a `waitForCode`
208 * that waits rejects. When `signal` aborts, the receiver closes, and
209 * `waitForCode` rejects with the reason of the signal.
210 *
211 * @example
212 * ```ts
213 * const receiver = await startLoopbackReceiver({ signal })
214 * try {
215 * // Register receiver.redirectUri, then send the user to the sign-in page.
216 * const { code, iss } = await receiver.waitForCode(state)
217 * } finally {
218 * receiver.close()
219 * }
220 * ```
221 */
222export async function startLoopbackReceiver(
223 options: { timeoutMs?: number; signal?: AbortSignal } = {},
224) {
225 const { signal } = options
226 const { createServer } = await import('node:http')
227 const server = createServer()
228 await new Promise<void>((resolve, reject) => {
229 server.once('error', reject)
230 server.listen(0, '127.0.0.1', () => resolve())
231 })
232 if (signal?.aborted) {
233 server.close()
234 throw signal.reason
235 }
236 const address = server.address()
237 const port = typeof address === 'object' && address ? address.port : 0
238 const redirectUri = `http://127.0.0.1:${port}/callback`
239 let timer: ReturnType<typeof setTimeout> | undefined
240 /** Rejects the `waitForCode` that waits. */
241 let fail: (error: unknown) => void = () => {}
242 /** Stop listening. With `error`, a `waitForCode` that waits rejects. */
243 const stop = (error?: unknown) => {
244 clearTimeout(timer)
245 signal?.removeEventListener('abort', onAbort)
246 server.closeAllConnections()
247 server.close()
248 if (error !== undefined) fail(error)
249 }
250 const onAbort = () => stop(signal?.reason)
251 signal?.addEventListener('abort', onAbort, { once: true })
252 return {
253 redirectUri,
254 close: () => stop(new Error('Sign-in cancelled.')),
255 waitForCode: (state: string) =>
256 new Promise<{ code: string; iss?: string }>((resolve, reject) => {
257 if (!server.listening) {
258 reject(
259 signal?.aborted ? signal.reason : new Error('Sign-in cancelled.'),
260 )
261 return
262 }
263 fail = reject
264 timer = setTimeout(
265 () => stop(new Error('Sign-in timed out.')),
266 options.timeoutMs ?? 10 * 60_000,
267 )
268 // The deadline must not keep a CLI or a test process alive.
269 if (typeof timer === 'object' && 'unref' in timer) timer.unref()
270 server.on('request', (req, res) => {
271 const url = new URL(req.url ?? '/', redirectUri)
272 if (url.pathname !== '/callback') {
273 res.writeHead(404).end()
274 return
275 }
276 const params = url.searchParams
277 const code = params.get('code')
278 const returnedState = params.get('state')
279 // Not an answer of the server, for example a reload or a probe.
280 if (code === null && returnedState === null) {
281 res.writeHead(400).end()
282 return
283 }
284 res.writeHead(200, { 'Content-Type': 'text/html' }).end(DONE_PAGE)
285 const iss = params.get('iss')
286 if (returnedState !== state) {
287 stop(new Error('Sign-in failed: the state does not match.'))
288 } else if (!code) {
289 stop(
290 new Error(`Sign-in failed: ${params.get('error') ?? 'no code'}`),
291 )
292 } else {
293 resolve(iss ? { code, iss } : { code })
294 stop()
295 }
296 })
297 }),
298 }
299}
300
301/**
302 * Sign in through the browser with a loopback redirect (RFC 8252 + PKCE).
303 * Listens on `127.0.0.1` on a random port, for one callback only. Calls
304 * `onUrl` with the URL to open. Resolves with the tokens.
305 *
306 * When the server sends `iss` with the code (RFC 9207) and `config.issuer`
307 * is set, they must be the same. When `signal` aborts, the sign-in stops at
308 * once, stops listening, and rejects with the reason of the signal.
309 *
310 * @example
311 * ```ts
312 * const credential = await loopbackLogin(config, {
313 * onUrl: (url) => console.log(`Open ${url}`),
314 * signal,
315 * })
316 * ```
317 */
318export async function loopbackLogin(
319 config: OAuthConfig,
320 options: {
321 onUrl: (url: string) => void
322 fetch?: Fetch
323 timeoutMs?: number
324 signal?: AbortSignal
325 },
326) {
327 const { verifier, challenge } = await createPkce()
328 const state = randomString(16)
329 const receiver = await startLoopbackReceiver(options)
330 const { redirectUri } = receiver
331 try {
332 options.onUrl(
333 buildAuthorizationUrl(config, { redirectUri, state, challenge }),
334 )
335 const { code, iss } = await receiver.waitForCode(state)
336 const isOtherIssuer =
337 iss !== undefined && config.issuer !== undefined && iss !== config.issuer
338 if (isOtherIssuer) {
339 throw new Error('Sign-in failed: the issuer does not match.')
340 }
341 return await exchangeCode(config, {
342 code,
343 verifier,
344 redirectUri,
345 fetch: options.fetch,
346 signal: options.signal,
347 })
348 } finally {
349 receiver.close()
350 }
351}
352
353/**
354 * Sign in with a device code (RFC 8628), for SSH sessions, containers, and
355 * CI. Calls `onCode` with the code and the page to enter it on, then polls.
356 * It waits the interval the server asks for, at least 1 second. When
357 * `signal` aborts, it stops polling at once and rejects with the reason of
358 * the signal.
359 *
360 * @example
361 * ```ts
362 * const credential = await deviceLogin(config, {
363 * onCode: ({ userCode, verificationUri }) =>
364 * console.log(`Enter ${userCode} at ${verificationUri}`),
365 * signal,
366 * })
367 * ```
368 */
369export async function deviceLogin(
370 config: OAuthConfig,
371 options: {
372 /** `expiresAt`: when the code expires, in epoch milliseconds. */
373 onCode: (info: {
374 userCode: string
375 verificationUri: string
376 expiresAt: number
377 }) => void
378 fetch?: Fetch
379 signal?: AbortSignal
380 /**
381 * Test hook. Default waits `ms`, and ends early when `signal` aborts.
382 */
383 sleep?: (ms: number, signal?: AbortSignal) => Promise<void>
384 },
385) {
386 if (!config.deviceUrl)
387 throw new Error('This OAuth app has no device endpoint.')
388 const { signal } = options
389 const doFetch = options.fetch ?? fetch
390 const sleep = options.sleep ?? wait
391 const started = await doFetch(config.deviceUrl, {
392 method: 'POST',
393 headers: {
394 'Content-Type': 'application/x-www-form-urlencoded',
395 Accept: 'application/json',
396 },
397 body: new URLSearchParams({
398 client_id: config.clientId,
399 ...(config.scopes?.length ? { scope: config.scopes.join(' ') } : {}),
400 }),
401 signal,
402 })
403 const device: unknown = await started.json()
404 if (
405 typeof device !== 'object' ||
406 device === null ||
407 !('device_code' in device) ||
408 typeof device.device_code !== 'string' ||
409 !('user_code' in device) ||
410 typeof device.user_code !== 'string'
411 ) {
412 throw new Error('Device sign-in failed: the server sent no device code.')
413 }
414 const verificationUri =
415 'verification_uri' in device && typeof device.verification_uri === 'string'
416 ? device.verification_uri
417 : config.authorizationUrl
418 // 5 seconds when the server names no interval (RFC 8628 section 3.5). At
419 // least 1 second, so a server that sends 0 gets no tight loop.
420 let interval =
421 'interval' in device && typeof device.interval === 'number'
422 ? Math.max(device.interval, 1) * 1000
423 : 5000
424 const expiresAt =
425 Date.now() +
426 ('expires_in' in device && typeof device.expires_in === 'number'
427 ? device.expires_in * 1000
428 : 15 * 60_000)
429 options.onCode({ userCode: device.user_code, verificationUri, expiresAt })
430
431 while (Date.now() < expiresAt) {
432 await sleep(interval, signal)
433 signal?.throwIfAborted()
434 const response = await tokenRequest(
435 config,
436 {
437 grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
438 device_code: device.device_code,
439 },
440 options,
441 )
442 if (response.error === 'authorization_pending') continue
443 if (response.error === 'slow_down') {
444 interval += 5000
445 continue
446 }
447 return credentialFrom(response)
448 }
449 throw new Error('Device sign-in expired.')
450}