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.
@@ -0,0 +1,911 @@
1
+ /**
2
+ * `/api oauth <domain>` — provision / inspect / revoke OAuth2 tokens.
3
+ *
4
+ * - `oauth <domain>` — mint a token and stamp the token store.
5
+ * client_credentials: pure HTTP. authorization_code: print the authorize URL
6
+ * (redirect_uri = http://127.0.0.1/callback, RFC 8252 §7.3), the user
7
+ * consents in their own browser and pastes the redirect URL back — inline
8
+ * prompt (TUI) or `--code <redirect-url-or-code>` (headless/scripting).
9
+ * - `oauth <domain> --status` — metadata-only token state (no network).
10
+ * - `oauth <domain> --refresh` — force a fresh token (client_credentials:
11
+ * re-mint; authorization_code: refresh via the stored refresh token, or a
12
+ * fresh authorize URL when there is none).
13
+ * - `oauth <domain> --revoke` — revoke at the provider's revokeUrl (if declared) and clear the store.
14
+ * Tokens live in slot-keyed store entries (`<grant>__<hash(tokenUrl)>` within
15
+ * one `<domain>.json`), so an app token and a user token coexist per domain.
16
+ * - `oauth <domain> --code <code>` — complete an authorization-code flow with
17
+ * the pasted redirect URL (or bare code) from a previous authorize step.
18
+ * - `oauth init <domain> [flags]` — guide-less bootstrap: provision
19
+ * a token without an oauth2 guide. Interactive wizard (ctx.hasUI) or headless
20
+ * flags (--grant --token-url --client-id [--client-secret] [--authorize-url]
21
+ * [--scopes] [--token-endpoint-auth-method]); auth-code completion is the
22
+ * two-call `init <domain> <same flags> --code <paste>`. Client credentials
23
+ * are secrets-store NAMES picked from what's provisioned — values never
24
+ * enter the transcript.
25
+ * - `oauth` (bare) — list token-store slots (domain · grant · issuer) with status metadata.
26
+ *
27
+ * Tokens can outlive their guide (deleted via /api delete, or minted while
28
+ * testing), so bare listing, `--status`, and `--revoke` also work guide-less
29
+ * (keyed by the literal domain; revoke is then local-only — no revokeUrl
30
+ * without a guide). Minting/refreshing goes through the guide's flow, or
31
+ * guide-less through `init`.
32
+ *
33
+ * Always-available / not focus-guarded — a peer of `secrets`/`verify`/`delete`
34
+ * (writes the token store, not toolset state). The client secret lives in the
35
+ * secrets store; only minted tokens land here.
36
+ */
37
+
38
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
39
+ import { findGuidesByDomain } from "./guide-store.js";
40
+ import { pickGuideForCommand } from "./guide-picker.js";
41
+ import type { SelectItem } from "@earendil-works/pi-tui";
42
+ import { pickWithDescription } from "./select-picker.js";
43
+ import {
44
+ buildSyntheticOAuth2Auth,
45
+ canonicalStoreDomain,
46
+ credentialNameGap,
47
+ isTokenExpired,
48
+ mintFreshClientCredentials,
49
+ resolveAccessToken,
50
+ resolveProvisionedParentDomain,
51
+ revokeAccessToken,
52
+ slotOverwriteWarning,
53
+ OAuthTokenMissingError,
54
+ } from "./auth.js";
55
+ import type { OAuth2TokenEndpointAuthMethod } from "./api-guide-types.js";
56
+ import type { SyntheticOAuth2Fields } from "./auth.js";
57
+ import {
58
+ readToken,
59
+ deleteToken,
60
+ deletePendingFlow,
61
+ readPendingFlow,
62
+ listTokenDomains,
63
+ listSlots,
64
+ getOAuthDir,
65
+ } from "./oauth-store.js";
66
+ import type { OAuthToken } from "./oauth-store.js";
67
+ import { REDIRECT_URI, mintAuthCodeToken } from "./oauth-flow.js";
68
+ import { listNames } from "./secrets-store.js";
69
+ import type { OAuth2Grant } from "./api-guide-types.js";
70
+
71
+ /** Full usage + storage docs, surfaced by `--help`. */
72
+ function helpText(): string {
73
+ return [
74
+ "Usage: /api oauth <domain> [--status | --refresh | --revoke | --code <code>]",
75
+ " /api oauth <domain> mint a token and stamp the token store",
76
+ " (client_credentials: pure HTTP; authorization_code:",
77
+ " authorize URL + paste the redirect URL back)",
78
+ " /api oauth <domain> --status metadata-only token state (no network)",
79
+ " /api oauth <domain> --refresh force a fresh token (auth-code: refresh via the",
80
+ " stored refresh token, or a fresh authorize URL)",
81
+ " /api oauth <domain> --revoke revoke at the guide's revokeUrl (if declared) and clear the store",
82
+ " /api oauth <domain> --code <code> complete an auth-code flow with the pasted",
83
+ " redirect URL (or bare code)",
84
+ " /api oauth <domain> [--redirect-uri <url>] override the default redirect URI",
85
+ " (default http://127.0.0.1/callback; some providers",
86
+ " require the localhost spelling or https — match your",
87
+ " app registration; only matters for auth-code mint)",
88
+ " /api oauth init <domain> guide-less bootstrap (no oauth2 guide needed):",
89
+ " interactive wizard (TUI), or headless flags:",
90
+ " --grant client_credentials|authorization_code",
91
+ " --token-url <url> --client-id <store name>",
92
+ " [--client-secret <store name>] [--authorize-url <url>]",
93
+ " [--scopes a,b] [--token-endpoint-auth-method <method>]",
94
+ " auth-code completion (headless two-call): /api oauth init",
95
+ " <domain> <same flags> --code <redirect-url-or-code>",
96
+ " /api oauth list token-store domains (guide-independent);",
97
+ " --status/--revoke on orphaned tokens accept an",
98
+ " optional grant qualifier when the domain has 2+ slots",
99
+ "",
100
+ `Tokens are stored per-domain (0600) at ${getOAuthDir()}/<domain>.json, keyed by`,
101
+ "slot = <grant>__<hash(tokenUrl)> — one domain can hold an app token and a user",
102
+ "token (and tokens from two issuers) side by side. The client secret lives in",
103
+ "the secrets store (/api secrets <domain>), never here.",
104
+ ].join("\n");
105
+ }
106
+
107
+ function tokenState(token: OAuthToken): string {
108
+ return isTokenExpired(token)
109
+ ? `expired${token.refreshToken ? " (refreshable)" : ""}`
110
+ : "valid";
111
+ }
112
+
113
+ function tokenExpiry(token: OAuthToken): string {
114
+ return token.expiresAt === undefined
115
+ ? "unknown"
116
+ : new Date(token.expiresAt).toISOString();
117
+ }
118
+
119
+ /** State/Expires/Refresh/Scope detail lines shared by both --status arms. */
120
+ function tokenDetailLines(token: OAuthToken): string[] {
121
+ return [
122
+ ` State: ${tokenState(token)}`,
123
+ ` Expires: ${tokenExpiry(token)}`,
124
+ ...(token.refreshToken ? [" Refresh token: present"] : []),
125
+ ...(token.scope ? [` Scope: ${token.scope}`] : []),
126
+ ];
127
+ }
128
+
129
+ /** The grant qualifier accepted after a domain in `--status`/`--revoke`. */
130
+ const GRANT_QUALIFIERS: readonly OAuth2Grant[] = [
131
+ "client_credentials",
132
+ "authorization_code",
133
+ ];
134
+
135
+ /** Render slot rows (grant · issuer · state) for a listing / usage error. */
136
+ function slotRows(
137
+ slots: { grant: string; tokenUrl: string; token: OAuthToken }[],
138
+ ): string {
139
+ return slots
140
+ .map((s) => ` · ${s.grant} · ${s.tokenUrl} — ${tokenState(s.token)}`)
141
+ .join("\n");
142
+ }
143
+
144
+ /**
145
+ * Shared `--flag <value>` grammar for both oauth command arms. Each name in
146
+ * `valueFlags` consumes the following token as its value (position-based — a
147
+ * value that happens to spell a flag name is never mistaken for one); names
148
+ * in `boolFlags` are recognized bare; unknown `--flags` are rejected.
149
+ */
150
+ type FlagParse =
151
+ | {
152
+ ok: true;
153
+ flags: Record<string, string>;
154
+ bools: Set<string>;
155
+ positional: string[];
156
+ }
157
+ | { ok: false; message: string };
158
+
159
+ function parseFlags(
160
+ parts: readonly string[],
161
+ valueFlags: readonly string[],
162
+ boolFlags: readonly string[],
163
+ ): FlagParse {
164
+ const flags: Record<string, string> = {};
165
+ const bools = new Set<string>();
166
+ const positional: string[] = [];
167
+ for (let i = 0; i < parts.length; i++) {
168
+ const p = parts[i]!;
169
+ if (valueFlags.includes(p)) {
170
+ const value = parts[i + 1];
171
+ if (value === undefined) {
172
+ return {
173
+ ok: false,
174
+ message: `Flag '${p}' is missing its value — see /api oauth --help.`,
175
+ };
176
+ }
177
+ flags[p] = value;
178
+ i++;
179
+ continue;
180
+ }
181
+ if (boolFlags.includes(p)) {
182
+ bools.add(p);
183
+ continue;
184
+ }
185
+ if (p.startsWith("--")) {
186
+ return {
187
+ ok: false,
188
+ message: `Unknown flag '${p}' — see /api oauth --help.`,
189
+ };
190
+ }
191
+ positional.push(p);
192
+ }
193
+ return { ok: true, flags, bools, positional };
194
+ }
195
+
196
+ /**
197
+ * Handle the `oauth` subcommand of `/api`.
198
+ *
199
+ * @param args The text after "oauth" ("" / "<domain>" / "<domain> <flag>")
200
+ * @param ctx The extension command context
201
+ */
202
+ export async function handleOauthSubcommand(
203
+ args: string,
204
+ ctx: ExtensionCommandContext,
205
+ ): Promise<void> {
206
+ const parts = args.trim().split(/\s+/).filter(Boolean);
207
+
208
+ // `--help` (or `help`) short-circuits before domain dispatch.
209
+ if (parts.includes("--help") || parts.includes("help")) {
210
+ ctx.ui.notify(helpText(), "info");
211
+ return;
212
+ }
213
+
214
+ // `init` subcommand — guide-less bootstrap. Its own flag
215
+ // grammar, so it short-circuits before the plain-command parsing below.
216
+ if (parts[0] === "init") {
217
+ await handleOauthInit(args.trim().replace(/^init\b\s*/, ""), ctx);
218
+ return;
219
+ }
220
+
221
+ const parsed = parseFlags(
222
+ parts,
223
+ ["--code", "--redirect-uri"],
224
+ ["--status", "--refresh", "--revoke"],
225
+ );
226
+ if (!parsed.ok) {
227
+ ctx.ui.notify(parsed.message, "warning");
228
+ return;
229
+ }
230
+ const statusFlag = parsed.bools.has("--status");
231
+ const refreshFlag = parsed.bools.has("--refresh");
232
+ const revokeFlag = parsed.bools.has("--revoke");
233
+ // `--code` completes an auth-code flow with the pasted redirect URL (or
234
+ // bare code); `--redirect-uri <url>` overrides the RFC 8252 default for
235
+ // the mint arm — some providers constrain the spelling (Twitch: https or
236
+ // `localhost`; OSM: unencrypted must be 127.0.0.1). Stored on the pending
237
+ // flow, so the `--code` completion needs no flag.
238
+ const codeArg = parsed.flags["--code"];
239
+ const redirectUriArg = parsed.flags["--redirect-uri"];
240
+ const domain = parsed.positional[0];
241
+ const selector = parsed.positional[1];
242
+
243
+ if (!domain) {
244
+ // Flags without a domain are usage errors, never a silent no-op: an
245
+ // unacknowledged `--code` paste would strand a live auth-code flow.
246
+ if (statusFlag || refreshFlag || revokeFlag || codeArg || redirectUriArg) {
247
+ ctx.ui.notify(
248
+ "Missing <domain> — usage: /api oauth <domain> [--status | --refresh | --revoke | --code <code>]",
249
+ "warning",
250
+ );
251
+ return;
252
+ }
253
+ // Bare `/api oauth` — list the token store (guide-independent).
254
+ const domains = listTokenDomains();
255
+ if (domains.length === 0) {
256
+ ctx.ui.notify(
257
+ "🔑 OAuth2 token store is empty. Provision a token with /api oauth <domain> (needs an oauth2 guide) or guide-less with /api oauth init <domain> — see /api oauth --help.",
258
+ "info",
259
+ );
260
+ return;
261
+ }
262
+ const lines = ["🔑 OAuth2 token store:"];
263
+ for (const d of domains) {
264
+ const slots = listSlots(d);
265
+ if (slots.length === 0) {
266
+ lines.push(` ${d} — unreadable`);
267
+ continue;
268
+ }
269
+ for (const s of slots) {
270
+ lines.push(
271
+ ` ${d} · ${s.grant} · ${s.tokenUrl} — ${tokenState(s.token)}, expires ${tokenExpiry(s.token)}`,
272
+ );
273
+ }
274
+ }
275
+ ctx.ui.notify(lines.join("\n"), "info");
276
+ return;
277
+ }
278
+
279
+ // Resolve the guide by domain; only oauth2 guides are token-provisionable.
280
+ const allMatches = findGuidesByDomain(domain);
281
+ if (allMatches.length === 0) {
282
+ // Guide-less fallback: tokens can outlive their guide, so --status /
283
+ // --revoke work on the orphaned slots (all of them, or the one a grant
284
+ // qualifier names when the domain has 2+). The lookup applies the same
285
+ // parent-domain normalization `init` stamps with, so a subdomain spelling
286
+ // still finds the slots. Minting/refreshing still needs auth facts.
287
+ if (statusFlag || revokeFlag) {
288
+ const storeDomain = resolveProvisionedParentDomain(domain);
289
+ const qualifier = parsed.positional[1];
290
+ if (
291
+ qualifier !== undefined &&
292
+ !GRANT_QUALIFIERS.includes(qualifier as OAuth2Grant)
293
+ ) {
294
+ ctx.ui.notify(
295
+ `Unknown grant qualifier '${qualifier}' — use client_credentials or authorization_code.`,
296
+ "warning",
297
+ );
298
+ return;
299
+ }
300
+ const slots = listSlots(storeDomain);
301
+ if (slots.length === 0) {
302
+ ctx.ui.notify(
303
+ `🔑 OAuth2 for '${storeDomain}' (no guide): no token.`,
304
+ "info",
305
+ );
306
+ return;
307
+ }
308
+ const target =
309
+ qualifier === undefined
310
+ ? slots
311
+ : slots.filter((s) => s.grant === qualifier);
312
+ if (target.length === 0) {
313
+ ctx.ui.notify(
314
+ `🔑 OAuth2 for '${storeDomain}' — no '${qualifier}' slot. Slots:\n` +
315
+ slotRows(slots),
316
+ "info",
317
+ );
318
+ return;
319
+ }
320
+ if (target.length > 1) {
321
+ if (qualifier === undefined) {
322
+ // 2+ slots and no qualifier — list + usage error, never a guess.
323
+ ctx.ui.notify(
324
+ `🔑 OAuth2 for '${storeDomain}' (no guide) has ${target.length} slots — pass the grant qualifier (client_credentials | authorization_code):\n` +
325
+ slotRows(target),
326
+ "info",
327
+ );
328
+ return;
329
+ }
330
+ // Same grant on two issuers behind one domain — the grant qualifier
331
+ // alone can't disambiguate; list and stop, never a guess.
332
+ ctx.ui.notify(
333
+ `🔑 OAuth2 for '${storeDomain}' has ${target.length} '${qualifier}' slots (two issuers, same grant) — the grant qualifier alone can't disambiguate; use a guide-backed call.\n` +
334
+ slotRows(target),
335
+ "info",
336
+ );
337
+ return;
338
+ }
339
+ const slot = target[0]!;
340
+ if (statusFlag) {
341
+ const pending = readPendingFlow(storeDomain, slot.grant, slot.tokenUrl);
342
+ ctx.ui.notify(
343
+ [
344
+ `🔑 OAuth2 for '${storeDomain}' (no guide) — slot ${slot.grant}`,
345
+ ` Token URL: ${slot.tokenUrl}`,
346
+ ...tokenDetailLines(slot.token),
347
+ ...(pending ? [" Pending flow: awaiting --code paste"] : []),
348
+ ].join("\n"),
349
+ "info",
350
+ );
351
+ return;
352
+ }
353
+ // revoke — guide-less, so provider-side revocation isn't possible.
354
+ // The slot's record is stamped (grant + tokenUrl), so these facts
355
+ // round-trip the exact slot key the record was written under.
356
+ deletePendingFlow(storeDomain, slot.grant, slot.tokenUrl);
357
+ deleteToken(storeDomain, slot.grant, slot.tokenUrl);
358
+ ctx.ui.notify(
359
+ `🔑 OAuth2 token slot (${slot.grant}) for '${storeDomain}' cleared locally — no guide, so provider-side revocation was not attempted.`,
360
+ "info",
361
+ );
362
+ return;
363
+ }
364
+ ctx.ui.notify(
365
+ `No API guide for '${domain}'. ` +
366
+ `Call api-guide({}) to list available guides, or api-learn({domain: "${domain}"}) to author one. ` +
367
+ `To bootstrap a token guide-less, run: /api oauth init ${domain}.`,
368
+ "warning",
369
+ );
370
+ return;
371
+ }
372
+ const matches = allMatches.filter(({ guide }) => guide.auth.kind === "oauth2");
373
+ if (matches.length === 0) {
374
+ ctx.ui.notify(
375
+ `No OAuth2 guide for '${domain}' (${allMatches.length} guide(s) found, none with auth.kind: oauth2). ` +
376
+ `Token provisioning needs an oauth2 guide.`,
377
+ "warning",
378
+ );
379
+ return;
380
+ }
381
+
382
+ const selected = await pickGuideForCommand(
383
+ ctx,
384
+ domain,
385
+ selector,
386
+ matches,
387
+ "/api oauth",
388
+ "OAuth2 guides",
389
+ );
390
+ if (!selected) return;
391
+
392
+ const { guide } = selected;
393
+ const auth = guide.auth;
394
+ if (auth.kind !== "oauth2") return; // unreachable — filtered above
395
+ // Token store key is the canonical store domain, decoupled from the
396
+ // routing `domain` (same rule as the secrets store).
397
+ const storeDomain = canonicalStoreDomain(guide);
398
+
399
+ if (revokeFlag) {
400
+ await revokeAccessToken(auth, storeDomain);
401
+ // Slot-scoped: a bare pending delete would leave a stale verifier for a
402
+ // sibling-grant/prior-issuer slot to consume.
403
+ deletePendingFlow(storeDomain, auth.grant, auth.tokenUrl);
404
+ ctx.ui.notify(
405
+ `🔑 OAuth2 token for '${storeDomain}' revoked and cleared.`,
406
+ "info",
407
+ );
408
+ return;
409
+ }
410
+
411
+ if (statusFlag) {
412
+ const token = readToken(storeDomain, auth.grant, auth.tokenUrl);
413
+ if (!token) {
414
+ ctx.ui.notify(
415
+ `🔑 OAuth2 for '${storeDomain}': no token. Run /api oauth ${storeDomain} to mint one.`,
416
+ "info",
417
+ );
418
+ return;
419
+ }
420
+ const lines = [
421
+ `🔑 OAuth2 for '${storeDomain}' (grant ${auth.grant})`,
422
+ ...tokenDetailLines(token),
423
+ ];
424
+ ctx.ui.notify(lines.join("\n"), "info");
425
+ return;
426
+ }
427
+
428
+ // Mint (or refresh) a token. The token store is read fresh inside
429
+ // resolveAccessToken, so a re-mint here is visible to the next api-fetch
430
+ // call. authorization_code guides route through the paste flow (print the
431
+ // authorize URL, user consents in their own browser, pastes the redirect
432
+ // URL back); client_credentials stays pure HTTP.
433
+ if (
434
+ auth.grant !== "authorization_code" &&
435
+ (codeArg !== undefined || redirectUriArg !== undefined)
436
+ ) {
437
+ ctx.ui.notify(authCodeOnlyFlagsNote(storeDomain, auth.grant), "warning");
438
+ return;
439
+ }
440
+ try {
441
+ if (auth.grant === "authorization_code") {
442
+ await mintAuthCodeToken(auth, storeDomain, ctx, {
443
+ ...(codeArg === undefined ? {} : { code: codeArg }),
444
+ ...(refreshFlag ? { refresh: true } : {}),
445
+ ...(redirectUriArg === undefined ? {} : { redirectUri: redirectUriArg }),
446
+ });
447
+ } else {
448
+ // Cached token resolves as-is; the delete is conditional on --refresh
449
+ // (unlike the bootstrap paths, which always want a fresh mint).
450
+ if (refreshFlag) deleteToken(storeDomain, auth.grant, auth.tokenUrl);
451
+ await resolveAccessToken(auth, storeDomain);
452
+ }
453
+ } catch (err) {
454
+ if (err instanceof OAuthTokenMissingError) {
455
+ ctx.ui.notify(`🔑 ${err.message}`, "warning");
456
+ return;
457
+ }
458
+ ctx.ui.notify(
459
+ `⚡ OAuth2 provisioning failed for '${storeDomain}': ` +
460
+ `${err instanceof Error ? err.message : String(err)}`,
461
+ "warning",
462
+ );
463
+ return;
464
+ }
465
+ ctx.ui.notify(
466
+ `🔑 OAuth2 token for '${storeDomain}' ${refreshFlag ? "refreshed" : "provisioned"} (grant ${auth.grant}).`,
467
+ "info",
468
+ );
469
+ }
470
+
471
+ // ═══════════════════════════════════════════════════════════════
472
+ // init — guide-less OAuth2 bootstrap
473
+ // ═══════════════════════════════════════════════════════════════
474
+
475
+ const INIT_USAGE = [
476
+ "Usage: /api oauth init <domain> [flags] — guide-less OAuth2 bootstrap (no oauth2 guide needed).",
477
+ " Flags (headless/scripting; TUI users get a wizard instead):",
478
+ " --grant client_credentials|authorization_code (inferred from --authorize-url when omitted)",
479
+ " --token-url <url> token endpoint",
480
+ " --client-id <store name> provisioned secrets-store NAME (never a literal)",
481
+ " --client-secret <store name> required for client_credentials",
482
+ " --authorize-url <url> required for authorization_code",
483
+ " --scopes a,b comma-separated",
484
+ " --token-endpoint-auth-method client_secret_post|client_secret_basic|none",
485
+ " --redirect-uri <url> override the default redirect URI (default",
486
+ " http://127.0.0.1/callback — match your app registration;",
487
+ " the TUI wizard prompts for this too)",
488
+ " auth-code completion (headless two-call): re-run with the same flags + --code <redirect-url-or-code>.",
489
+ " Client credentials are store names resolved from the secrets store — values never enter the transcript.",
490
+ ].join("\n");
491
+
492
+ /** Flags with values the `init` grammar understands. */
493
+ const INIT_FLAG_NAMES: readonly string[] = [
494
+ "--grant",
495
+ "--token-url",
496
+ "--authorize-url",
497
+ "--client-id",
498
+ "--client-secret",
499
+ "--scopes",
500
+ "--token-endpoint-auth-method",
501
+ "--redirect-uri",
502
+ "--code",
503
+ ];
504
+
505
+ /**
506
+ * Serialize SyntheticOAuth2Fields into the init flag grammar above. Lives
507
+ * next to INIT_FLAG_NAMES so a flag rename here can't silently drift the
508
+ * escape-hatch hint oauth-mint emits.
509
+ */
510
+ export function initFlagsFromFields(fields: SyntheticOAuth2Fields): string[] {
511
+ return [
512
+ `--grant ${fields.grant}`,
513
+ `--token-url ${fields.tokenUrl}`,
514
+ ...(fields.authorizeUrl === undefined
515
+ ? []
516
+ : [`--authorize-url ${fields.authorizeUrl}`]),
517
+ `--client-id ${fields.clientId}`,
518
+ ...(fields.clientSecret === undefined
519
+ ? []
520
+ : [`--client-secret ${fields.clientSecret}`]),
521
+ ...(fields.tokenEndpointAuthMethod === undefined
522
+ ? []
523
+ : [`--token-endpoint-auth-method ${fields.tokenEndpointAuthMethod}`]),
524
+ ];
525
+ }
526
+
527
+ /** Wizard picker option meaning "no client secret" (PKCE public client). */
528
+ const OMIT_SECRET = "(omit — PKCE public client)";
529
+
530
+ /**
531
+ * `/api oauth init <domain>` — provision a token WITHOUT an oauth2 guide.
532
+ * The interactive grant's bootstrap previously required authoring a
533
+ * throwaway draft guide first; the wizard dissolves that asymmetry with
534
+ * client-credentials (which probe mint-on-demand already solved). The wizard collects flow facts (grant, tokenUrl, authorizeUrl,
535
+ * store-NAME credentials) into a synthetic oauth2 auth and feeds the
536
+ * EXISTING flow machinery (`mintAuthCodeToken` / `resolveAccessToken`) —
537
+ * no new mint mechanism, no schema change, nothing saved.
538
+ *
539
+ * Interactive (ctx.hasUI, no flags) → wizard prompts mirroring the
540
+ * `secrets-command` assisted-entry precedent. Headless or scripted → the
541
+ * flag one-shot acts directly (the same split the paste flow already uses).
542
+ * Token-store keying applies the probe's parent-domain normalization
543
+ * (longest provisioned parent in the SECRETS store); a normalized stamp is
544
+ * called out so it doesn't go invisible to the eventual guide.
545
+ */
546
+ /** Shared refusal prose for auth-code-only flags on a pure-HTTP mint arm
547
+ * (plain command + init wizard — one message, one place). */
548
+ function authCodeOnlyFlagsNote(storeDomain: string, grant: string): string {
549
+ return (
550
+ "--code and --redirect-uri apply only to the authorization_code grant — " +
551
+ `'${storeDomain}' mints via ${grant} (pure HTTP, nothing to paste).`
552
+ );
553
+ }
554
+
555
+ async function handleOauthInit(
556
+ args: string,
557
+ ctx: ExtensionCommandContext,
558
+ ): Promise<void> {
559
+ const parts = args.trim().split(/\s+/).filter(Boolean);
560
+
561
+ // Parse the flag grammar (shared with the plain command): each known flag
562
+ // consumes one value; anything else is a positional (exactly one — the
563
+ // domain).
564
+ const parsed = parseFlags(parts, INIT_FLAG_NAMES, []);
565
+ if (!parsed.ok) {
566
+ ctx.ui.notify(parsed.message, "warning");
567
+ return;
568
+ }
569
+ const flags = parsed.flags;
570
+ const domain = parsed.positional[0];
571
+ if (domain === undefined || parsed.positional.length > 1) {
572
+ ctx.ui.notify(INIT_USAGE, "info");
573
+ return;
574
+ }
575
+ const codeArg = flags["--code"];
576
+
577
+ // Token-store key wrinkle: normalize against the SECRETS store (same
578
+ // longest-provisioned-parent lookup the probe uses) so a bootstrap as
579
+ // `api.example.org` lands where a guide keyed `example.org` looks.
580
+ // No provisioned match → use the domain as given (fail at exchange,
581
+ // not silently).
582
+ const storeDomain = resolveProvisionedParentDomain(domain);
583
+ const viaFlags = Object.keys(flags).length > 0;
584
+
585
+ let fields: SyntheticOAuth2Fields;
586
+ let wizardRedirectUri: string | undefined;
587
+ if (viaFlags) {
588
+ const scopesRaw = flags["--scopes"];
589
+ const grant =
590
+ flags["--grant"] ??
591
+ (flags["--authorize-url"] === undefined
592
+ ? "client_credentials"
593
+ : "authorization_code");
594
+ const methodFlag = flags["--token-endpoint-auth-method"];
595
+ fields = {
596
+ grant: grant as SyntheticOAuth2Fields["grant"],
597
+ tokenUrl: flags["--token-url"] ?? "",
598
+ clientId: flags["--client-id"] ?? "",
599
+ ...(flags["--client-secret"] === undefined
600
+ ? {}
601
+ : { clientSecret: flags["--client-secret"] }),
602
+ ...(flags["--authorize-url"] === undefined
603
+ ? {}
604
+ : { authorizeUrl: flags["--authorize-url"] }),
605
+ ...(scopesRaw === undefined
606
+ ? {}
607
+ : {
608
+ scopes: scopesRaw
609
+ .split(",")
610
+ .map((s) => s.trim())
611
+ .filter(Boolean),
612
+ }),
613
+ ...(methodFlag === undefined
614
+ ? {}
615
+ : {
616
+ tokenEndpointAuthMethod: methodFlag as NonNullable<
617
+ SyntheticOAuth2Fields["tokenEndpointAuthMethod"]
618
+ >,
619
+ }),
620
+ };
621
+ } else if (ctx.hasUI) {
622
+ const gathered = await wizardFields(ctx, storeDomain);
623
+ if (gathered === undefined) return; // cancelled / aborted (message shown)
624
+ fields = gathered.fields;
625
+ wizardRedirectUri = gathered.redirectUri;
626
+ } else {
627
+ ctx.ui.notify(INIT_USAGE, "info");
628
+ return;
629
+ }
630
+
631
+ let synthetic;
632
+ try {
633
+ synthetic = buildSyntheticOAuth2Auth(fields);
634
+ } catch (err) {
635
+ ctx.ui.notify(
636
+ `⚡ ${err instanceof Error ? err.message : String(err)}\n\n${INIT_USAGE}`,
637
+ "warning",
638
+ );
639
+ return;
640
+ }
641
+
642
+ // Store-name rule (hard): every credential is a provisioned store NAME,
643
+ // resolved at flow time. A miss points at /api secrets — never a value
644
+ // prompt, never a free-typed literal.
645
+ const gap = credentialNameGap(
646
+ storeDomain,
647
+ fields.clientId,
648
+ fields.clientSecret,
649
+ );
650
+ if (gap !== null) {
651
+ ctx.ui.notify(gap, "warning");
652
+ return;
653
+ }
654
+
655
+ const provisionedMsg = () => {
656
+ const lines = [
657
+ `🔑 OAuth2 token for '${storeDomain}' provisioned via /api oauth init (grant ${synthetic.grant}).`,
658
+ ];
659
+ if (storeDomain !== domain) {
660
+ // Ordering dependency worth flagging to the user: normalization matched the
661
+ // SECRETS store, but the eventual guide keys on its domains[0].
662
+ lines.push(
663
+ `Note: provision secrets under the same domain the guide will claim as domains[0] — the token was stamped at '${storeDomain}' (normalized from '${domain}').`,
664
+ );
665
+ }
666
+ ctx.ui.notify(lines.join("\n"), "info");
667
+ };
668
+
669
+ // auth-code-only flags: --code / --redirect-uri do nothing on a
670
+ // client_credentials mint — refuse loudly instead of reporting success
671
+ // while the flag did nothing.
672
+ if (
673
+ synthetic.grant !== "authorization_code" &&
674
+ (codeArg !== undefined || flags["--redirect-uri"] !== undefined)
675
+ ) {
676
+ ctx.ui.notify(authCodeOnlyFlagsNote(storeDomain, synthetic.grant), "warning");
677
+ return;
678
+ }
679
+
680
+ try {
681
+ if (codeArg !== undefined) {
682
+ // Headless two-call completion: reconstruct the synthetic auth from
683
+ // the same flags used to start; the pending flow holds verifier+state.
684
+ await mintAuthCodeToken(synthetic, storeDomain, ctx, { code: codeArg });
685
+ provisionedMsg();
686
+ return;
687
+ }
688
+ if (synthetic.grant === "client_credentials") {
689
+ // Bootstrap wants a fresh mint, not a cached token (mirrors the
690
+ // plain command's --refresh path).
691
+ const overwrite = slotOverwriteWarning(synthetic, storeDomain);
692
+ if (overwrite) ctx.ui.notify(overwrite, "warning");
693
+ await mintFreshClientCredentials(synthetic, storeDomain);
694
+ provisionedMsg();
695
+ return;
696
+ }
697
+ // authorization_code start: prints the authorize URL and persists the
698
+ // pending flow (including the redirect URI, so the --code completion
699
+ // exchanges with the same value); interactive users complete inline,
700
+ // headless awaits `init ... --code`.
701
+ const mintRedirectUri = flags["--redirect-uri"] ?? wizardRedirectUri;
702
+ try {
703
+ await mintAuthCodeToken(
704
+ synthetic,
705
+ storeDomain,
706
+ ctx,
707
+ mintRedirectUri === undefined ? {} : { redirectUri: mintRedirectUri },
708
+ );
709
+ provisionedMsg();
710
+ } catch (err) {
711
+ if (!(err instanceof OAuthTokenMissingError)) throw err;
712
+ if (viaFlags) {
713
+ // Headless start: the pending flow survived — teach the init-owned
714
+ // completion call (reconstructs the synthetic auth from flags).
715
+ ctx.ui.notify(
716
+ `🔑 Awaiting the OAuth2 authorization result for '${storeDomain}'. ` +
717
+ `Open the URL above, authorize, then complete:\n` +
718
+ ` /api oauth init ${args.trim()} --code <redirect-url-or-code>`,
719
+ "info",
720
+ );
721
+ } else {
722
+ // Wizard user cancelled the paste prompt — flags-based completion
723
+ // isn't available to them; a re-run generates a fresh URL.
724
+ ctx.ui.notify(
725
+ `🔑 Cancelled. Re-run /api oauth init ${domain} to generate a fresh authorize URL (or complete with flags + --code).`,
726
+ "info",
727
+ );
728
+ }
729
+ }
730
+ } catch (err) {
731
+ if (err instanceof OAuthTokenMissingError) {
732
+ ctx.ui.notify(`🔑 ${err.message}`, "warning");
733
+ return;
734
+ }
735
+ ctx.ui.notify(
736
+ `⚡ OAuth2 bootstrap failed for '${storeDomain}': ` +
737
+ `${err instanceof Error ? err.message : String(err)}`,
738
+ "warning",
739
+ );
740
+ }
741
+ }
742
+
743
+ /**
744
+ * Interactive wizard — the wizard branch tree is deliberately short: grant → tokenUrl → client credentials as
745
+ * store NAMES from a picker → auth-code extras. DPoP, PAR, device flow, JWT
746
+ * assertions etc. must NOT grow wizard branches — this is a provisioning aid,
747
+ * not an OAuth playground. Returns undefined when the user cancels/aborts.
748
+ */
749
+ const GRANT_ITEMS: SelectItem[] = [
750
+ {
751
+ value: "client_credentials",
752
+ label: "client_credentials",
753
+ description: "Server-to-server — no browser; one POST to the token endpoint.",
754
+ },
755
+ {
756
+ value: "authorization_code",
757
+ label: "authorization_code",
758
+ description:
759
+ "Consent in your own browser (PKCE), then paste the redirect URL back.",
760
+ },
761
+ ];
762
+
763
+ const AUTH_METHOD_ITEMS: SelectItem[] = [
764
+ {
765
+ value: "client_secret_post",
766
+ label: "client_secret_post",
767
+ description: "Credentials in the token-POST body.",
768
+ },
769
+ {
770
+ value: "client_secret_basic",
771
+ label: "client_secret_basic",
772
+ description: "Credentials in a Basic Authorization header.",
773
+ },
774
+ ];
775
+
776
+ async function wizardFields(
777
+ ctx: ExtensionCommandContext,
778
+ storeDomain: string,
779
+ ): Promise<
780
+ { fields: SyntheticOAuth2Fields; redirectUri?: string } | undefined
781
+ > {
782
+ const cancelled = () =>
783
+ ctx.ui.notify("Cancelled — nothing provisioned.", "info");
784
+
785
+ const grant = await pickWithDescription(
786
+ ctx,
787
+ `OAuth2 grant for '${storeDomain}'`,
788
+ GRANT_ITEMS,
789
+ );
790
+ if (grant === undefined) {
791
+ await cancelled();
792
+ return undefined;
793
+ }
794
+ let redirectUri: string | undefined;
795
+ if (grant === "authorization_code") {
796
+ // Ask first: the redirect URI is a fact of the user's app registration,
797
+ // not the provider's API — if it isn't registered at the provider,
798
+ // nothing later in the wizard matters, so fail fast (empty keeps the
799
+ // RFC 8252 convention). The pending flow carries it through to the
800
+ // --code exchange (RFC 6749 §4.1.3).
801
+ const raw = (
802
+ await ctx.ui.input(
803
+ `Redirect URI — make sure your provider app has this registered (empty for the default ${REDIRECT_URI})`,
804
+ REDIRECT_URI,
805
+ )
806
+ )?.trim();
807
+ if (raw === undefined) {
808
+ await cancelled();
809
+ return undefined;
810
+ }
811
+ if (raw !== "") redirectUri = raw;
812
+ }
813
+ const tokenUrl = (
814
+ await ctx.ui.input(
815
+ `Token endpoint URL for '${storeDomain}'`,
816
+ "https://provider.example.com/oauth/token",
817
+ )
818
+ )?.trim();
819
+ if (!tokenUrl) {
820
+ await cancelled();
821
+ return undefined;
822
+ }
823
+ // Store-name rule: client-id/secret are picked from provisioned secrets —
824
+ // never values, never free-typed literals (the /api secrets audit rule).
825
+ const names = listNames(storeDomain);
826
+ if (names.length === 0) {
827
+ ctx.ui.notify(
828
+ `No provisioned secrets for '${storeDomain}' — client credentials are store NAMES, never free-typed literals. ` +
829
+ `Provision them first: /api secrets ${storeDomain} <name>.`,
830
+ "warning",
831
+ );
832
+ return undefined;
833
+ }
834
+ const clientId = await ctx.ui.select(
835
+ `client-id STORE NAME for '${storeDomain}' (value resolves from the store)`,
836
+ names,
837
+ );
838
+ if (clientId === undefined) {
839
+ await cancelled();
840
+ return undefined;
841
+ }
842
+ const clientSecret = await ctx.ui.select(
843
+ `client-secret STORE NAME for '${storeDomain}'`,
844
+ grant === "client_credentials" ? names : [OMIT_SECRET, ...names],
845
+ );
846
+ if (clientSecret === undefined) {
847
+ await cancelled();
848
+ return undefined;
849
+ }
850
+ // A public PKCE client (secret omitted) sends no client credentials —
851
+ // method is forced to none. Otherwise the user picks where the secret
852
+ // goes (plenty of providers default to Basic; the runtime default is
853
+ // post). cc always has a secret, so this covers both arms.
854
+ const tokenEndpointAuthMethod: OAuth2TokenEndpointAuthMethod | undefined =
855
+ clientSecret === OMIT_SECRET
856
+ ? "none"
857
+ : ((await pickWithDescription(
858
+ ctx,
859
+ "Token-endpoint auth method",
860
+ AUTH_METHOD_ITEMS,
861
+ )) as OAuth2TokenEndpointAuthMethod | undefined);
862
+ if (tokenEndpointAuthMethod === undefined) {
863
+ await cancelled();
864
+ return undefined;
865
+ }
866
+ if (grant === "client_credentials") {
867
+ return {
868
+ fields: {
869
+ grant: "client_credentials",
870
+ tokenUrl,
871
+ clientId,
872
+ clientSecret: clientSecret!,
873
+ tokenEndpointAuthMethod,
874
+ },
875
+ };
876
+ }
877
+ const authorizeUrl = (
878
+ await ctx.ui.input(
879
+ `Authorization endpoint URL for '${storeDomain}'`,
880
+ "https://provider.example.com/oauth/authorize",
881
+ )
882
+ )?.trim();
883
+ if (!authorizeUrl) {
884
+ await cancelled();
885
+ return undefined;
886
+ }
887
+ const scopesRaw = await ctx.ui.input(
888
+ "Scopes (comma-separated)",
889
+ "e.g. read,profile — empty to skip",
890
+ );
891
+ if (scopesRaw === undefined) {
892
+ await cancelled();
893
+ return undefined;
894
+ }
895
+ const scopes = scopesRaw
896
+ .split(",")
897
+ .map((s) => s.trim())
898
+ .filter(Boolean);
899
+ return {
900
+ fields: {
901
+ grant: grant as SyntheticOAuth2Fields["grant"],
902
+ tokenUrl,
903
+ clientId,
904
+ ...(clientSecret === OMIT_SECRET ? {} : { clientSecret: clientSecret! }),
905
+ authorizeUrl,
906
+ ...(scopes.length > 0 ? { scopes } : {}),
907
+ tokenEndpointAuthMethod,
908
+ },
909
+ ...(redirectUri === undefined ? {} : { redirectUri }),
910
+ };
911
+ }