pi-lean-host 0.3.1 → 0.5.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/core/auth.ts CHANGED
@@ -1,14 +1,41 @@
1
1
  /**
2
- * Static-key auth — store-backed secret resolution + metadata-only footer.
2
+ * Auth — store-backed secret resolution + OAuth2 token resolution + the
3
+ * metadata-only auth footer.
3
4
  *
4
- * Both `api-fetch` (injection + fail-closed) and the `api-guide`/`api-fetch`
5
- * footers share this module. It reads the secrets store and exposes names
6
- * only — secret values never leave `resolveSecretHeaders`' resolved header
5
+ * Shared by `api-fetch` (injection + fail-closed), `api-guide`/`api-fetch`
6
+ * footers, and `/api oauth`. Reads the secrets store and the OAuth2 token
7
+ * store; exposes names only — secret values never leave the resolved header
7
8
  * map (which only the fetch pipeline consumes, never agent context).
9
+ *
10
+ * Import direction: this module imports `oauth-store.ts` (the footer and
11
+ * token resolution must read the token store); `oauth-store.ts` imports
12
+ * nothing from here, so the edge stays one-way and no cycle can form.
8
13
  */
9
14
 
10
- import type { AuthConfig, ApiGuide } from "./api-guide-types.js";
11
- import { readSecret, provisionedDomainsSuffix } from "./secrets-store.js";
15
+ import type {
16
+ ApiGuide,
17
+ AuthConfig,
18
+ OAuth2Auth,
19
+ OAuth2Grant,
20
+ OAuth2TokenEndpointAuthMethod,
21
+ StaticKeyAuth,
22
+ } from "./api-guide-types.js";
23
+ import {
24
+ isOAuth2Grant,
25
+ isOAuth2TokenEndpointAuthMethod,
26
+ oauth2GrantIssue,
27
+ OAUTH2_GRANTS,
28
+ OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS,
29
+ type OAuth2GrantIssue,
30
+ } from "./api-guide-types.js";
31
+ import {
32
+ listDomains,
33
+ listNames,
34
+ readSecret,
35
+ provisionedDomainsSuffix,
36
+ } from "./secrets-store.js";
37
+ import { readToken, writeToken, deleteToken, slotKey } from "./oauth-store.js";
38
+ import type { OAuthToken } from "./oauth-store.js";
12
39
 
13
40
  /**
14
41
  * The canonical secret-store key for a guide: its primary browsable domain.
@@ -31,29 +58,28 @@ export interface SecretResolution {
31
58
  * audit — a server may echo the bare token, not just the prefixed form.
32
59
  */
33
60
  rawHeaderValues: string[];
34
- /** secret names referenced by `requires` that are absent from the store. */
61
+ /** secret names referenced by required refs that are absent from the store. */
35
62
  absentRequired: string[];
36
- /** secret names referenced by `optional` that are absent from the store. */
63
+ /** secret names referenced by optional refs that are absent from the store. */
37
64
  absentOptional: string[];
38
65
  }
39
66
 
40
- /** Resolve store-secret headers for a `static-key` guide (no-op otherwise). */
67
+ /** Resolve store-secret headers for a `static-key` guide. */
41
68
  export function resolveSecretHeaders(
42
- auth: AuthConfig,
69
+ auth: StaticKeyAuth,
43
70
  domain: string,
44
71
  ): SecretResolution {
45
72
  const headers: Record<string, string> = {};
46
73
  const rawHeaderValues: string[] = [];
47
74
  const absentRequired: string[] = [];
48
75
  const absentOptional: string[] = [];
49
- const requires = auth.requires ?? [];
50
- for (const [headerName, secretName] of Object.entries(auth.secretRefs ?? {})) {
51
- const value = readSecret(domain, secretName);
76
+ for (const [headerName, ref] of Object.entries(auth.secretRefs ?? {})) {
77
+ const value = readSecret(domain, ref.secret);
52
78
  if (value === null) {
53
- if (requires.includes(secretName)) absentRequired.push(secretName);
54
- else absentOptional.push(secretName);
79
+ if (ref.optional) absentOptional.push(ref.secret);
80
+ else absentRequired.push(ref.secret);
55
81
  } else {
56
- headers[headerName] = (auth.headerPrefixes?.[headerName] ?? "") + value;
82
+ headers[headerName] = (ref.prefix ?? "") + value;
57
83
  rawHeaderValues.push(value);
58
84
  }
59
85
  }
@@ -64,33 +90,30 @@ export function resolveSecretHeaders(
64
90
  export interface QuerySecretResolution {
65
91
  /** paramName → resolved value, injected below the agent params map. */
66
92
  queryParams: Record<string, string>;
67
- /** secret names referenced by `requires` that are absent from the store. */
93
+ /** secret names referenced by required refs that are absent from the store. */
68
94
  absentRequired: string[];
69
- /** secret names referenced by `optional` that are absent from the store. */
95
+ /** secret names referenced by optional refs that are absent from the store. */
70
96
  absentOptional: string[];
71
97
  }
72
98
 
73
99
  /**
74
100
  * Resolve store-secret query params for a `static-key` guide. Mirrors
75
- * `resolveSecretHeaders`: reads the store, splits absents by requires vs
76
- * optional. The values are injected below the agent-supplied params map by
77
- * the fetch pipeline and never enter agent context.
101
+ * `resolveSecretHeaders`: reads the store, splits absents by ref.optional.
102
+ * The values are injected below the agent-supplied params map by the fetch
103
+ * pipeline and never enter agent context.
78
104
  */
79
105
  export function resolveSecretQueryParams(
80
- auth: AuthConfig,
106
+ auth: StaticKeyAuth,
81
107
  domain: string,
82
108
  ): QuerySecretResolution {
83
109
  const queryParams: Record<string, string> = {};
84
110
  const absentRequired: string[] = [];
85
111
  const absentOptional: string[] = [];
86
- const requires = auth.requires ?? [];
87
- for (const [paramName, secretName] of Object.entries(
88
- auth.secretQueryRefs ?? {},
89
- )) {
90
- const value = readSecret(domain, secretName);
112
+ for (const [paramName, ref] of Object.entries(auth.secretQueryRefs ?? {})) {
113
+ const value = readSecret(domain, ref.secret);
91
114
  if (value === null) {
92
- if (requires.includes(secretName)) absentRequired.push(secretName);
93
- else absentOptional.push(secretName);
115
+ if (ref.optional) absentOptional.push(ref.secret);
116
+ else absentRequired.push(ref.secret);
94
117
  } else {
95
118
  queryParams[paramName] = value;
96
119
  }
@@ -98,62 +121,183 @@ export function resolveSecretQueryParams(
98
121
  return { queryParams, absentRequired, absentOptional };
99
122
  }
100
123
 
124
+ /**
125
+ * Resolve store-secret path tokens for a `static-key` guide. Mirrors
126
+ * `resolveSecretQueryParams` minus the optional arm: `secretPathRefs` are
127
+ * required-only (parse rejects `optional` — a path-keyed API has no
128
+ * unauthenticated state), so any store miss joins a single `missing` list
129
+ * and the caller fails closed. Values are the RAW secret (no prefix — path
130
+ * injection is verbatim; parse rejects `prefix` on path refs) and never
131
+ * enter agent context — they fill `{name}` in the op path at fetch time.
132
+ */
133
+ export interface PathSecretResolution {
134
+ /** pathTokenName → resolved raw value, injected below the agent params map. */
135
+ values: Record<string, string>;
136
+ /** secret names referenced by path refs that are absent from the store. */
137
+ missing: string[];
138
+ }
139
+
140
+ export function resolveSecretPathParams(
141
+ auth: StaticKeyAuth,
142
+ domain: string,
143
+ ): PathSecretResolution {
144
+ const values: Record<string, string> = {};
145
+ const missing: string[] = [];
146
+ for (const [tokenName, ref] of Object.entries(auth.secretPathRefs ?? {})) {
147
+ const value = readSecret(domain, ref.secret);
148
+ if (value === null) missing.push(ref.secret);
149
+ else values[tokenName] = value;
150
+ }
151
+ return { values, missing };
152
+ }
153
+
154
+ /**
155
+ * Fold the three resolver results into one deduped list of missing required
156
+ * secret names (a secret may be referenced by more than one ref map). One
157
+ * derivation shared by resolve-op, the /api verify precheck, and the auth
158
+ * status footer.
159
+ */
160
+ export function missingRequiredSecrets(
161
+ headerRes: SecretResolution,
162
+ queryRes: QuerySecretResolution,
163
+ pathRes: PathSecretResolution,
164
+ ): string[] {
165
+ return [
166
+ ...new Set([
167
+ ...headerRes.absentRequired,
168
+ ...queryRes.absentRequired,
169
+ ...pathRes.missing,
170
+ ]),
171
+ ];
172
+ }
173
+
174
+ /**
175
+ * Path-token names owned by `secretPathRefs` — store-filled, never
176
+ * caller-supplied, so never unsatisfiable (see `unsatisfiable`).
177
+ */
178
+ export function secretPathTokenNames(auth: AuthConfig): ReadonlySet<string> {
179
+ return auth.kind === "static-key"
180
+ ? new Set(Object.keys(auth.secretPathRefs ?? {}))
181
+ : new Set<string>();
182
+ }
183
+
184
+ /**
185
+ * Secret store-names a guide's auth block declares, from `auth.secretRefs`,
186
+ * and `auth.secretQueryRefs` (ref.secret values). For oauth2 the clientId/
187
+ * clientSecret refs are declared too — their store names are resolved
188
+ * per-user, so assisted provisioning should prompt for them. Empty for
189
+ * guides without keyed/oauth auth. Single source of truth for both the
190
+ * `/api secrets` assisted-entry and the `api-store` declared/gap report.
191
+ */
192
+ export function declaredSecretRefNames(guide: ApiGuide): string[] {
193
+ const names = new Set<string>();
194
+ switch (guide.auth.kind) {
195
+ case "static-key":
196
+ for (const ref of Object.values(guide.auth.secretRefs ?? {}))
197
+ names.add(ref.secret);
198
+ for (const ref of Object.values(guide.auth.secretQueryRefs ?? {}))
199
+ names.add(ref.secret);
200
+ for (const ref of Object.values(guide.auth.secretPathRefs ?? {}))
201
+ names.add(ref.secret);
202
+ break;
203
+ case "oauth2":
204
+ // clientId/clientSecret are SecretRefs resolved per-user — declare
205
+ // their store names so assisted provisioning prompts for them.
206
+ for (const ref of [guide.auth.clientId, guide.auth.clientSecret])
207
+ if (ref) names.add(ref.secret);
208
+ for (const ref of Object.values(guide.auth.secretRefs ?? {}))
209
+ names.add(ref.secret);
210
+ break;
211
+ case "none":
212
+ break;
213
+ default: {
214
+ const _exhaustive: never = guide.auth;
215
+ throw new Error(`Unhandled auth kind: ${_exhaustive}`);
216
+ }
217
+ }
218
+ return [...names].sort((a, b) => a.localeCompare(b));
219
+ }
220
+
101
221
  /**
102
222
  * Metadata-only auth status footer line, shared by `api-guide` and `api-fetch`.
103
- * Five states: no-auth (→ undefined) / ok / nudge-provision (required absent) /
104
- * ok-optional (optionals provisioned) / optional-not-provisioned.
105
- * Covers BOTH `secretRefs` (header) and `secretQueryRefs` (query) ref maps.
106
- * Never renders a secret value — names only.
223
+ * Five static-key states (no-auth → undefined / ok / nudge-provision /
224
+ * ok-optional / optional-not-provisioned) plus the oauth2 states (ok /
225
+ * expired-but-refreshable / missing → nudge /api oauth). Never renders a
226
+ * secret value — names only.
107
227
  */
108
228
  export function authStatusLine(
109
229
  auth: AuthConfig,
110
230
  domain: string,
111
231
  ): string | undefined {
112
- if (auth.kind !== "static-key") return undefined;
113
- // Nothing to report when neither ref map has an entry (empty maps are valid
114
- // = no injection). Length-based, matching the pre-query-ref "no footer"
115
- // semantics for an empty `secretRefs`, while still covering query-only guides.
116
- if (
117
- Object.keys(auth.secretRefs ?? {}).length === 0 &&
118
- Object.keys(auth.secretQueryRefs ?? {}).length === 0
119
- )
120
- return undefined;
121
- const headerRes = resolveSecretHeaders(auth, domain);
122
- const queryRes = resolveSecretQueryParams(auth, domain);
123
- // Dedupe across the two ref maps: a secret injected into both a header
124
- // and a query param must be named once, not twice.
125
- const absentRequired = [
126
- ...new Set([...headerRes.absentRequired, ...queryRes.absentRequired]),
127
- ];
128
- if (absentRequired.length > 0) {
129
- return (
130
- `🔑 auth: requires ${absentRequired.join(", ")} — not provisioned. ` +
131
- `Run /api secrets ${domain}.` +
132
- provisionedDomainsSuffix(domain)
133
- );
134
- }
135
- // The optional dimension only exists for optional names actually referenced
136
- // by a ref (an `optional` name with no ref is meaningless).
137
- const refValues = new Set([
138
- ...Object.values(auth.secretRefs ?? {}),
139
- ...Object.values(auth.secretQueryRefs ?? {}),
140
- ]);
141
- const referencedOptional = (auth.optional ?? []).filter((n) =>
142
- refValues.has(n),
143
- );
144
- if (referencedOptional.length > 0) {
145
- const absentOptional = [
146
- ...new Set([...headerRes.absentOptional, ...queryRes.absentOptional]),
147
- ];
148
- if (absentOptional.length > 0) {
149
- return (
150
- `🔑 auth: ok (optional ${absentOptional.join(", ")} not ` +
151
- `provisioned — unauthenticated; provision with /api secrets ${domain} for higher limits)`
152
- );
232
+ switch (auth.kind) {
233
+ case "none":
234
+ return undefined;
235
+ case "static-key": {
236
+ // Nothing to report when no ref map has an entry (empty maps are
237
+ // valid = no injection). A path-secret-only guide must render as
238
+ // keyed auth, not "no auth".
239
+ if (
240
+ Object.keys(auth.secretRefs ?? {}).length === 0 &&
241
+ Object.keys(auth.secretQueryRefs ?? {}).length === 0 &&
242
+ Object.keys(auth.secretPathRefs ?? {}).length === 0
243
+ )
244
+ return undefined;
245
+ const headerRes = resolveSecretHeaders(auth, domain);
246
+ const queryRes = resolveSecretQueryParams(auth, domain);
247
+ const pathRes = resolveSecretPathParams(auth, domain);
248
+ const absentRequired = missingRequiredSecrets(headerRes, queryRes, pathRes);
249
+ if (absentRequired.length > 0) {
250
+ return (
251
+ `🔑 auth: requires ${absentRequired.join(", ")} — not provisioned. ` +
252
+ `Run /api secrets ${domain}.` +
253
+ provisionedDomainsSuffix(domain)
254
+ );
255
+ }
256
+ // The optional dimension only exists for refs actually marked
257
+ // optional (a ref with optional: true). Path refs are required-only
258
+ // (parse rejects `optional`), so they never contribute here — the
259
+ // spread is for hand-built auth symmetry only.
260
+ const referencedOptional = [
261
+ ...Object.entries(auth.secretRefs ?? {}),
262
+ ...Object.entries(auth.secretQueryRefs ?? {}),
263
+ ...Object.entries(auth.secretPathRefs ?? {}),
264
+ ]
265
+ .filter(([, r]) => r.optional)
266
+ .map(([, r]) => r.secret);
267
+ if (referencedOptional.length > 0) {
268
+ const absentOptional = [
269
+ ...new Set([...headerRes.absentOptional, ...queryRes.absentOptional]),
270
+ ];
271
+ if (absentOptional.length > 0) {
272
+ return (
273
+ `🔑 auth: ok (optional ${absentOptional.join(", ")} not ` +
274
+ `provisioned — unauthenticated; provision with /api secrets ${domain} for higher limits)`
275
+ );
276
+ }
277
+ return "🔑 auth: ok (optional provisioned)";
278
+ }
279
+ return "🔑 auth: ok";
280
+ }
281
+ case "oauth2": {
282
+ const token = readToken(domain, auth.grant, auth.tokenUrl);
283
+ if (!token) {
284
+ return `🔑 auth: oauth2 — no token. Run /api oauth ${domain}.`;
285
+ }
286
+ if (isTokenExpired(token)) {
287
+ return (
288
+ `🔑 auth: oauth2 — token expired` +
289
+ (token.refreshToken
290
+ ? `, refreshable. Run /api oauth ${domain} --refresh.`
291
+ : `. Run /api oauth ${domain} to re-mint.`)
292
+ );
293
+ }
294
+ return "🔑 auth: ok (oauth2)";
295
+ }
296
+ default: {
297
+ const _exhaustive: never = auth;
298
+ throw new Error(`Unhandled auth kind: ${_exhaustive}`);
153
299
  }
154
- return "🔑 auth: ok (optional provisioned)";
155
300
  }
156
- return "🔑 auth: ok";
157
301
  }
158
302
 
159
303
  /**
@@ -184,3 +328,779 @@ export function scrubSecretValues(
184
328
  }
185
329
  return text;
186
330
  }
331
+
332
+ // ═══════════════════════════════════════════════════════════════════
333
+ // OAuth2 token resolution (client_credentials + lazy refresh)
334
+ // ═══════════════════════════════════════════════════════════════════
335
+
336
+ /**
337
+ * Thrown when an OAuth2 token can't be produced without human action (no
338
+ * cached token, no client_secret to mint, or an auth-code guide with no
339
+ * interactive flow). Callers fail closed and nudge `/api oauth <domain>`.
340
+ */
341
+ export class OAuthTokenMissingError extends Error {
342
+ constructor(message: string) {
343
+ super(message);
344
+ this.name = "OAuthTokenMissingError";
345
+ }
346
+ }
347
+
348
+ /** Resolved OAuth2 token injection, shaped to drop straight into AuthOpts. */
349
+ export interface AccessTokenResult {
350
+ authHeaders?: Record<string, string>;
351
+ secretHeaderNames?: Set<string>;
352
+ secretQueryParams?: Record<string, string>;
353
+ secretQueryParamNames?: Set<string>;
354
+ secretValues: string[];
355
+ }
356
+
357
+ /** Granted scopes for a minted token: what the provider echoed at mint;
358
+ * absent → the requested scopes with `assumed: true` (RFC 6749 §5.1 —
359
+ * granted = requested). Empty when neither is on record. */
360
+ export function grantedScopes(
361
+ scope: string | undefined,
362
+ requested: string[],
363
+ ): { scopes: string[]; assumed: boolean } {
364
+ const echo = scope?.split(/\s+/).filter(Boolean) ?? [];
365
+ if (echo.length > 0) return { scopes: echo, assumed: false };
366
+ return { scopes: requested, assumed: requested.length > 0 };
367
+ }
368
+
369
+ /** Refresh the access token one round trip before real expiry. */
370
+ const EXPIRY_SKEW_MS = 60_000;
371
+
372
+ /** True when a cached token should be refreshed/re-minted (skewed early). */
373
+ export function isTokenExpired(
374
+ token: OAuthToken,
375
+ now: number = Date.now(),
376
+ ): boolean {
377
+ if (token.expiresAt === undefined) {
378
+ // ponytail: no expires_in → treat as fresh; a provider that omits it
379
+ // will 401 and the next call re-mints. Add a TTL heuristic if a real
380
+ // recipe's short TTL makes this hurt.
381
+ return false;
382
+ }
383
+ return now >= token.expiresAt - EXPIRY_SKEW_MS;
384
+ }
385
+
386
+ /**
387
+ * Per-slot in-process lock keyed by `(storeDomain, slot)` — the same slot
388
+ * derivation the token store uses (two derivations that can diverge would be
389
+ * a second clobber), so concurrent `api-fetch` calls for the same slot
390
+ * serialize on one read-check-refresh-write sequence. Without it, two
391
+ * parallel calls that both see an expired token could race a refresh and
392
+ * double-spend a rotated refresh token. Cross-slot calls don't serialize —
393
+ * they touch different records; the store's synchronous read-modify-write
394
+ * keeps them atomic wrt the event loop.
395
+ */
396
+ const tokenLocks = new Map<string, Promise<unknown>>();
397
+
398
+ /**
399
+ * Run `fn` while holding the per-slot lock — serializes any read-check-refresh-write
400
+ * sequence for `(storeDomain, slot)`, so `--refresh`/mint paths can't race an
401
+ * agent's `resolveAccessToken` into double-spending a rotated refresh token.
402
+ */
403
+ async function withSlotLock<T>(
404
+ auth: OAuth2Auth,
405
+ domain: string,
406
+ fn: () => Promise<T>,
407
+ ): Promise<T> {
408
+ const lockKey = `${domain}:${slotKey(auth.grant, auth.tokenUrl)}`;
409
+ // Chain onto the current holder instead of wait-then-run: everyone who
410
+ // awaited the same in-flight promise would otherwise resume as a herd and
411
+ // run fn() concurrently (double-spending a rotated refresh token).
412
+ const prev = tokenLocks.get(lockKey) ?? Promise.resolve();
413
+ const next = prev.catch(() => {}).then(fn);
414
+ tokenLocks.set(lockKey, next);
415
+ try {
416
+ return await next;
417
+ } finally {
418
+ if (tokenLocks.get(lockKey) === next) tokenLocks.delete(lockKey);
419
+ }
420
+ }
421
+
422
+ /**
423
+ * Resolve an access token for an oauth2 auth (guide-backed or synthetic):
424
+ * cached → lazy refresh → client-credentials mint. Reads the token store
425
+ * fresh on every call (no closure cache) so a refresh on op N is visible to
426
+ * op N+1 during a long `/api verify` run. Fail-closed: throws `OAuthTokenMissingError` when no
427
+ * token exists and none can be minted.
428
+ */
429
+ export async function resolveAccessToken(
430
+ auth: OAuth2Auth,
431
+ domain: string,
432
+ ): Promise<AccessTokenResult> {
433
+ return withSlotLock(auth, domain, () => resolveTokenUnlocked(auth, domain));
434
+ }
435
+
436
+ async function resolveTokenUnlocked(
437
+ auth: OAuth2Auth,
438
+ domain: string,
439
+ ): Promise<AccessTokenResult> {
440
+ let token = readToken(domain, auth.grant, auth.tokenUrl);
441
+ if (token && !isTokenExpired(token))
442
+ return toAccessTokenResult(auth, token, domain);
443
+ if (token?.refreshToken) {
444
+ try {
445
+ token = await refreshAccessToken(auth, domain, token.refreshToken);
446
+ writeToken(domain, auth.grant, auth.tokenUrl, token);
447
+ return toAccessTokenResult(auth, token, domain);
448
+ } catch {
449
+ // Refresh failed (rotated/revoked refresh token, endpoint down) —
450
+ // fall through to re-mint; the mint surfaces the real failure.
451
+ }
452
+ }
453
+ if (auth.grant === "client_credentials") {
454
+ token = await mintClientCredentialsToken(auth, domain);
455
+ writeToken(domain, auth.grant, auth.tokenUrl, token);
456
+ return toAccessTokenResult(auth, token, domain);
457
+ }
458
+ // authorization_code: no interactive mint here — fail closed with
459
+ // a nudge to /api oauth.
460
+ throw new OAuthTokenMissingError(
461
+ `No usable OAuth2 token for '${domain}' (grant: authorization_code). ` +
462
+ `Run /api oauth ${domain} to start the interactive flow.`,
463
+ );
464
+ }
465
+
466
+ /**
467
+ * Loud misconfiguration guard: a static `Authorization` header (from
468
+ * secretRefs) collides with the oauth2 bearer injection — fetch merges
469
+ * same-named headers case-insensitively, so both would ride one garbled
470
+ * `Authorization: Bearer x, Bearer y` header. Fail loudly instead.
471
+ */
472
+ export function assertNoBearerCollision(
473
+ headers: Record<string, string>,
474
+ source: string,
475
+ ): void {
476
+ const clash = Object.keys(headers).find(
477
+ (k) => k.toLowerCase() === "authorization",
478
+ );
479
+ if (clash !== undefined) {
480
+ throw new Error(
481
+ `oauth2 bearer injection collides with the static '${clash}' header declared via ${source} — ` +
482
+ `declare the secret under a different header (e.g. Client-Id) or set paramStyle: query.`,
483
+ );
484
+ }
485
+ }
486
+
487
+ /** Map a token set onto the AuthOpts shape (bearer-header or query style). */
488
+ function toAccessTokenResult(
489
+ auth: OAuth2Auth,
490
+ token: OAuthToken,
491
+ domain: string,
492
+ ): AccessTokenResult {
493
+ // secretRefs (e.g. Twitch's Client-Id) merge onto the same header map —
494
+ // SAME semantics as static-key: resolved from the secrets store,
495
+ // fail-closed when a required one is missing.
496
+ const resolvedHeaders: Record<string, string> = {};
497
+ const resolvedValues: string[] = [];
498
+ for (const [headerName, ref] of Object.entries(auth.secretRefs ?? {})) {
499
+ const value = readSecret(domain, ref.secret);
500
+ if (value === null) {
501
+ if (ref.optional) continue;
502
+ throw new OAuthTokenMissingError(
503
+ `OAuth2 request header '${headerName}' needs the secret '${ref.secret}' provisioned ` +
504
+ `for '${domain}'. Run /api secrets ${domain} then /api oauth ${domain}.`,
505
+ );
506
+ }
507
+ resolvedHeaders[headerName] = (ref.prefix ?? "") + value;
508
+ resolvedValues.push(value);
509
+ }
510
+ const style = auth.paramStyle ?? "bearer-header";
511
+ if (style === "query") {
512
+ // RFC 6750 §2.3 — the query-injected param name is `access_token`.
513
+ return {
514
+ ...(Object.keys(resolvedHeaders).length > 0
515
+ ? {
516
+ authHeaders: resolvedHeaders,
517
+ // Strip them on cross-domain redirect hops, same as bearer style.
518
+ secretHeaderNames: new Set(
519
+ Object.keys(resolvedHeaders).map((h) => h.toLowerCase()),
520
+ ),
521
+ }
522
+ : {}),
523
+ secretQueryParams: { access_token: token.accessToken },
524
+ secretQueryParamNames: new Set(["access_token"]),
525
+ secretValues: [token.accessToken, ...resolvedValues],
526
+ };
527
+ }
528
+ assertNoBearerCollision(resolvedHeaders, "secretRefs");
529
+ return {
530
+ authHeaders: {
531
+ authorization: `Bearer ${token.accessToken}`,
532
+ ...resolvedHeaders,
533
+ },
534
+ secretHeaderNames: new Set([
535
+ "authorization",
536
+ ...Object.keys(resolvedHeaders).map((h) => h.toLowerCase()),
537
+ ]),
538
+ secretValues: [token.accessToken, ...resolvedValues],
539
+ };
540
+ }
541
+
542
+ /**
543
+ * The client credentials for an oauth2 guide: resolved from the secrets
544
+ * store via the guide's named `clientId` / `clientSecret` SecretRefs
545
+ * (store-resolved values appear ONLY as `SecretRef.secret` — a shippable
546
+ * guide bakes in no per-user registration). Null secret when the guide
547
+ * declares no `clientSecret` (PKCE auth-code apps) or the store lacks it.
548
+ * Throws `OAuthTokenMissingError` when the client id's store name is absent —
549
+ * the token endpoint cannot be called without it — or when a declared,
550
+ * non-optional `clientSecret` is unprovisioned (fail closed with a naming
551
+ * nudge rather than silently degrading to an unauthenticated public client
552
+ * and a bare provider `invalid_client` at exchange time).
553
+ */
554
+ export function resolveClientCredentials(
555
+ auth: OAuth2Auth,
556
+ domain: string,
557
+ ): {
558
+ clientId: string;
559
+ clientSecret: { secret: string; refName: string } | null;
560
+ } {
561
+ const clientId = readSecret(domain, auth.clientId.secret);
562
+ if (clientId === null) {
563
+ throw new OAuthTokenMissingError(
564
+ `OAuth2 needs the client id '${auth.clientId.secret}' provisioned ` +
565
+ `for '${domain}'. Run /api secrets ${domain} then /api oauth ${domain}.`,
566
+ );
567
+ }
568
+ const ref = auth.clientSecret;
569
+ const clientSecret = ref ? readSecret(domain, ref.secret) : null;
570
+ if (ref && clientSecret === null && !ref.optional) {
571
+ throw new OAuthTokenMissingError(
572
+ `OAuth2 client secret '${ref.secret}' is declared but not provisioned ` +
573
+ `for '${domain}'. Run /api secrets ${domain} ${ref.secret}, or mark ` +
574
+ `the ref optional to proceed as a PKCE public client.`,
575
+ );
576
+ }
577
+ return {
578
+ clientId,
579
+ ...(clientSecret !== null && ref
580
+ ? { clientSecret: { secret: clientSecret, refName: ref.secret } }
581
+ : { clientSecret: null }),
582
+ };
583
+ }
584
+
585
+ /**
586
+ * Which of the given secrets-store NAMES are not provisioned for `domain`.
587
+ * Shared by oauth-mint and /api oauth init — both mint paths key credentials
588
+ * on store NAMEs (values never enter the transcript), so both precheck the
589
+ * same store before touching any prompt or endpoint.
590
+ */
591
+ export function missingCredentialNames(
592
+ domain: string,
593
+ names: string[],
594
+ ): string[] {
595
+ const provisioned = listNames(domain);
596
+ return names.filter((n) => !provisioned.includes(n));
597
+ }
598
+
599
+ /**
600
+ * Shared store-name precheck for both mint paths (oauth-mint tool +
601
+ * `/api oauth init`): returns the user-facing gap message, or null when all
602
+ * credential NAMES are provisioned. Keeps the security prose
603
+ * ("values never enter the transcript") in exactly one place.
604
+ * Caller decides delivery: notify (command) vs throw (tool).
605
+ */
606
+ export function credentialNameGap(
607
+ storeDomain: string,
608
+ clientId: string,
609
+ clientSecret?: string,
610
+ ): string | null {
611
+ const missing = missingCredentialNames(storeDomain, [
612
+ clientId,
613
+ ...(clientSecret === undefined ? [] : [clientSecret]),
614
+ ]);
615
+ if (missing.length === 0) return null;
616
+ return (
617
+ `OAuth2 client credentials must be provisioned store NAMEs, but ${missing.map((n) => `'${n}'`).join(", ")} ` +
618
+ `are not in the secrets store for '${storeDomain}'. ` +
619
+ `Provision them first: /api secrets ${storeDomain} <name> (values never enter the transcript).`
620
+ );
621
+ }
622
+
623
+ /**
624
+ * Mint-time overwrite warning: slots are keyed (domain, grant, tokenUrl), so
625
+ * a same-grant re-mint with different scopes/issuer silently replaces the
626
+ * previous token — the documented mitigation for the reserved slot-key seam
627
+ * (scopes/clientId are deliberately excluded from the key). Returns the
628
+ * warning text when a token already occupies the slot, else null; callers
629
+ * render via ctx.ui.notify (this module stays ui-free).
630
+ */
631
+ export function slotOverwriteWarning(
632
+ auth: OAuth2Auth,
633
+ domain: string,
634
+ ): string | null {
635
+ const existing = readToken(domain, auth.grant, auth.tokenUrl);
636
+ if (!existing) return null;
637
+ return `⚠ Overwriting an existing token for this slot (${auth.grant}) — previous scope: ${existing.scope ?? "(none)"}.`;
638
+ }
639
+
640
+ /**
641
+ * Fresh client_credentials mint: drop the slot's cached token, then mint.
642
+ * Shared by `/api oauth init` and oauth-mint — bootstrap paths that always
643
+ * want a fresh mint, never a cached token. Both must slot-scope the delete
644
+ * (a bare domain delete would leave a stale prior-grant/prior-issuer slot
645
+ * surviving the re-mint). NOTE: the plain command's `--refresh` arm stays
646
+ * inline — its delete is conditional on the flag; resolving the cached
647
+ * token is the default there.
648
+ */
649
+ export async function mintFreshClientCredentials(
650
+ auth: OAuth2Auth,
651
+ domain: string,
652
+ ): Promise<void> {
653
+ deleteToken(domain, auth.grant, auth.tokenUrl);
654
+ await resolveAccessToken(auth, domain);
655
+ }
656
+
657
+ /**
658
+ * True when a token can be produced without human interaction: a cached
659
+ * fresh token, a refreshable one, or (client_credentials) a provisioned
660
+ * client secret to mint from. Used by the `/api verify` precheck to
661
+ * fail-fast instead of surfacing N identical token-missing failures.
662
+ */
663
+ export function hasUsableTokenPath(auth: OAuth2Auth, domain: string): boolean {
664
+ const token = readToken(domain, auth.grant, auth.tokenUrl);
665
+ if (token && !isTokenExpired(token)) return true;
666
+ if (token?.refreshToken) return true;
667
+ if (auth.grant === "client_credentials") {
668
+ return (
669
+ readSecret(domain, auth.clientId.secret) !== null &&
670
+ auth.clientSecret !== undefined &&
671
+ readSecret(domain, auth.clientSecret.secret) !== null
672
+ );
673
+ }
674
+ return false;
675
+ }
676
+
677
+ /**
678
+ * Attach client authentication to a token-endpoint request (RFC 6749 §2.3):
679
+ * `client_secret_basic` → Basic Authorization header, `client_secret_post`
680
+ * (the default) → `client_secret` form field. Mutates `form` / `headers`.
681
+ * No-op without a client secret (PKCE public clients). Returns extra values
682
+ * callers must add to their `secretValues` scrub set — the Basic credential
683
+ * (`base64(clientId:secret)`, and its full header form) is a secret a
684
+ * token-endpoint error body can echo, just like the raw secret.
685
+ */
686
+ function applyClientAuth(
687
+ auth: OAuth2Auth,
688
+ clientId: string,
689
+ clientSecret: { secret: string } | null,
690
+ form: Record<string, string>,
691
+ headers: Record<string, string>,
692
+ ): string[] {
693
+ if (!clientSecret) return [];
694
+ const method = auth.tokenEndpointAuthMethod ?? "client_secret_post";
695
+ if (method === "client_secret_basic") {
696
+ const cred = Buffer.from(`${clientId}:${clientSecret.secret}`).toString(
697
+ "base64",
698
+ );
699
+ headers["authorization"] = "Basic " + cred;
700
+ return [cred, `Basic ${cred}`];
701
+ } else if (method === "client_secret_post") {
702
+ form["client_secret"] = clientSecret.secret;
703
+ }
704
+ return [];
705
+ }
706
+
707
+ /**
708
+ * Exchange an authorization code for a token set (PKCE verifier in the
709
+ * body). `redirectUri` must be the SAME URI sent in the authorize step.
710
+ * The client secret (when the guide declares one) rides per
711
+ * `tokenEndpointAuthMethod`; PKCE public clients send none.
712
+ */
713
+ export async function exchangeAuthCode(
714
+ auth: OAuth2Auth,
715
+ domain: string,
716
+ code: string,
717
+ redirectUri: string,
718
+ verifier: string,
719
+ ): Promise<OAuthToken> {
720
+ const { clientId, clientSecret } = resolveClientCredentials(auth, domain);
721
+ const form: Record<string, string> = {
722
+ grant_type: "authorization_code",
723
+ code,
724
+ redirect_uri: redirectUri,
725
+ client_id: clientId,
726
+ code_verifier: verifier,
727
+ };
728
+ const headers: Record<string, string> = {};
729
+ const clientAuthValues = applyClientAuth(
730
+ auth,
731
+ clientId,
732
+ clientSecret,
733
+ form,
734
+ headers,
735
+ );
736
+ const data = await oauthPost(auth.tokenUrl, form, headers, [
737
+ code,
738
+ ...(clientSecret ? [clientSecret.secret] : []),
739
+ ...clientAuthValues,
740
+ ]);
741
+ return tokenFromResponse(data);
742
+ }
743
+
744
+ /**
745
+ * Force a fresh token for an auth-code guide by refreshing via the stored
746
+ * refresh token (no re-consent). Throws `OAuthTokenMissingError` when there
747
+ * is no refresh token — the caller falls back to the interactive flow.
748
+ */
749
+ export async function forceRefreshToken(
750
+ auth: OAuth2Auth,
751
+ domain: string,
752
+ ): Promise<OAuthToken> {
753
+ return withSlotLock(auth, domain, () =>
754
+ forceRefreshTokenUnlocked(auth, domain),
755
+ );
756
+ }
757
+
758
+ async function forceRefreshTokenUnlocked(
759
+ auth: OAuth2Auth,
760
+ domain: string,
761
+ ): Promise<OAuthToken> {
762
+ const token = readToken(domain, auth.grant, auth.tokenUrl);
763
+ if (!token?.refreshToken) {
764
+ throw new OAuthTokenMissingError(
765
+ `No refresh token for '${domain}' — run /api oauth ${domain} to start the interactive flow.`,
766
+ );
767
+ }
768
+ const fresh = await refreshAccessToken(auth, domain, token.refreshToken);
769
+ writeToken(domain, auth.grant, auth.tokenUrl, fresh);
770
+ return fresh;
771
+ }
772
+
773
+ /**
774
+ * One POST to an OAuth2 endpoint (token/refresh/revoke) — the first non-GET
775
+ * requests host makes, kept OUT of `transport.ts` (GET-only by contract) in
776
+ * a small separate helper. `secretValues` are scrubbed from any error body
777
+ * so a server echoing a credential can't leak it into agent context.
778
+ *
779
+ * Returns the parsed JSON body, or `{}` for an empty/non-JSON body (valid
780
+ * for RFC 7009 revocation, which returns 200 OK with no body). Callers that
781
+ * need a token validate `access_token` themselves via `tokenFromResponse`.
782
+ */
783
+ async function oauthPost(
784
+ url: string,
785
+ form: Record<string, string>,
786
+ headers: Record<string, string>,
787
+ secretValues: string[],
788
+ ): Promise<Record<string, unknown>> {
789
+ // ponytail: fixed 30s matching transport's DEFAULT_TIMEOUT — configurable
790
+ // only if a provider ever needs more. Without this, a hung token endpoint
791
+ // holds the per-slot lock (and the user's command) until undici's 300s
792
+ // headersTimeout finally gives up.
793
+ const ac = new AbortController();
794
+ const timer = setTimeout(
795
+ () => ac.abort(new Error("OAuth2 endpoint timeout (30s)")),
796
+ 30_000,
797
+ );
798
+ try {
799
+ // The timer spans headers AND the body read — a server that sends
800
+ // headers then stalls mid-body is hung just as hard as one that never
801
+ // answers (mirrors singleGet's abort scope in transport.ts).
802
+ const res = await fetch(url, {
803
+ method: "POST",
804
+ redirect: "error", // token endpoints never redirect; a 3xx must not forward secret-bearing bodies
805
+ headers: {
806
+ "content-type": "application/x-www-form-urlencoded",
807
+ ...headers,
808
+ },
809
+ body: new URLSearchParams(form).toString(),
810
+ signal: ac.signal,
811
+ });
812
+ const text = await res.text();
813
+ if (!res.ok) {
814
+ // Scrub before slicing — a secret straddling the cut would otherwise
815
+ // leave its prefix unredacted.
816
+ throw new Error(
817
+ `OAuth2 endpoint ${res.status}: ${scrubSecretValues(text, secretValues).slice(0, 300)}`,
818
+ );
819
+ }
820
+ try {
821
+ const data = JSON.parse(text);
822
+ if (data && typeof data === "object" && !Array.isArray(data)) {
823
+ return data as Record<string, unknown>;
824
+ }
825
+ } catch {
826
+ // empty / non-JSON body — valid for revocation (RFC 7009)
827
+ }
828
+ return {};
829
+ } finally {
830
+ clearTimeout(timer);
831
+ }
832
+ }
833
+
834
+ function tokenFromResponse(data: Record<string, unknown>): OAuthToken {
835
+ const at = data["access_token"];
836
+ if (typeof at !== "string") {
837
+ throw new Error("OAuth2 token endpoint returned no access_token");
838
+ }
839
+ const token: OAuthToken = {
840
+ accessToken: at,
841
+ };
842
+ if (typeof data["refresh_token"] === "string") {
843
+ token.refreshToken = data["refresh_token"];
844
+ }
845
+ // Some providers return a string despite RFC 6749 §5.1 — coerce or the
846
+ // token is cached as eternal (isTokenExpired treats missing expiresAt as fresh).
847
+ const raw = data["expires_in"];
848
+ const expiresIn = typeof raw === "string" ? Number(raw) : raw;
849
+ if (typeof expiresIn === "number" && Number.isFinite(expiresIn)) {
850
+ token.expiresAt = Date.now() + expiresIn * 1000;
851
+ }
852
+ if (typeof data["scope"] === "string") token.scope = data["scope"];
853
+ return token;
854
+ }
855
+
856
+ /** Client-credentials mint: POST grant_type=client_credentials → token. */
857
+ async function mintClientCredentialsToken(
858
+ auth: OAuth2Auth,
859
+ domain: string,
860
+ ): Promise<OAuthToken> {
861
+ const { clientId, clientSecret } = resolveClientCredentials(auth, domain);
862
+ if (!clientSecret) {
863
+ const refName = auth.clientSecret?.secret ?? "client_secret";
864
+ throw new OAuthTokenMissingError(
865
+ `OAuth2 client_credentials needs the client secret '${refName}' provisioned ` +
866
+ `for '${domain}'. Run /api secrets ${domain} then /api oauth ${domain}.`,
867
+ );
868
+ }
869
+ const form: Record<string, string> = {
870
+ grant_type: "client_credentials",
871
+ client_id: clientId,
872
+ };
873
+ const headers: Record<string, string> = {};
874
+ const clientAuthValues = applyClientAuth(
875
+ auth,
876
+ clientId,
877
+ clientSecret,
878
+ form,
879
+ headers,
880
+ );
881
+ if (auth.scopes && auth.scopes.length > 0) {
882
+ form["scope"] = auth.scopes.join(" ");
883
+ }
884
+ const data = await oauthPost(auth.tokenUrl, form, headers, [
885
+ clientSecret.secret,
886
+ ...clientAuthValues,
887
+ ]);
888
+ return tokenFromResponse(data);
889
+ }
890
+
891
+ /** Lazy refresh: POST grant_type=refresh_token → fresh token set. */
892
+ async function refreshAccessToken(
893
+ auth: OAuth2Auth,
894
+ domain: string,
895
+ refreshToken: string,
896
+ ): Promise<OAuthToken> {
897
+ const { clientId, clientSecret } = resolveClientCredentials(auth, domain);
898
+ const form: Record<string, string> = {
899
+ grant_type: "refresh_token",
900
+ refresh_token: refreshToken,
901
+ client_id: clientId,
902
+ };
903
+ const headers: Record<string, string> = {};
904
+ const clientAuthValues = applyClientAuth(
905
+ auth,
906
+ clientId,
907
+ clientSecret,
908
+ form,
909
+ headers,
910
+ );
911
+ const data = await oauthPost(auth.tokenUrl, form, headers, [
912
+ refreshToken,
913
+ ...(clientSecret ? [clientSecret.secret] : []),
914
+ ...clientAuthValues,
915
+ ]);
916
+ const fresh = tokenFromResponse(data);
917
+ // RFC 6749 §6: the refresh response MAY omit refresh_token (e.g. GitHub,
918
+ // OSM) — the old one stays valid. Carry it forward so refresh capability
919
+ // isn't silently destroyed on the next expiry.
920
+ if (!fresh.refreshToken) fresh.refreshToken = refreshToken;
921
+ return fresh;
922
+ }
923
+
924
+ /**
925
+ * Best-effort revocation: POST the access token to the guide's declared
926
+ * `revokeUrl` (if any), then clear the local token store regardless.
927
+ */
928
+ export async function revokeAccessToken(
929
+ auth: OAuth2Auth,
930
+ domain: string,
931
+ ): Promise<void> {
932
+ const token = readToken(domain, auth.grant, auth.tokenUrl);
933
+ if (token && auth.revokeUrl) {
934
+ try {
935
+ const { clientId, clientSecret } = resolveClientCredentials(auth, domain);
936
+ const form: Record<string, string> = { token: token.accessToken };
937
+ const headers: Record<string, string> = {};
938
+ const clientAuthValues = applyClientAuth(
939
+ auth,
940
+ clientId,
941
+ clientSecret,
942
+ form,
943
+ headers,
944
+ );
945
+ await oauthPost(auth.revokeUrl, form, headers, [
946
+ token.accessToken,
947
+ ...(clientSecret ? [clientSecret.secret] : []),
948
+ ...clientAuthValues,
949
+ ]);
950
+ } catch {
951
+ // best-effort — the local store is cleared regardless
952
+ }
953
+ }
954
+ deleteToken(domain, auth.grant, auth.tokenUrl);
955
+ }
956
+
957
+ // ═══════════════════════════════════════════════════════════════
958
+ // Guide-less bootstrap — shared synthetic-auth construction
959
+ // ═══════════════════════════════════════════════════════════════
960
+
961
+ /**
962
+ * Secrets-store domain for a not-yet-guided hostname: the hostname when it is
963
+ * itself provisioned, else the longest provisioned parent domain
964
+ * (api.openstreetmap.org → openstreetmap.org), else the hostname as-is (fail
965
+ * at exchange, not silently). Matched against the SECRETS store — the wizard
966
+ * and the probe both resolve credentials from it. ponytail: parent-suffix
967
+ * match against the store, not a public-suffix list — no dep, and the store
968
+ * is the source of truth for where secrets live.
969
+ */
970
+ export function resolveProvisionedParentDomain(hostname: string): string {
971
+ const domains = listDomains();
972
+ if (domains.includes(hostname)) return hostname;
973
+ const parent = domains
974
+ .filter((d) => hostname.endsWith(`.${d}`))
975
+ .sort((a, b) => b.length - a.length)[0];
976
+ return parent ?? hostname;
977
+ }
978
+
979
+ /**
980
+ * Scrub-set forms for a resolved path-secret value: raw + both hex-encoded
981
+ * echo shapes (upper, as `fillPathTemplate` produces, and lower). A 401 body
982
+ * echoing the token inside a URL string (`bot123%3AABC…`) is the most likely
983
+ * echo shape — scrubSecretValues replaces raw values only. Single source for
984
+ * every site that folds path secrets into a body/header scrub set.
985
+ */
986
+ export function pathScrubValues(values: Record<string, string>): string[] {
987
+ return Object.values(values).flatMap((v) => {
988
+ if (v.length === 0) return [];
989
+ const enc = encodeURIComponent(v);
990
+ return [v, enc, enc.replace(/%../g, (s) => s.toLowerCase())];
991
+ });
992
+ }
993
+
994
+ /** Hostname of an apiHost URL (falls back to the raw string). */
995
+ export function hostnameOf(apiHost: string): string {
996
+ try {
997
+ return new URL(apiHost).hostname;
998
+ } catch {
999
+ return apiHost;
1000
+ }
1001
+ }
1002
+
1003
+ /** Fields the bootstrap surfaces collect into a synthetic `OAuth2Auth`. */
1004
+ export interface SyntheticOAuth2Fields {
1005
+ grant: OAuth2Grant;
1006
+ tokenUrl: string;
1007
+ /** secrets-store NAME — the value resolves at flow time, never a literal. */
1008
+ clientId: string;
1009
+ clientSecret?: string;
1010
+ authorizeUrl?: string;
1011
+ scopes?: string[];
1012
+ tokenEndpointAuthMethod?: OAuth2TokenEndpointAuthMethod;
1013
+ }
1014
+
1015
+ /**
1016
+ * Build a synthetic oauth2 auth for the guide-less bootstrap paths (`/api
1017
+ * oauth init <domain>` and api-probe's mint arm). Shared construction pattern:
1018
+ * the synthetic auth feeds the existing resolveAccessToken / mintAuthCodeToken
1019
+ * machinery, so cache/refresh/lock/stamp is shared code. Fail-closed (command
1020
+ * semantics — the probe wraps its own try/catch around the flow): invalid
1021
+ * combinations throw instead of parsing loosely.
1022
+ */
1023
+ export function buildSyntheticOAuth2Auth(f: SyntheticOAuth2Fields): OAuth2Auth {
1024
+ if (!isOAuth2Grant(f.grant)) {
1025
+ throw new Error(
1026
+ `--grant must be ${OAUTH2_GRANTS.join(" | ")} (got: ${String(f.grant)})`,
1027
+ );
1028
+ }
1029
+ if (!isHttpUrl(f.tokenUrl)) {
1030
+ throw new Error(`--token-url must be an http(s) URL (got: ${f.tokenUrl})`);
1031
+ }
1032
+ if (!f.clientId) {
1033
+ throw new Error("--client-id (a provisioned store NAME) is required.");
1034
+ }
1035
+ if (
1036
+ f.tokenEndpointAuthMethod !== undefined &&
1037
+ !isOAuth2TokenEndpointAuthMethod(f.tokenEndpointAuthMethod)
1038
+ ) {
1039
+ throw new Error(
1040
+ `--token-endpoint-auth-method must be ${OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS.join(" | ")} (got: ${String(f.tokenEndpointAuthMethod)})`,
1041
+ );
1042
+ }
1043
+ if (f.authorizeUrl !== undefined && !isHttpUrl(f.authorizeUrl)) {
1044
+ throw new Error(
1045
+ `--authorize-url must be an http(s) URL (got: ${f.authorizeUrl})`,
1046
+ );
1047
+ }
1048
+ // An empty-string secret is a mistyped flag, not a credential — treat it
1049
+ // as absent so client_credentials fails loudly here (store resolution
1050
+ // would only misreport it later).
1051
+ const clientSecret = f.clientSecret || undefined;
1052
+ // Grant invariants — shared with the guide parser (parse-api-guide.ts);
1053
+ // one statement of the cross-field rules for both surfaces.
1054
+ const issue = oauth2GrantIssue({
1055
+ grant: f.grant,
1056
+ hasClientSecret: clientSecret !== undefined,
1057
+ authorizeUrl: f.authorizeUrl,
1058
+ tokenEndpointAuthMethod: f.tokenEndpointAuthMethod,
1059
+ });
1060
+ if (issue) {
1061
+ throw new Error(syntheticGrantIssueMessage(issue.code));
1062
+ }
1063
+ const auth: OAuth2Auth = {
1064
+ kind: "oauth2",
1065
+ grant: f.grant,
1066
+ tokenUrl: f.tokenUrl,
1067
+ clientId: { secret: f.clientId },
1068
+ };
1069
+ if (clientSecret !== undefined) {
1070
+ auth.clientSecret = { secret: clientSecret };
1071
+ }
1072
+ if (f.scopes !== undefined && f.scopes.length > 0) {
1073
+ auth.scopes = f.scopes;
1074
+ }
1075
+ if (f.tokenEndpointAuthMethod !== undefined) {
1076
+ auth.tokenEndpointAuthMethod = f.tokenEndpointAuthMethod;
1077
+ }
1078
+ if (f.authorizeUrl !== undefined) {
1079
+ auth.authorizeUrl = f.authorizeUrl;
1080
+ }
1081
+ return auth;
1082
+ }
1083
+
1084
+ /** CLI-flag phrasing of the shared grant-invariant codes for the
1085
+ * bootstrap surfaces (`/api oauth init`, api-probe mint arm, oauth-mint). */
1086
+ function syntheticGrantIssueMessage(code: OAuth2GrantIssue["code"]): string {
1087
+ switch (code) {
1088
+ case "noneWithSecret":
1089
+ return "--token-endpoint-auth-method none sends no client credentials — drop --client-secret.";
1090
+ case "ccRequiresSecret":
1091
+ return "grant client_credentials requires --client-secret (a provisioned store NAME).";
1092
+ case "ccRejectsAuthorizeUrl":
1093
+ return "--authorize-url is only valid with --grant authorization_code (client_credentials is server-to-server).";
1094
+ case "acRequiresAuthorizeUrl":
1095
+ return "grant authorization_code requires --authorize-url (the provider's authorization endpoint).";
1096
+ }
1097
+ }
1098
+
1099
+ function isHttpUrl(s: string): boolean {
1100
+ try {
1101
+ const u = new URL(s);
1102
+ return u.protocol === "https:" || u.protocol === "http:";
1103
+ } catch {
1104
+ return false;
1105
+ }
1106
+ }