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.
package/README.md CHANGED
@@ -79,6 +79,7 @@ also shows how to configure a provider directly in `opencode.json`.
79
79
  | 🧩 **Reasoning-effort variants** | When LiteLLM reports per-model effort support (`supports_low_reasoning_effort`, …), the plugin surfaces each level as a picker variant automatically. |
80
80
  | 🧭 **Responses-API routing** | Models LiteLLM reports with `mode: "responses"` are invoked through `/v1/responses` instead of `/v1/chat/completions`, with no extra configuration. OpenCode 2 overrides the runtime package per model; OpenCode 1 gets a `<provider>-responses` sibling. |
81
81
  | 🔐 **Auth-aware** | Honours `providers.litellm.settings.apiKey`, OpenCode `/connect` credentials, the box auth store, and `LITELLM_API_KEY` / `LITELLM_MASTER_KEY` on both the V1 server path and the OpenCode 2 plugin host; on OpenCode 2 a **LiteLLM** entry in the connect-provider dialog (key plus optional base URL) connects a gateway entirely from the web UI. A saved credential beats the environment key. |
82
+ | 🪪 **Single sign-on** | Signs in through LiteLLM SSO (CLI-auth PKCE, CLI SSO, or a token pasted from the LiteLLM UI) or directly with an OpenID Connect identity provider, from the connect dialog of OpenCode 1 and 2, their Desktop apps, or `opencode auth login`. The token is refreshed and sent with every request. |
82
83
  | 🌐 **Gateway-friendly** | Supports provider `headers` (and the legacy `customHeaders` option) for proxies behind Cloudflare Access or other API gateways. |
83
84
  | 🧩 **Splittable catalog** | `includeModels` / `excludeModels` (glob patterns) let one LiteLLM proxy be divided into several OpenCode providers — e.g. by naming prefix — without hand-maintaining a model list. |
84
85
  | 🎚️ **Capability overrides** | `modelCapabilities` forces or retracts per-model capability flags (`supports_vision`, `supports_function_calling`, …) when `/v1/model/info` is unavailable or disagrees with your deployment. |
@@ -327,6 +328,7 @@ If your LiteLLM proxy requires a master key, expose it via any of these approach
327
328
  | Method | Example |
328
329
  |---|---|
329
330
  | Web UI / `/connect` | Run `/connect` (or use the Desktop providers view), pick **LiteLLM**, paste the key, and optionally fill in the base URL and provider id |
331
+ | Single sign-on | `/connect` (or the Desktop providers view) → **LiteLLM** → **LiteLLM SSO** or **Identity provider (OIDC)**; see [Single sign-on](#single-sign-on) |
330
332
  | Env var (base URL) | `LITELLM_BASE_URL=https://litellm.internal.example.com/v1` |
331
333
  | Env var | `export LITELLM_API_KEY=sk-...` |
332
334
  | Env var (alias) | `export LITELLM_MASTER_KEY=sk-...` |
@@ -344,7 +346,36 @@ With no configuration at all, `/connect` → **LiteLLM** is enough:
344
346
 
345
347
  Precedence when several sources are configured: explicit provider/plugin settings always win. For the key, a credential saved in the box (the active connection or the `/connect` entry) beats the environment (`LITELLM_API_KEY`/`LITELLM_MASTER_KEY`), which is only a fallback; for the base URL, the dialog answer beats `LITELLM_BASE_URL` and local port auto-detection. A provider defined in `opencode.json` (without its own key) picks the saved credential up on the next start, while providers created from the dialog update immediately — reconnecting re-points them in place, including a changed base URL or provider id.
346
348
 
347
- The discovered model list is cached per credential: a short hash of the effective key (never the raw key) is part of every cache entry's key, so when the selected credential changes the next discovery starts fresh instead of serving another credential's model list. A `credential.switched` event also recomputes the effective key and reloads the provider registry when it changed — including the first credential saved after setup.
349
+ #### Single sign-on
350
+
351
+ The **LiteLLM** entry in `/connect` also offers two browser sign-ins. The sign-in returns to a temporary `http://127.0.0.1` callback, so the browser must run on the same machine as the OpenCode server (OpenCode Desktop's own server qualifies; a Desktop connected to a remote server does not), and the proxy needs an `https` base URL (plain `http` only on a loopback host). On OpenCode 2, OpenCode stores the session as a credential of the integration, refreshes it, and injects it into requests, as it does with a connected key; OpenCode 1 differences are [below](#opencode-1).
352
+
353
+ **LiteLLM SSO** signs in through the proxy. Leave **Base URL** empty to use the configured provider's URL, the current sign-in's proxy, or `LITELLM_BASE_URL`. A URL that differs from the configured one is refused, because explicit configuration wins in discovery and the token would go to a proxy that did not issue it. The plugin uses the newest flow the proxy offers:
354
+
355
+ 1. **CLI-auth contract** (`/.well-known/litellm-cli-auth`): authorization code + PKCE (`S256`) with a dynamically registered client. Advertised endpoints must stay on the proxy's origin, and these requests do not follow redirects. Access and refresh tokens rotate automatically; a temporary token-endpoint failure (network, 429, 5xx) keeps the current token until it actually expires.
356
+ 2. **CLI SSO** (`/sso/cli/start`, when the discovery path serves no contract the plugin speaks: a 404, an access gateway's 401 or 403, a page from a catch-all route, or another contract version): confirm the code OpenCode shows in the browser. When your account belongs to several teams, LiteLLM asks for one; the sign-in then fails with the list of teams, so connect again with the team's ID or alias as **Team**. The token lasts as long as the proxy reports (24 hours on proxies that report nothing), then you connect again.
357
+ 3. **UI token** (when `/sso/cli/start` answers with another error, such as 404 or 405 on older proxies, or 401 or 403 from an access gateway): sign in on the page OpenCode opens and paste the token from the LiteLLM UI as the code. The plugin exchanges it for a virtual key through `/key/generate`, and uses the token itself when the proxy cannot mint one: 403 (no key-generation rights), 404, or 500 (no database). Any other answer, such as 401 for an expired token, fails the sign-in.
358
+
359
+ A rate limit (429) or server error (5xx) at discovery or `/sso/cli/start` fails the sign-in instead of falling back to an older flow, so trying again can still reach the newer one.
360
+
361
+ **Identity provider (OIDC)** signs in with your identity provider directly, for proxies running LiteLLM JWT auth (`enable_jwt_auth`) that trust its issuer and accept the client ID as an audience. Enter the `https` issuer URL, a public client ID (no secret) registered for authorization code + PKCE with the redirect `http://127.0.0.1:<port>/callback`, the scopes (default `openid`; some identity providers only issue a refresh token with `offline_access`), and, for identity providers that only accept exact redirect URIs, the ports to try. The `id_token` is the bearer token: the plugin checks its issuer, audience, authorized party, subject, expiry, and nonce, and the proxy verifies its signature. Signing in sends nothing to the proxy, and identity provider requests never carry custom headers.
362
+
363
+ A sign-in's token only goes to the proxy it is for. Without a configured base URL, the plugin uses the proxy the sign-in came from; a base URL configured for another proxy turns the sign-in off, with a warning in the log. A sign-in that names no proxy, such as an OIDC sign-in with an empty **Base URL**, uses the configured base URL or `LITELLM_BASE_URL`; the plugin does not probe local ports for it, because whatever answered there would get the token. On OpenCode 2 this covers the plugin's own requests, but OpenCode itself pairs the provider whose id is `litellm` with the **LiteLLM** connection and sends that connection's token with the provider's requests. After pointing `litellm` at another proxy, connect again to that proxy, or disconnect.
364
+
365
+ Disconnecting removes the local credential only; it does not revoke the session on the proxy or the identity provider.
366
+
367
+ If a sign-in fails before the browser opens (no proxy URL, a plain `http` URL, an unreachable proxy or identity provider, an invalid OIDC field), OpenCode shows only a generic error, such as "Unknown error" in the Desktop app: OpenCode drops the message of an error a plugin raises at that step. The reason is in OpenCode's log. Errors after the browser step, such as the team list, are shown.
368
+
369
+ ##### OpenCode 1
370
+
371
+ OpenCode 1 lists the sign-ins under the `litellm` provider, in `/connect`, its Desktop app's providers view, and `opencode auth login`. The answers that can be left out sit behind a choice instead of an empty field, since the Desktop app cannot submit one: the proxy (**Configured or previous proxy** or **Another URL…**), the team, the scopes, and the redirect ports. Without a configured or previous proxy, pick **Another URL…**.
372
+
373
+ - **First sign-in:** run `opencode auth login -p litellm`. OpenCode 1 lists a provider in `/connect` and the Desktop app only once it has models, and the proxy hides them until you sign in. After that, reconnect from either; the model list stays cached for the sign-in, so LiteLLM keeps appearing even after the session ends.
374
+ - The session lives in OpenCode 1's `auth.json` like any login (the sign-in's details in `accountId`, the only field OpenCode 1 keeps). The plugin refreshes it shortly before it expires, sends the current token with every request (including the `-responses` sibling), and saves rotated tokens back; when another OpenCode process sharing the file refreshed first, it uses that one.
375
+ - A configured `apiKey` still wins over a sign-in, and a sign-in wins over `LITELLM_API_KEY` / `LITELLM_MASTER_KEY`, even once it expired: requests then ask you to connect again.
376
+ - Only the default `litellm` provider id can sign in: OpenCode 1 gives a plugin one auth entry. OpenCode 2 imports OpenCode 1 logins under a method this plugin does not claim, so connect again after upgrading.
377
+
378
+ The discovered model list is cached per credential: a short hash of the effective key (never the raw key) is part of every cache entry's key, so when the selected credential changes the next discovery starts fresh instead of serving another credential's model list. A sign-in is keyed by its credential id instead, because its access token rotates on every refresh. A `credential.switched` event also recomputes the effective key and reloads the provider registry when it changed — including the first credential saved after setup.
348
379
 
349
380
  ### Slow proxies (`LITELLM_REQUEST_TIMEOUT_MS`)
350
381
 
@@ -461,6 +492,51 @@ By default the plugin prettifies each discovered id into a display name — `ant
461
492
  - Like the other options above, `formatModelNames` is part of the cache identity, so toggling it triggers a fresh discovery on the next start instead of serving previously cached names.
462
493
  - To rename just a handful of models while keeping smart formatting for the rest, use the per-model `name` override described in [Overriding or curating individual models](#overriding-or-curating-individual-models-optional).
463
494
 
495
+ ### Naming models per provider (`modelNameTemplate`)
496
+
497
+ Several providers can point at the same LiteLLM proxy with different keys. Every key then exposes the same model ids, so the picker shows identical names under each provider and there is no way to tell which key a model will use. `modelNameTemplate` wraps every discovered model's display name with that provider's context:
498
+
499
+ ```jsonc
500
+ {
501
+ "providers": {
502
+ "litellm-team-a": {
503
+ "name": "Team A",
504
+ "settings": {
505
+ "baseURL": "https://litellm.example.com/v1",
506
+ "apiKey": "{env:KEY_A}",
507
+ "modelNameTemplate": "{name} ({provider_name})"
508
+ }
509
+ },
510
+ "litellm-team-b": {
511
+ "name": "Team B",
512
+ "settings": {
513
+ "baseURL": "https://litellm.example.com/v1",
514
+ "apiKey": "{env:KEY_B}",
515
+ "modelNameTemplate": "[B] {name}"
516
+ }
517
+ }
518
+ }
519
+ }
520
+ ```
521
+
522
+ `Claude 3.5 Sonnet` shows up as `Claude 3.5 Sonnet (Team A)` under the first provider and `[B] Claude 3.5 Sonnet` under the second.
523
+
524
+ | Placeholder | Value |
525
+ | --- | --- |
526
+ | `{name}` | The display name the plugin would produce anyway — formatted, or the raw id when `formatModelNames: false` |
527
+ | `{id}` | The model id exactly as `/v1/models` returned it |
528
+ | `{provider_id}` | The OpenCode provider id, for example `litellm-team-a` |
529
+ | `{provider_name}` | The provider's configured `name`, or its id when no name is set |
530
+
531
+ - The default is `{name}`, so omitting the setting changes nothing.
532
+ - The template runs after name formatting, so it composes with `formatModelNames: false`.
533
+ - An explicit `models.<id>.name` still wins and is never templated.
534
+ - Unknown placeholders are left as written, and substitution is single-pass: a placeholder that appears inside a resolved value stays literal.
535
+ - Non-string and empty values are ignored.
536
+ - On OpenCode 1, models that need the Responses API are served by a `<provider>-responses` sibling, so `{provider_id}` and `{provider_name}` resolve to that sibling for those models (for example `litellm-team-a-responses`).
537
+ - Like `formatModelNames`, the template is part of the cache identity — and so is the resolved provider name — so changing either starts a fresh discovery on the next start instead of serving previously cached names.
538
+ - Model ids, capability flags, pricing and filtering are unaffected.
539
+
464
540
  ### Prompt caching (`modelCompatibility`)
465
541
 
466
542
  On OpenCode 2.0.28+ (earlier 2.x releases ignore the setting), the OpenAI-compatible Chat Completions runtime only places Anthropic-style `cache_control` breakpoints when a model declares `compatibility.cacheFormat: "anthropic"`. The plugin sets that for every discovered Chat Completions model whose `/v1/model/info` entry lists `cache_control` under `supported_openai_params` — which LiteLLM reports for Anthropic and Vertex AI Anthropic deployments — so prompt caching keeps working for Claude behind the proxy. Only the Chat Completions runtimes read this setting: the Anthropic Messages runtime adds its own cache breakpoints, and the Responses runtimes do not use it, so models on those packages are left alone.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "opencode-plugin-litellm",
4
- "version": "1.8.1",
4
+ "version": "1.10.0",
5
5
  "description": "OpenCode CLI (v1 and v2) and Desktop plugin for LiteLLM proxy support with auto-detection and dynamic model discovery",
6
6
  "type": "module",
7
7
  "main": "./src/index.ts",
@@ -0,0 +1,312 @@
1
+ import type { AuthHook, AuthOAuthResult, PluginInput } from '@opencode-ai/plugin'
2
+ import { getOpenCodeStoredSso, toOpenCodeOAuthEntry } from '../utils/opencode-auth'
3
+ import {
4
+ authorizeLiteLLM,
5
+ authorizeOidc,
6
+ parseOidcConfig,
7
+ refreshSsoToken,
8
+ signInRoot,
9
+ type SsoAuthorization,
10
+ type SsoToken,
11
+ } from '../utils/sso'
12
+
13
+ /** Where the config hook found the provider; a sign-in goes to its proxy, with its gateway headers. */
14
+ export interface SignInTarget {
15
+ /** The provider's configured base URL, which discovery always uses. */
16
+ baseURL: string | undefined
17
+ /** The proxy of the stored sign-in, the default for a provider configured nowhere. */
18
+ previousURL: string | undefined
19
+ headers: Record<string, string>
20
+ }
21
+
22
+ // OpenCode 2 refreshes credentials this long before they expire; OpenCode 1 leaves it to plugins.
23
+ const REFRESH_LEAD_MS = 5 * 60 * 1000
24
+ // After a refresh that did not happen (an unavailable token endpoint), requests use the current
25
+ // token for this long instead of each waiting on the token endpoint again.
26
+ const RETRY_MS = 30 * 1000
27
+
28
+ export interface SsoSession {
29
+ /** The stored sign-in, expired or not, or undefined without one. */
30
+ stored(): Promise<SsoToken | undefined>
31
+ /** A live access token; throws when the sign-in expired and cannot be refreshed. */
32
+ access(headers?: Record<string, string>): Promise<string | undefined>
33
+ }
34
+
35
+ interface SessionState {
36
+ token?: Promise<SsoToken | undefined>
37
+ refreshing?: Promise<SsoToken>
38
+ retryAt?: number
39
+ }
40
+
41
+ // One state per provider for the whole process: OpenCode 1 can keep calling a fetch an earlier
42
+ // plugin instance wrote into its cached config, and every caller must share one refresh.
43
+ const sessions = new Map<string, SessionState>()
44
+
45
+ /**
46
+ * The OpenCode 1 side of a LiteLLM sign-in: the session OpenCode stored in
47
+ * auth.json, refreshed when it nears expiry and saved back through the
48
+ * OpenCode client, because OpenCode 1 does not refresh plugin credentials.
49
+ */
50
+ export function createSsoSession(
51
+ client: PluginInput['client'],
52
+ providerID: string,
53
+ warn: (message: string) => void,
54
+ ): SsoSession {
55
+ const state = sessions.get(providerID) ?? {}
56
+ sessions.set(providerID, state)
57
+ // A new plugin instance follows a login, so it reads auth.json again.
58
+ state.token = undefined
59
+ state.retryAt = undefined
60
+ const stored = () => (state.token ??= getOpenCodeStoredSso(providerID))
61
+
62
+ async function refresh(current: SsoToken, headers?: Record<string, string>): Promise<SsoToken> {
63
+ const latest = await getOpenCodeStoredSso(providerID)
64
+ // Never overwrite a credential saved since: a logout, an API key, or another sign-in.
65
+ if (!latest) throw new Error('The LiteLLM sign-in was removed; connect LiteLLM again')
66
+ if (latest.access !== current.access) {
67
+ // Another OpenCode process refreshed it; a sign-in to another proxy must not inherit this one's requests.
68
+ if (latest.metadata.baseURL !== current.metadata.baseURL) {
69
+ throw new Error('The LiteLLM sign-in changed; connect LiteLLM again')
70
+ }
71
+ return latest
72
+ }
73
+ const next = await refreshSsoToken(current, headers)
74
+ if (next === current) {
75
+ state.retryAt = Date.now() + RETRY_MS
76
+ return current
77
+ }
78
+ // A credential saved during the refresh wins on disk; this process keeps its own tokens.
79
+ if ((await getOpenCodeStoredSso(providerID))?.access === current.access) {
80
+ const saved = await client.auth
81
+ .set({ path: { id: providerID }, body: toOpenCodeOAuthEntry(next) })
82
+ .catch((error: unknown) => ({ error }))
83
+ if (saved.error) {
84
+ warn(
85
+ '[opencode-litellm] Could not save the refreshed LiteLLM sign-in; the next start may ask for a new one.',
86
+ )
87
+ }
88
+ }
89
+ return next
90
+ }
91
+
92
+ return {
93
+ stored,
94
+ async access(headers) {
95
+ const current = await stored()
96
+ if (!current) return undefined
97
+ const now = Date.now()
98
+ if (current.expires > now + REFRESH_LEAD_MS) return current.access
99
+ if (current.expires > now && state.retryAt !== undefined && now < state.retryAt)
100
+ return current.access
101
+ // One refresh at a time: a rotated refresh token cannot be spent twice.
102
+ state.refreshing ??= refresh(current, headers)
103
+ .then((next) => {
104
+ state.token = Promise.resolve(next)
105
+ return next
106
+ })
107
+ .finally(() => {
108
+ state.refreshing = undefined
109
+ })
110
+ return (await state.refreshing).access
111
+ },
112
+ }
113
+ }
114
+
115
+ /** Sends the sign-in's live token on every request; OpenCode 1 builds requests from static options. */
116
+ export function ssoFetch(session: SsoSession, headers?: Record<string, string>): typeof fetch {
117
+ return async (input, init) => {
118
+ const access = await session.access(headers)
119
+ const requestHeaders = new Headers(
120
+ init?.headers ?? (input instanceof Request ? input.headers : undefined),
121
+ )
122
+ if (access) requestHeaders.set('Authorization', `Bearer ${access}`)
123
+ return fetch(input, { ...init, headers: requestHeaders })
124
+ }
125
+ }
126
+
127
+ function text(value: string | undefined): string | undefined {
128
+ return value?.trim() || undefined
129
+ }
130
+
131
+ /** Wraps a sign-in for OpenCode 1, which stores a successful result in auth.json. */
132
+ function toAuthResult(authorization: SsoAuthorization, baseURL?: string): AuthOAuthResult {
133
+ const success = (token: SsoToken) => {
134
+ const { type: _, ...entry } = toOpenCodeOAuthEntry({
135
+ ...token,
136
+ metadata: { ...token.metadata, ...(baseURL ? { baseURL } : {}) },
137
+ })
138
+ return { type: 'success' as const, ...entry }
139
+ }
140
+ const { url, instructions } = authorization
141
+ if (authorization.mode === 'code') {
142
+ return {
143
+ url,
144
+ instructions,
145
+ method: 'code',
146
+ callback: async (code) => success(await authorization.callback(code)),
147
+ }
148
+ }
149
+ return {
150
+ url,
151
+ instructions,
152
+ method: 'auto',
153
+ callback: async () => success(await authorization.callback),
154
+ }
155
+ }
156
+
157
+ type Prompt = NonNullable<
158
+ Extract<AuthHook['methods'][number], { type: 'oauth' }>['prompts']
159
+ >[number]
160
+
161
+ // OpenCode Desktop cannot submit an empty text prompt, so each optional answer sits behind a select.
162
+ const proxyPrompts: Prompt[] = [
163
+ {
164
+ type: 'select',
165
+ key: 'proxy',
166
+ message: 'LiteLLM proxy',
167
+ options: [
168
+ {
169
+ label: 'Configured or previous proxy',
170
+ value: 'known',
171
+ hint: 'the provider baseURL, the last sign-in, or LITELLM_BASE_URL',
172
+ },
173
+ { label: 'Another URL…', value: 'other' },
174
+ ],
175
+ },
176
+ {
177
+ type: 'text',
178
+ key: 'baseURL',
179
+ message: 'LiteLLM proxy URL',
180
+ placeholder: 'https://llm.example.com',
181
+ when: { key: 'proxy', op: 'eq', value: 'other' },
182
+ },
183
+ ]
184
+
185
+ /** The proxy a sign-in goes to: a typed URL, else the configured one, the previous sign-in's, or the environment's. */
186
+ function proxyFor(
187
+ inputs: Record<string, string>,
188
+ target: SignInTarget,
189
+ providerID: string,
190
+ ): string | undefined {
191
+ const typed = inputs.proxy === 'other' ? text(inputs.baseURL) : undefined
192
+ if (inputs.proxy === 'other' && !typed) throw new Error('Enter the LiteLLM proxy URL')
193
+ // The previous sign-in's proxy is only a default: unlike configuration, signing in elsewhere replaces it.
194
+ const previous = target.baseURL ? undefined : target.previousURL
195
+ return signInRoot(typed ?? previous, target.baseURL, providerID)
196
+ }
197
+
198
+ /**
199
+ * The `/connect` and `opencode auth login` entries for the LiteLLM provider:
200
+ * LiteLLM SSO, a direct sign-in with an OpenID Connect identity provider, or
201
+ * an API key. `target` reports where the config hook found the provider.
202
+ */
203
+ export function liteLLMAuthHook(providerID: string, target: () => SignInTarget): AuthHook {
204
+ return {
205
+ provider: providerID,
206
+ methods: [
207
+ {
208
+ type: 'oauth',
209
+ label: 'LiteLLM SSO',
210
+ prompts: [
211
+ ...proxyPrompts,
212
+ {
213
+ type: 'select',
214
+ key: 'teamChoice',
215
+ message: 'LiteLLM team',
216
+ options: [
217
+ {
218
+ label: 'Default',
219
+ value: 'default',
220
+ hint: 'LiteLLM asks only when your account has several',
221
+ },
222
+ { label: 'A specific team…', value: 'other' },
223
+ ],
224
+ },
225
+ {
226
+ type: 'text',
227
+ key: 'team',
228
+ message: 'LiteLLM team ID or alias',
229
+ when: { key: 'teamChoice', op: 'eq', value: 'other' },
230
+ },
231
+ ],
232
+ authorize: async (inputs = {}) => {
233
+ const baseURL = proxyFor(inputs, target(), providerID)
234
+ if (!baseURL) throw new Error('Enter the LiteLLM proxy URL, or set LITELLM_BASE_URL')
235
+ const team = inputs.teamChoice === 'other' ? text(inputs.team) : undefined
236
+ return toAuthResult(await authorizeLiteLLM(baseURL, target().headers, team))
237
+ },
238
+ },
239
+ {
240
+ type: 'oauth',
241
+ label: 'Identity provider (OIDC)',
242
+ prompts: [
243
+ ...proxyPrompts,
244
+ {
245
+ type: 'text',
246
+ key: 'issuer',
247
+ message: "Your identity provider's issuer URL",
248
+ placeholder: 'https://idp.example.com',
249
+ },
250
+ {
251
+ type: 'text',
252
+ key: 'clientId',
253
+ message:
254
+ 'Public client ID (no secret) for the redirect http://127.0.0.1:<port>/callback',
255
+ },
256
+ {
257
+ type: 'select',
258
+ key: 'scope',
259
+ message: 'Scopes',
260
+ options: [
261
+ { label: 'openid', value: 'openid' },
262
+ {
263
+ label: 'openid offline_access',
264
+ value: 'openid offline_access',
265
+ hint: 'some identity providers only issue refresh tokens with it',
266
+ },
267
+ { label: 'Other scopes…', value: 'other' },
268
+ ],
269
+ },
270
+ {
271
+ type: 'text',
272
+ key: 'customScope',
273
+ message: 'Scopes, space-separated, including openid',
274
+ when: { key: 'scope', op: 'eq', value: 'other' },
275
+ },
276
+ {
277
+ type: 'select',
278
+ key: 'ports',
279
+ message: 'Redirect port',
280
+ options: [
281
+ { label: 'Any free port', value: 'any' },
282
+ {
283
+ label: 'Specific ports…',
284
+ value: 'specific',
285
+ hint: 'for identity providers that only accept exact registered redirect URIs',
286
+ },
287
+ ],
288
+ },
289
+ {
290
+ type: 'text',
291
+ key: 'redirectPorts',
292
+ message: 'Ports to try, in order',
293
+ placeholder: '8400, 8401',
294
+ when: { key: 'ports', op: 'eq', value: 'specific' },
295
+ },
296
+ ],
297
+ authorize: async (inputs = {}) => {
298
+ // Nothing is sent to the proxy, so its URL is only recorded for discovery.
299
+ const baseURL = proxyFor(inputs, target(), providerID)
300
+ const config = parseOidcConfig({
301
+ issuer: text(inputs.issuer),
302
+ clientId: text(inputs.clientId),
303
+ scope: inputs.scope === 'other' ? text(inputs.customScope) : text(inputs.scope),
304
+ redirectPorts: inputs.ports === 'specific' ? text(inputs.redirectPorts) : undefined,
305
+ })
306
+ return toAuthResult(await authorizeOidc(config), baseURL)
307
+ },
308
+ },
309
+ { type: 'api', label: 'API key' },
310
+ ],
311
+ }
312
+ }