opencode-plugin-litellm 1.8.1 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,998 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
2
+ import { createServer } from 'node:http'
3
+ import { isIP } from 'node:net'
4
+ import { setTimeout as delay } from 'node:timers/promises'
5
+ import { normalizeBaseURL } from './litellm-api'
6
+
7
+ // Cap for each login and refresh request to the proxy or the identity provider.
8
+ const REQUEST_TIMEOUT_MS = 10_000
9
+ // How long a browser sign-in may take, as long as OpenCode 2 gives an OAuth attempt by default; the
10
+ // connect attempt expires with it.
11
+ const CALLBACK_TIMEOUT_MS = 10 * 60 * 1000
12
+ const CLI_SSO_POLL_INTERVAL_MS = 2_000
13
+ const CLI_SSO_EXPIRES_IN_SECONDS = 600
14
+ // LiteLLM's default CLI token lifetime, for proxies whose poll response omits `expires_in`.
15
+ const CLI_TOKEN_LIFETIME_MS = 24 * 60 * 60 * 1000
16
+ const CLI_AUTH_DISCOVERY_PATH = '/.well-known/litellm-cli-auth'
17
+ const OIDC_DISCOVERY_PATH = '/.well-known/openid-configuration'
18
+ // Where a pasted UI token still works but cannot become a virtual key: no key-generation rights
19
+ // (403), no `/key/generate` route (404), or no database (500).
20
+ const KEEPS_PASTED_TOKEN: ReadonlySet<number> = new Set([403, 404, 500])
21
+ /** Expiry of a token that carries none, such as a virtual key without `expires`. */
22
+ const NEVER_EXPIRES = Number.MAX_SAFE_INTEGER
23
+ // Persisted in credential metadata; never rename.
24
+ const PKCE_FLOW = 'litellm_cli_pkce'
25
+ const OIDC_FLOW = 'oidc_pkce'
26
+
27
+ /** A signed-in session; OpenCode stores it as the OAuth credential, metadata included. */
28
+ export interface SsoToken {
29
+ access: string
30
+ refresh: string
31
+ /** Exact expiry in epoch milliseconds; OpenCode refreshes five minutes before it. */
32
+ expires: number
33
+ metadata: Record<string, unknown>
34
+ }
35
+
36
+ /** A started sign-in, in the shape of OpenCode's OAuth authorization. */
37
+ export type SsoAuthorization = { url: string; instructions: string; expiresAt?: number } & (
38
+ | { mode: 'auto'; callback: Promise<SsoToken> }
39
+ | { mode: 'code'; callback: (code: string) => Promise<SsoToken> }
40
+ )
41
+
42
+ export interface OidcConfig {
43
+ issuer: string
44
+ clientId: string
45
+ scope: string
46
+ redirectPorts: number[]
47
+ }
48
+
49
+ type Json = Record<string, unknown>
50
+ type ProxyHeaders = Record<string, string> | undefined
51
+ type TokenFailure = { ok: false; transient: boolean; message: string }
52
+ type TokenResult =
53
+ { ok: true; token: { access: string; refresh: string; expires: number } } | TokenFailure
54
+ type CliAuthDiscovery = {
55
+ authorizationEndpoint: string
56
+ tokenEndpoint: string
57
+ registrationEndpoint: string
58
+ resource: string
59
+ }
60
+ type CliSsoStart = {
61
+ loginId: string
62
+ pollSecret: string
63
+ userCode: string
64
+ expiresInSeconds: number
65
+ }
66
+
67
+ function isRecord(value: unknown): value is Json {
68
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
69
+ }
70
+
71
+ /** Tokens and client IDs: printable ASCII without spaces. */
72
+ function isAuthToken(value: unknown): value is string {
73
+ return typeof value === 'string' && /^[\x21-\x7e]+$/.test(value)
74
+ }
75
+
76
+ /** The OAuth `error` code when it is a plain code; descriptions and other fields are never echoed. */
77
+ function oauthErrorCode(value: unknown): string | undefined {
78
+ return typeof value === 'string' && /^[a-z_]{1,64}$/.test(value) ? value : undefined
79
+ }
80
+
81
+ function positiveNumber(value: unknown): number | undefined {
82
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined
83
+ }
84
+
85
+ // A loop, not /\/+$/: that regex backtracks quadratically on a long slash run followed by another character.
86
+ function trimTrailingSlashes(value: string): string {
87
+ let end = value.length
88
+ while (end > 0 && value[end - 1] === '/') end--
89
+ return value.slice(0, end)
90
+ }
91
+
92
+ function expiresIn(seconds: number): number {
93
+ return Math.floor(Date.now() + seconds * 1_000)
94
+ }
95
+
96
+ function requestSignal(): AbortSignal {
97
+ return AbortSignal.timeout(REQUEST_TIMEOUT_MS)
98
+ }
99
+
100
+ /** A rate limit or server error: retrying can still reach a flow that falling back would give up. */
101
+ function transientStatus(status: number): boolean {
102
+ return status === 429 || status >= 500
103
+ }
104
+
105
+ function authHeaders(headers: ProxyHeaders, contentType?: string): Headers {
106
+ const result = new Headers(headers)
107
+ result.set('Accept', 'application/json')
108
+ if (contentType) result.set('Content-Type', contentType)
109
+ return result
110
+ }
111
+
112
+ async function readJson(response: Response, stage: string): Promise<unknown> {
113
+ try {
114
+ return await response.json()
115
+ } catch {
116
+ throw new Error(`${stage} returned invalid JSON`)
117
+ }
118
+ }
119
+
120
+ // The host awaits a callback only once the attempt is recorded; until then a rejection must not crash the process.
121
+ function handled<T>(promise: Promise<T>): Promise<T> {
122
+ promise.catch(() => {})
123
+ return promise
124
+ }
125
+
126
+ function constantTimeEqual(value: unknown, expected: string): boolean {
127
+ if (typeof value !== 'string') return false
128
+ const left = Buffer.from(value)
129
+ const right = Buffer.from(expected)
130
+ return left.length === right.length && timingSafeEqual(left, right)
131
+ }
132
+
133
+ function jwtClaims(token: string): Json | undefined {
134
+ const [, payload, ...rest] = token.split('.')
135
+ if (rest.length !== 1 || !payload || !/^[\w-]+$/.test(payload)) return undefined
136
+ try {
137
+ const claims: unknown = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
138
+ return isRecord(claims) ? claims : undefined
139
+ } catch {
140
+ return undefined
141
+ }
142
+ }
143
+
144
+ /** A JWT's `exp` in milliseconds, or `fallback` for an opaque token. */
145
+ function tokenExpiry(token: string, fallback: number): number {
146
+ const exp = positiveNumber(jwtClaims(token)?.exp)
147
+ return exp === undefined ? fallback : Math.min(Math.floor(exp * 1_000), NEVER_EXPIRES)
148
+ }
149
+
150
+ /**
151
+ * The proxy root a sign-in talks to. SSO tokens are bearer credentials, so plain http is only
152
+ * accepted on a loopback host.
153
+ */
154
+ export function ssoRoot(baseURL: string): string {
155
+ let url: URL
156
+ try {
157
+ url = new URL(baseURL)
158
+ } catch {
159
+ throw new Error(`LiteLLM base URL is not a valid URL: ${baseURL}`)
160
+ }
161
+ const host = url.hostname
162
+ const loopback =
163
+ host === 'localhost' || host === '[::1]' || (isIP(host) === 4 && host.startsWith('127.'))
164
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {
165
+ throw new Error('LiteLLM sign-in needs an https base URL (http only on a loopback host)')
166
+ }
167
+ if (url.username || url.password || url.search || url.hash) {
168
+ throw new Error('LiteLLM base URL must not carry credentials, a query, or a fragment')
169
+ }
170
+ return normalizeBaseURL(url.href)
171
+ }
172
+
173
+ /**
174
+ * The proxy a sign-in for `providerID` goes to. Explicit configuration wins in discovery, so a typed
175
+ * URL that differs from it is refused: the token would be sent to a proxy that did not issue it.
176
+ */
177
+ export function signInRoot(
178
+ typed: string | undefined,
179
+ configured: string | undefined,
180
+ providerID: string,
181
+ ): string | undefined {
182
+ if (typed && configured && ssoRoot(typed) !== ssoRoot(configured)) {
183
+ throw new Error(
184
+ `Provider "${providerID}" is configured for ${configured}; leave Base URL empty to sign in there`,
185
+ )
186
+ }
187
+ const baseURL = typed ?? configured ?? (process.env.LITELLM_BASE_URL?.trim() || undefined)
188
+ return baseURL && ssoRoot(baseURL)
189
+ }
190
+
191
+ /** Whether two base URLs name the same proxy. */
192
+ export function sameProxy(a: string, b: string): boolean {
193
+ try {
194
+ return ssoRoot(a) === ssoRoot(b)
195
+ } catch {
196
+ return false
197
+ }
198
+ }
199
+
200
+ /** What a sign-in's model cache is keyed by: stable while its tokens rotate, new for a new sign-in. */
201
+ export function ssoIdentity(token: SsoToken): string {
202
+ const { flow, clientId, issuer, subject } = token.metadata
203
+ if (flow === PKCE_FLOW) return `${flow} ${String(clientId)}`
204
+ if (flow === OIDC_FLOW) return `${flow} ${String(issuer)} ${String(subject)}`
205
+ // CLI SSO and UI tokens are never refreshed.
206
+ return token.access
207
+ }
208
+
209
+ function canonicalIssuer(value: string): string {
210
+ const url = new URL(value)
211
+ if (url.username || url.password || url.search || url.hash)
212
+ throw new Error('LiteLLM CLI auth has invalid issuer')
213
+ return `${url.origin}${trimTrailingSlashes(url.pathname) || '/'}`
214
+ }
215
+
216
+ function sameOriginUrl(value: unknown, issuer: URL, field: string): string {
217
+ if (typeof value !== 'string' || !value.trim())
218
+ throw new Error(`LiteLLM CLI auth discovery has invalid ${field}`)
219
+ let url: URL
220
+ try {
221
+ url = new URL(value)
222
+ } catch {
223
+ throw new Error(`LiteLLM CLI auth discovery has invalid ${field}`)
224
+ }
225
+ if (url.origin !== issuer.origin)
226
+ throw new Error(`LiteLLM CLI auth discovery has cross-origin ${field}`)
227
+ if (url.username || url.password || url.hash)
228
+ throw new Error(`LiteLLM CLI auth discovery has invalid ${field}`)
229
+ return value.trim()
230
+ }
231
+
232
+ /** An https URL without credentials or fragment, returned verbatim. */
233
+ function httpsUrl(value: unknown, { allowQuery }: { allowQuery: boolean }): string | undefined {
234
+ if (typeof value !== 'string' || value.includes('#') || (!allowQuery && value.includes('?')))
235
+ return undefined
236
+ try {
237
+ const url = new URL(value)
238
+ return url.protocol === 'https:' && !url.username && !url.password ? value : undefined
239
+ } catch {
240
+ return undefined
241
+ }
242
+ }
243
+
244
+ /** POSTs a token form without following redirects; each flow validates its own success fields. */
245
+ async function postTokenForm(
246
+ endpoint: string,
247
+ form: URLSearchParams,
248
+ headers: ProxyHeaders,
249
+ label: string,
250
+ ): Promise<{ ok: true; data: Json } | TokenFailure> {
251
+ let response: Response
252
+ try {
253
+ response = await fetch(endpoint, {
254
+ method: 'POST',
255
+ headers: authHeaders(headers, 'application/x-www-form-urlencoded'),
256
+ body: form,
257
+ redirect: 'manual',
258
+ signal: requestSignal(),
259
+ })
260
+ } catch {
261
+ return { ok: false, transient: true, message: `${label} token exchange failed (network error)` }
262
+ }
263
+ let data: Json | undefined
264
+ try {
265
+ const parsed: unknown = await response.json()
266
+ if (isRecord(parsed)) data = parsed
267
+ } catch (error) {
268
+ if (response.ok && !(error instanceof SyntaxError)) {
269
+ return {
270
+ ok: false,
271
+ transient: true,
272
+ message: `${label} token exchange failed (network error)`,
273
+ }
274
+ }
275
+ }
276
+ if (!response.ok) {
277
+ const code = oauthErrorCode(data?.error)
278
+ return {
279
+ ok: false,
280
+ transient: response.status === 429 || response.status >= 500,
281
+ message: code
282
+ ? `${label} token exchange rejected (${code})`
283
+ : `${label} token exchange failed (HTTP ${response.status})`,
284
+ }
285
+ }
286
+ return { ok: true, data: data ?? {} }
287
+ }
288
+
289
+ async function requestPkceToken(
290
+ endpoint: string,
291
+ form: URLSearchParams,
292
+ headers: ProxyHeaders,
293
+ existingRefreshToken?: string,
294
+ ): Promise<TokenResult> {
295
+ const response = await postTokenForm(endpoint, form, headers, 'LiteLLM')
296
+ if (!response.ok) return response
297
+ const { data } = response
298
+ const lifetime = positiveNumber(data.expires_in)
299
+ const expires = lifetime === undefined ? NaN : expiresIn(lifetime)
300
+ if (
301
+ !isAuthToken(data.access_token) ||
302
+ (!isAuthToken(data.refresh_token) && !isAuthToken(existingRefreshToken)) ||
303
+ typeof data.token_type !== 'string' ||
304
+ data.token_type.toLowerCase() !== 'bearer' ||
305
+ !Number.isSafeInteger(expires)
306
+ ) {
307
+ return {
308
+ ok: false,
309
+ transient: false,
310
+ message: 'LiteLLM token exchange returned an invalid response',
311
+ }
312
+ }
313
+ return {
314
+ ok: true,
315
+ token: {
316
+ access: data.access_token,
317
+ // A refresh may not rotate the refresh token; keep the existing one when the server omits it.
318
+ refresh: isAuthToken(data.refresh_token) ? data.refresh_token : existingRefreshToken!,
319
+ expires,
320
+ },
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Exchanges a grant for an id_token and checks its claims (OIDC Core §3.1.3.7). The signature is
326
+ * deliberately not verified: the proxy verifies it against the IdP's keys before honouring the
327
+ * bearer, so these checks only stop OpenCode from storing a token meant for another client or login.
328
+ */
329
+ async function requestOidcToken(
330
+ endpoint: string,
331
+ form: URLSearchParams,
332
+ expected: { issuer: string; clientId: string; nonce?: string; subject?: string },
333
+ existingRefreshToken = '',
334
+ ): Promise<TokenResult & { subject?: string }> {
335
+ // IdP requests never carry the proxy's headers: they can hold gateway credentials.
336
+ const response = await postTokenForm(endpoint, form, undefined, 'OIDC')
337
+ if (!response.ok) return response
338
+ const { id_token: idToken, refresh_token: refreshToken } = response.data
339
+ const claims = isAuthToken(idToken) ? jwtClaims(idToken) : undefined
340
+ if (!isAuthToken(idToken) || !claims) {
341
+ return { ok: false, transient: false, message: 'OIDC token response has no valid id_token' }
342
+ }
343
+ const invalid = (claim: string): TokenFailure => ({
344
+ ok: false,
345
+ transient: false,
346
+ message: `OIDC id_token has invalid ${claim}`,
347
+ })
348
+ if (claims.iss !== expected.issuer) return invalid('iss')
349
+ if (!(Array.isArray(claims.aud) ? claims.aud : [claims.aud]).includes(expected.clientId))
350
+ return invalid('aud')
351
+ // azp is optional, even with several audiences, but when present it must name this client.
352
+ if (claims.azp !== undefined && claims.azp !== expected.clientId) return invalid('azp')
353
+ if (typeof claims.sub !== 'string' || !claims.sub) return invalid('sub')
354
+ if (expected.subject !== undefined && claims.sub !== expected.subject) return invalid('sub')
355
+ const expires = typeof claims.exp === 'number' ? Math.floor(claims.exp * 1_000) : NaN
356
+ if (!Number.isSafeInteger(expires) || expires <= Date.now()) return invalid('exp')
357
+ if (expected.nonce !== undefined && !constantTimeEqual(claims.nonce, expected.nonce))
358
+ return invalid('nonce')
359
+ return {
360
+ ok: true,
361
+ token: {
362
+ access: idToken,
363
+ // The refresh token is optional, and an IdP that does not rotate it keeps the existing one valid.
364
+ refresh: isAuthToken(refreshToken) ? refreshToken : existingRefreshToken,
365
+ expires,
366
+ },
367
+ subject: claims.sub,
368
+ }
369
+ }
370
+
371
+ interface Loopback {
372
+ redirectUri: string
373
+ state: string
374
+ expiresAt: number
375
+ /** The authorization code of the first callback carrying `state`. */
376
+ code: Promise<string>
377
+ close(): void
378
+ }
379
+
380
+ /**
381
+ * Serves an RFC 8252 loopback redirect on 127.0.0.1 until `code` settles: on the first valid
382
+ * callback, an OAuth error, the sign-in timeout, or `close()`.
383
+ */
384
+ async function listenForCallback(label: string, ports: readonly number[]): Promise<Loopback> {
385
+ const state = randomBytes(32).toString('base64url')
386
+ const expiresAt = Date.now() + CALLBACK_TIMEOUT_MS
387
+ const server = createServer()
388
+ let settle!: (result: { code?: string; error?: Error }) => void
389
+ const code = handled(
390
+ new Promise<string>((resolve, reject) => {
391
+ const timeout = setTimeout(
392
+ () => settle({ error: new Error(`${label} sign-in timed out`) }),
393
+ CALLBACK_TIMEOUT_MS,
394
+ )
395
+ settle = (result) => {
396
+ settle = () => {}
397
+ clearTimeout(timeout)
398
+ server.close()
399
+ if (result.error) reject(result.error)
400
+ else resolve(result.code!)
401
+ }
402
+ }),
403
+ )
404
+ server.on('request', (request, response) => {
405
+ response.setHeader('Cache-Control', 'no-store')
406
+ let url: URL
407
+ try {
408
+ url = new URL(request.url ?? '/', 'http://127.0.0.1')
409
+ } catch {
410
+ response.writeHead(400).end('Invalid callback URL')
411
+ return
412
+ }
413
+ if (url.pathname !== '/callback') {
414
+ response.writeHead(404).end()
415
+ return
416
+ }
417
+ if (request.method !== 'GET') {
418
+ response.writeHead(405, { Allow: 'GET' }).end()
419
+ return
420
+ }
421
+ if (!constantTimeEqual(url.searchParams.get('state'), state)) {
422
+ response.writeHead(400).end('Invalid OAuth state')
423
+ return
424
+ }
425
+ const error = url.searchParams.get('error')
426
+ if (error) {
427
+ response.writeHead(400).end('OAuth login failed')
428
+ const errorCode = oauthErrorCode(error)
429
+ settle({
430
+ error: new Error(`${label} sign-in was denied${errorCode ? ` (${errorCode})` : ''}`),
431
+ })
432
+ return
433
+ }
434
+ const authorizationCode = url.searchParams.get('code')
435
+ if (!authorizationCode) {
436
+ response.writeHead(400).end('Missing OAuth code')
437
+ return
438
+ }
439
+ response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
440
+ response.end(
441
+ '<!doctype html><title>LiteLLM login complete</title><p>You can close this window.</p>',
442
+ )
443
+ settle({ code: authorizationCode })
444
+ })
445
+ // Try each pre-registered port in order; without any, the OS assigns one (RFC 8252 §7.3).
446
+ const candidates = ports.length > 0 ? ports : [0]
447
+ for (const [index, port] of candidates.entries()) {
448
+ try {
449
+ await new Promise<void>((resolve, reject) => {
450
+ server.once('error', reject)
451
+ server.listen(port, '127.0.0.1', () => {
452
+ server.off('error', reject)
453
+ resolve()
454
+ })
455
+ })
456
+ break
457
+ } catch (error) {
458
+ if (index === candidates.length - 1) {
459
+ settle({ error: error as Error })
460
+ throw error
461
+ }
462
+ }
463
+ }
464
+ const address = server.address()
465
+ if (!address || typeof address === 'string') {
466
+ settle({ error: new Error(`${label} callback failed to start`) })
467
+ throw new Error(`${label} callback failed to start`)
468
+ }
469
+ // A later server error, such as EMFILE on accept, ends the sign-in instead of crashing OpenCode.
470
+ server.on('error', (error) => settle({ error }))
471
+ return {
472
+ redirectUri: `http://127.0.0.1:${address.port}/callback`,
473
+ state,
474
+ expiresAt,
475
+ code,
476
+ close: () => settle({ error: new Error(`${label} sign-in cancelled`) }),
477
+ }
478
+ }
479
+
480
+ function pkceChallenge(verifier: string): string {
481
+ return createHash('sha256').update(verifier).digest('base64url')
482
+ }
483
+
484
+ async function discoverPkce(
485
+ root: string,
486
+ headers: ProxyHeaders,
487
+ ): Promise<CliAuthDiscovery | undefined> {
488
+ const response = await fetch(`${root}${CLI_AUTH_DISCOVERY_PATH}`, {
489
+ headers: authHeaders(headers),
490
+ redirect: 'manual',
491
+ signal: requestSignal(),
492
+ })
493
+ if (transientStatus(response.status)) {
494
+ throw new Error(`LiteLLM CLI auth discovery failed (HTTP ${response.status})`)
495
+ }
496
+ // Anything but a contract this plugin speaks means the proxy does not offer it here: a missing
497
+ // route, an access gateway's 401/403, a page from a catch-all route, or another contract version.
498
+ if (!response.ok) return undefined
499
+ const data: unknown = await response.json().catch(() => undefined)
500
+ if (!isRecord(data) || data.contract_version !== 1) return undefined
501
+ if (
502
+ !Array.isArray(data.code_challenge_methods_supported) ||
503
+ !data.code_challenge_methods_supported.includes('S256')
504
+ ) {
505
+ throw new Error('LiteLLM CLI auth discovery does not support S256')
506
+ }
507
+ let issuer: URL
508
+ try {
509
+ issuer = new URL(String(data.issuer))
510
+ if (canonicalIssuer(issuer.href) !== canonicalIssuer(root)) throw new Error('mismatch')
511
+ } catch {
512
+ throw new Error('LiteLLM CLI auth discovery issuer does not match the proxy URL')
513
+ }
514
+ return {
515
+ authorizationEndpoint: sameOriginUrl(
516
+ data.authorization_endpoint,
517
+ issuer,
518
+ 'authorization endpoint',
519
+ ),
520
+ tokenEndpoint: sameOriginUrl(data.token_endpoint, issuer, 'token endpoint'),
521
+ registrationEndpoint: sameOriginUrl(
522
+ data.registration_endpoint,
523
+ issuer,
524
+ 'registration endpoint',
525
+ ),
526
+ resource: sameOriginUrl(data.resource, issuer, 'resource'),
527
+ }
528
+ }
529
+
530
+ /** LiteLLM's CLI-auth contract: dynamic client registration, then authorization code + PKCE. */
531
+ async function authorizePkce(
532
+ root: string,
533
+ discovery: CliAuthDiscovery,
534
+ headers: ProxyHeaders,
535
+ ): Promise<SsoAuthorization> {
536
+ const verifier = randomBytes(32).toString('base64url')
537
+ const callback = await listenForCallback('LiteLLM', [])
538
+ try {
539
+ const registrationResponse = await fetch(discovery.registrationEndpoint, {
540
+ method: 'POST',
541
+ headers: authHeaders(headers, 'application/json'),
542
+ body: JSON.stringify({
543
+ client_name: 'opencode-litellm',
544
+ redirect_uris: [callback.redirectUri],
545
+ token_endpoint_auth_method: 'none',
546
+ grant_types: ['authorization_code', 'refresh_token'],
547
+ response_types: ['code'],
548
+ }),
549
+ redirect: 'manual',
550
+ signal: requestSignal(),
551
+ })
552
+ if (!registrationResponse.ok) {
553
+ throw new Error(
554
+ `LiteLLM PKCE client registration failed (HTTP ${registrationResponse.status})`,
555
+ )
556
+ }
557
+ const registration = await readJson(registrationResponse, 'LiteLLM CLI auth registration')
558
+ if (
559
+ !isRecord(registration) ||
560
+ !isAuthToken(registration.client_id) ||
561
+ !Array.isArray(registration.redirect_uris) ||
562
+ !registration.redirect_uris.includes(callback.redirectUri)
563
+ ) {
564
+ throw new Error('LiteLLM PKCE client registration returned an invalid response')
565
+ }
566
+ const clientId = registration.client_id
567
+ const url = new URL(discovery.authorizationEndpoint)
568
+ for (const [key, value] of Object.entries({
569
+ client_id: clientId,
570
+ redirect_uri: callback.redirectUri,
571
+ response_type: 'code',
572
+ resource: discovery.resource,
573
+ code_challenge: pkceChallenge(verifier),
574
+ code_challenge_method: 'S256',
575
+ state: callback.state,
576
+ })) {
577
+ url.searchParams.set(key, value)
578
+ }
579
+ return {
580
+ mode: 'auto',
581
+ url: url.toString(),
582
+ instructions: 'Sign in to LiteLLM in your browser, on the machine that runs OpenCode.',
583
+ expiresAt: callback.expiresAt,
584
+ callback: handled(
585
+ callback.code.then(async (code) => {
586
+ const result = await requestPkceToken(
587
+ discovery.tokenEndpoint,
588
+ new URLSearchParams({
589
+ grant_type: 'authorization_code',
590
+ code,
591
+ redirect_uri: callback.redirectUri,
592
+ client_id: clientId,
593
+ code_verifier: verifier,
594
+ resource: discovery.resource,
595
+ }),
596
+ headers,
597
+ )
598
+ if (!result.ok) throw new Error(result.message)
599
+ return {
600
+ ...result.token,
601
+ metadata: {
602
+ flow: PKCE_FLOW,
603
+ baseURL: root,
604
+ clientId,
605
+ tokenEndpoint: discovery.tokenEndpoint,
606
+ resource: discovery.resource,
607
+ },
608
+ }
609
+ }),
610
+ ),
611
+ }
612
+ } catch (error) {
613
+ callback.close()
614
+ throw error
615
+ }
616
+ }
617
+
618
+ async function startCliSso(root: string, headers: ProxyHeaders): Promise<CliSsoStart | undefined> {
619
+ const response = await fetch(`${root}/sso/cli/start`, {
620
+ method: 'POST',
621
+ headers,
622
+ redirect: 'manual',
623
+ signal: requestSignal(),
624
+ })
625
+ if (transientStatus(response.status)) {
626
+ throw new Error(`LiteLLM CLI SSO start failed (HTTP ${response.status})`)
627
+ }
628
+ // Not offered here, as on proxies without it (404/405) or behind an access gateway (401/403); a
629
+ // token pasted from the LiteLLM UI may still work.
630
+ if (!response.ok) return undefined
631
+ const data = await readJson(response, 'LiteLLM CLI SSO start')
632
+ if (
633
+ !isRecord(data) ||
634
+ typeof data.login_id !== 'string' ||
635
+ !data.login_id ||
636
+ typeof data.poll_secret !== 'string' ||
637
+ !data.poll_secret ||
638
+ typeof data.user_code !== 'string' ||
639
+ !data.user_code
640
+ ) {
641
+ throw new Error('LiteLLM CLI SSO start returned an invalid response')
642
+ }
643
+ return {
644
+ loginId: data.login_id,
645
+ pollSecret: data.poll_secret,
646
+ userCode: data.user_code,
647
+ expiresInSeconds: positiveNumber(data.expires_in) ?? CLI_SSO_EXPIRES_IN_SECONDS,
648
+ }
649
+ }
650
+
651
+ /** The teams a CLI SSO poll offers, as `id` plus a display label. */
652
+ function cliSsoTeams(data: Json): Array<{ id: string; label: string }> {
653
+ const details = Array.isArray(data.team_details) ? data.team_details : []
654
+ const teams = details.flatMap((team) => {
655
+ if (!isRecord(team)) return []
656
+ const id = typeof team.team_id === 'string' ? team.team_id : team.id
657
+ const alias = team.team_alias
658
+ return typeof id === 'string' && id
659
+ ? [{ id, label: typeof alias === 'string' && alias ? alias : id }]
660
+ : []
661
+ })
662
+ if (teams.length === 0 && Array.isArray(data.teams)) {
663
+ teams.push(
664
+ ...data.teams.flatMap((id) => (typeof id === 'string' && id ? [{ id, label: id }] : [])),
665
+ )
666
+ }
667
+ return teams
668
+ }
669
+
670
+ async function pollCliSso(
671
+ root: string,
672
+ start: CliSsoStart,
673
+ headers: ProxyHeaders,
674
+ team?: string,
675
+ ): Promise<SsoToken> {
676
+ const deadline = Date.now() + start.expiresInSeconds * 1_000
677
+ const pollUrl = new URL(`${root}/sso/cli/poll/${encodeURIComponent(start.loginId)}`)
678
+ let teamId: string | undefined
679
+ while (Date.now() < deadline) {
680
+ if (teamId) pollUrl.searchParams.set('team_id', teamId)
681
+ let response: Response
682
+ try {
683
+ response = await fetch(pollUrl, {
684
+ headers: { ...headers, 'x-litellm-cli-poll-secret': start.pollSecret },
685
+ redirect: 'manual',
686
+ signal: requestSignal(),
687
+ })
688
+ } catch {
689
+ await delay(CLI_SSO_POLL_INTERVAL_MS)
690
+ continue
691
+ }
692
+ if (response.status === 429 || response.status >= 500) {
693
+ await delay(CLI_SSO_POLL_INTERVAL_MS)
694
+ continue
695
+ }
696
+ if (response.status === 400) throw new Error('LiteLLM CLI SSO login expired or is invalid')
697
+ if (!response.ok) throw new Error(`LiteLLM CLI SSO polling failed (HTTP ${response.status})`)
698
+ const data = await readJson(response, 'LiteLLM CLI SSO polling')
699
+ if (!isRecord(data)) throw new Error('LiteLLM CLI SSO polling returned an invalid response')
700
+ if (data.status === 'ready' && isAuthToken(data.key)) {
701
+ const lifetime = positiveNumber(data.expires_in)
702
+ return {
703
+ access: data.key,
704
+ refresh: '',
705
+ expires: lifetime
706
+ ? expiresIn(lifetime)
707
+ : tokenExpiry(data.key, Date.now() + CLI_TOKEN_LIFETIME_MS),
708
+ metadata: { baseURL: root },
709
+ }
710
+ }
711
+ if (data.status === 'ready' && data.requires_team_selection === true && !teamId) {
712
+ const teams = cliSsoTeams(data)
713
+ if (teams.length === 0)
714
+ throw new Error('LiteLLM CLI SSO requested team selection without any teams')
715
+ const selected = team
716
+ ? teams.find((candidate) => candidate.id === team || candidate.label === team)
717
+ : undefined
718
+ if (!selected) {
719
+ // The connect dialog cannot ask mid-sign-in, so the choice has to come from the Team field.
720
+ const choices = teams
721
+ .map(({ id, label }) => (label === id ? id : `${label} (${id})`))
722
+ .join(', ')
723
+ throw new Error(
724
+ `${team ? `Your LiteLLM account has no team "${team}"` : 'LiteLLM asks which team to sign in with'}; connect again with one of these as Team: ${choices}`,
725
+ )
726
+ }
727
+ teamId = selected.id
728
+ continue
729
+ }
730
+ if (data.status !== 'pending')
731
+ throw new Error('LiteLLM CLI SSO polling returned an invalid response')
732
+ await delay(CLI_SSO_POLL_INTERVAL_MS)
733
+ }
734
+ throw new Error('LiteLLM CLI SSO login expired')
735
+ }
736
+
737
+ /** Exchanges a pasted UI token for a virtual key, or undefined when the proxy cannot mint one. */
738
+ async function generateVirtualKey(
739
+ root: string,
740
+ userToken: string,
741
+ headers: ProxyHeaders,
742
+ ): Promise<{ key: string; expires?: number } | undefined> {
743
+ const response = await fetch(`${root}/key/generate`, {
744
+ method: 'POST',
745
+ headers: {
746
+ ...headers,
747
+ Authorization: `Bearer ${userToken}`,
748
+ 'Content-Type': 'application/json',
749
+ },
750
+ body: JSON.stringify({}),
751
+ redirect: 'manual',
752
+ signal: requestSignal(),
753
+ })
754
+ if (KEEPS_PASTED_TOKEN.has(response.status)) {
755
+ console.log(
756
+ `[opencode-litellm] Using the pasted LiteLLM token directly; /key/generate answered HTTP ${response.status}`,
757
+ )
758
+ return undefined
759
+ }
760
+ if (response.status === 401) {
761
+ throw new Error('LiteLLM rejected the pasted token; sign in again and paste a current one')
762
+ }
763
+ if (!response.ok) throw new Error(`/key/generate failed (HTTP ${response.status})`)
764
+ const data = await readJson(response, '/key/generate')
765
+ if (!isRecord(data) || !isAuthToken(data.key)) throw new Error('/key/generate returned no key')
766
+ const expires = typeof data.expires === 'string' ? Date.parse(data.expires) : NaN
767
+ return { key: data.key, expires: Number.isSafeInteger(expires) ? expires : undefined }
768
+ }
769
+
770
+ /** The oldest flow: the user copies a token from the LiteLLM UI, exchanged for a virtual key when the proxy allows it. */
771
+ function authorizePastedToken(root: string, headers: ProxyHeaders): SsoAuthorization {
772
+ return {
773
+ mode: 'code',
774
+ url: `${root}/sso/key/generate`,
775
+ instructions:
776
+ 'Sign in to LiteLLM in your browser, then paste the token from the LiteLLM UI as the code.',
777
+ callback: async (code) => {
778
+ const token = code
779
+ .trim()
780
+ .replace(/^Bearer\s+/i, '')
781
+ .trim()
782
+ if (!isAuthToken(token)) throw new Error('Paste the token from the LiteLLM UI')
783
+ const generated = await generateVirtualKey(root, token, headers)
784
+ return generated
785
+ ? {
786
+ access: generated.key,
787
+ refresh: '',
788
+ expires: generated.expires ?? NEVER_EXPIRES,
789
+ metadata: { baseURL: root },
790
+ }
791
+ : {
792
+ access: token,
793
+ refresh: '',
794
+ expires: tokenExpiry(token, NEVER_EXPIRES),
795
+ metadata: { baseURL: root },
796
+ }
797
+ },
798
+ }
799
+ }
800
+
801
+ /**
802
+ * Starts a LiteLLM-hosted sign-in, preferring the newest flow the proxy offers: the CLI-auth
803
+ * contract (authorization code + PKCE), then CLI SSO with a confirmation code, then a token
804
+ * pasted from the LiteLLM UI.
805
+ */
806
+ export async function authorizeLiteLLM(
807
+ baseURL: string,
808
+ headers?: Record<string, string>,
809
+ team?: string,
810
+ ): Promise<SsoAuthorization> {
811
+ const root = ssoRoot(baseURL)
812
+ const discovery = await discoverPkce(root, headers)
813
+ if (discovery) return authorizePkce(root, discovery, headers)
814
+ const start = await startCliSso(root, headers)
815
+ if (!start) return authorizePastedToken(root, headers)
816
+ return {
817
+ mode: 'auto',
818
+ url: `${root}/sso/key/generate?${new URLSearchParams({ source: 'litellm-cli', key: start.loginId })}`,
819
+ // OpenCode 1's connect dialog shows the text after the last colon as the code to confirm.
820
+ instructions: `Sign in to LiteLLM in your browser and confirm this code: ${start.userCode}`,
821
+ expiresAt: expiresIn(start.expiresInSeconds),
822
+ callback: handled(pollCliSso(root, start, headers, team)),
823
+ }
824
+ }
825
+
826
+ /** Validates the identity provider fields of the connect form. */
827
+ export function parseOidcConfig(raw: {
828
+ issuer?: string
829
+ clientId?: string
830
+ scope?: string
831
+ redirectPorts?: string
832
+ }): OidcConfig {
833
+ const invalid = (field: string, expected: string) =>
834
+ new Error(`Invalid OIDC ${field}: expected ${expected}`)
835
+ const issuer = httpsUrl(raw.issuer?.trim(), { allowQuery: false })
836
+ if (!issuer) throw invalid('issuer', 'an https URL without credentials, query, or fragment')
837
+ const clientId = raw.clientId?.trim()
838
+ if (!isAuthToken(clientId)) throw invalid('client ID', 'a non-empty value without spaces')
839
+ const scope = raw.scope?.trim() || 'openid'
840
+ if (!scope.split(/\s+/).includes('openid'))
841
+ throw invalid('scopes', 'a space-separated list that includes "openid"')
842
+ const ports = (raw.redirectPorts ?? '').split(/[\s,]+/).filter(Boolean)
843
+ // Digits only: Number() would also take forms like 0x10 or 1e3.
844
+ if (!ports.every((port) => /^\d+$/.test(port) && Number(port) >= 1 && Number(port) <= 65535)) {
845
+ throw invalid('redirect ports', 'port numbers from 1 to 65535')
846
+ }
847
+ return { issuer, clientId, scope, redirectPorts: ports.map(Number) }
848
+ }
849
+
850
+ async function discoverOidc(
851
+ issuer: string,
852
+ ): Promise<{ issuer: string; authorizationEndpoint: string; tokenEndpoint: string }> {
853
+ const response = await fetch(`${trimTrailingSlashes(issuer)}${OIDC_DISCOVERY_PATH}`, {
854
+ headers: authHeaders(undefined),
855
+ redirect: 'manual',
856
+ signal: requestSignal(),
857
+ })
858
+ if (!response.ok) throw new Error(`OIDC discovery failed (HTTP ${response.status})`)
859
+ const data = await readJson(response, 'OIDC discovery')
860
+ if (
861
+ !isRecord(data) ||
862
+ typeof data.issuer !== 'string' ||
863
+ trimTrailingSlashes(data.issuer) !== trimTrailingSlashes(issuer)
864
+ ) {
865
+ throw new Error('OIDC discovery issuer does not match the configured issuer')
866
+ }
867
+ const methods = data.code_challenge_methods_supported
868
+ if (methods !== undefined && (!Array.isArray(methods) || !methods.includes('S256'))) {
869
+ throw new Error('OIDC discovery does not support S256')
870
+ }
871
+ const authorizationEndpoint = httpsUrl(data.authorization_endpoint, { allowQuery: true })
872
+ if (!authorizationEndpoint) throw new Error('OIDC discovery has invalid authorization_endpoint')
873
+ const tokenEndpoint = httpsUrl(data.token_endpoint, { allowQuery: true })
874
+ if (!tokenEndpoint) throw new Error('OIDC discovery has invalid token_endpoint')
875
+ return { issuer: data.issuer, authorizationEndpoint, tokenEndpoint }
876
+ }
877
+
878
+ /**
879
+ * Signs in with the identity provider directly, as a public client, for proxies running LiteLLM
880
+ * JWT auth. The `id_token` becomes the bearer token; nothing is sent to the proxy.
881
+ */
882
+ export async function authorizeOidc(config: OidcConfig): Promise<SsoAuthorization> {
883
+ const discovery = await discoverOidc(config.issuer)
884
+ const verifier = randomBytes(32).toString('base64url')
885
+ const nonce = randomBytes(32).toString('base64url')
886
+ const callback = await listenForCallback('OIDC', config.redirectPorts)
887
+ const url = new URL(discovery.authorizationEndpoint)
888
+ for (const [key, value] of Object.entries({
889
+ response_type: 'code',
890
+ client_id: config.clientId,
891
+ redirect_uri: callback.redirectUri,
892
+ scope: config.scope,
893
+ state: callback.state,
894
+ nonce,
895
+ code_challenge: pkceChallenge(verifier),
896
+ code_challenge_method: 'S256',
897
+ })) {
898
+ url.searchParams.set(key, value)
899
+ }
900
+ return {
901
+ mode: 'auto',
902
+ url: url.toString(),
903
+ instructions:
904
+ 'Sign in with your identity provider in your browser, on the machine that runs OpenCode.',
905
+ expiresAt: callback.expiresAt,
906
+ callback: handled(
907
+ callback.code.then(async (code) => {
908
+ const result = await requestOidcToken(
909
+ discovery.tokenEndpoint,
910
+ new URLSearchParams({
911
+ grant_type: 'authorization_code',
912
+ code,
913
+ redirect_uri: callback.redirectUri,
914
+ client_id: config.clientId,
915
+ code_verifier: verifier,
916
+ }),
917
+ { issuer: discovery.issuer, clientId: config.clientId, nonce },
918
+ )
919
+ if (!result.ok) throw new Error(result.message)
920
+ return {
921
+ ...result.token,
922
+ metadata: {
923
+ flow: OIDC_FLOW,
924
+ issuer: discovery.issuer,
925
+ clientId: config.clientId,
926
+ tokenEndpoint: discovery.tokenEndpoint,
927
+ subject: result.subject,
928
+ scope: config.scope,
929
+ },
930
+ }
931
+ }),
932
+ ),
933
+ }
934
+ }
935
+
936
+ /**
937
+ * Renews a session through its token endpoint. A transient failure keeps the current token until it
938
+ * actually expires; CLI SSO and UI tokens have no refresh grant and last until they expire.
939
+ */
940
+ export async function refreshSsoToken(
941
+ token: SsoToken,
942
+ headers?: Record<string, string>,
943
+ ): Promise<SsoToken> {
944
+ const { metadata } = token
945
+ let result: TokenResult
946
+ if (metadata.flow === PKCE_FLOW) {
947
+ if (
948
+ typeof metadata.baseURL !== 'string' ||
949
+ !isAuthToken(metadata.clientId) ||
950
+ !isAuthToken(token.refresh)
951
+ ) {
952
+ throw new Error('Invalid LiteLLM PKCE credential; connect LiteLLM again')
953
+ }
954
+ const issuer = new URL(ssoRoot(metadata.baseURL))
955
+ result = await requestPkceToken(
956
+ sameOriginUrl(metadata.tokenEndpoint, issuer, 'token endpoint'),
957
+ new URLSearchParams({
958
+ grant_type: 'refresh_token',
959
+ refresh_token: token.refresh,
960
+ client_id: metadata.clientId,
961
+ resource: sameOriginUrl(metadata.resource, issuer, 'resource'),
962
+ }),
963
+ headers,
964
+ token.refresh,
965
+ )
966
+ } else if (metadata.flow === OIDC_FLOW && isAuthToken(token.refresh)) {
967
+ const tokenEndpoint = httpsUrl(metadata.tokenEndpoint, { allowQuery: true })
968
+ const { issuer, clientId, subject, scope } = metadata
969
+ if (
970
+ !tokenEndpoint ||
971
+ typeof issuer !== 'string' ||
972
+ !isAuthToken(clientId) ||
973
+ typeof subject !== 'string' ||
974
+ !subject
975
+ ) {
976
+ throw new Error('Invalid LiteLLM OIDC credential; connect LiteLLM again')
977
+ }
978
+ result = await requestOidcToken(
979
+ tokenEndpoint,
980
+ new URLSearchParams({
981
+ grant_type: 'refresh_token',
982
+ refresh_token: token.refresh,
983
+ client_id: clientId,
984
+ // Some identity providers want the original scope on a refresh; the others ignore it.
985
+ ...(typeof scope === 'string' && scope ? { scope } : {}),
986
+ }),
987
+ { issuer, clientId, subject },
988
+ token.refresh,
989
+ )
990
+ } else {
991
+ if (Date.now() < token.expires) return token
992
+ throw new Error('LiteLLM sign-in expired; connect LiteLLM again')
993
+ }
994
+ if (result.ok) return { ...token, ...result.token }
995
+ if (result.transient && Date.now() < token.expires) return token
996
+ // A transient failure leaves the session intact, and a new sign-in would need the same endpoint.
997
+ throw new Error(result.transient ? result.message : `${result.message}; connect LiteLLM again`)
998
+ }