pi-lean-host 0.4.0 → 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,376 @@
1
+ /**
2
+ * OAuth2 authorization-code + PKCE flow — headless paste-based, host-only.
3
+ *
4
+ * The user consents in THEIR OWN browser at the provider, logging in with
5
+ * their own credentials. Routing that through portal's driven browser would
6
+ * flow the user's provider password through agent context — a hard no. So
7
+ * this module: generates the PKCE pair, builds the authorize URL
8
+ * (`redirect_uri = http://127.0.0.1/callback`, the RFC 8252 §7.3 loopback
9
+ * convention — nothing listens there, by design), persists the pending flow,
10
+ * and surfaces the URL. The user pastes back the address-bar redirect URL
11
+ * (or bare code); pi validates `state`, exchanges the code, and stamps the
12
+ * token store. No listener, no inbound network surface — the flow works
13
+ * unchanged whether pi runs on the user's machine, in a container, or inside
14
+ * a VM. No static portal import — the host-only boundary holds.
15
+ *
16
+ * Import direction: oauth-flow → auth (exchange/refresh) → oauth-store; the
17
+ * store imports nothing from here, so no cycle can form.
18
+ */
19
+
20
+ import { createHash, randomBytes } from "node:crypto";
21
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
22
+ import { getCapabilities, hyperlink } from "@earendil-works/pi-tui";
23
+ import type { OAuth2Auth } from "./api-guide-types.js";
24
+ import {
25
+ exchangeAuthCode,
26
+ forceRefreshToken,
27
+ resolveClientCredentials,
28
+ slotOverwriteWarning,
29
+ OAuthTokenMissingError,
30
+ } from "./auth.js";
31
+ import {
32
+ readPendingFlow,
33
+ writePendingFlow,
34
+ deletePendingFlow,
35
+ writeToken,
36
+ } from "./oauth-store.js";
37
+ import type { OAuthToken } from "./oauth-store.js";
38
+
39
+ /**
40
+ * The redirect-URI convention for every auth-code guide (RFC 8252 §7.3 —
41
+ * loopback, variable port). The IP literal 127.0.0.1 is used rather than
42
+ * `localhost`: RFC 8252 §7.3 recommends it, and some providers (OSM) accept
43
+ * only `http://127.0.0.1*` as a non-https redirect. The redirect URI is a
44
+ * fact of the USER's app
45
+ * registration, not the provider's API, so the schema carries no field;
46
+ * the runtime owns the redirect end-to-end through this one convention.
47
+ * Nothing listens on the port — the user copies the address-bar URL.
48
+ */
49
+ export const REDIRECT_URI = "http://127.0.0.1/callback";
50
+
51
+ function base64url(buf: Buffer): string {
52
+ return buf.toString("base64url");
53
+ }
54
+
55
+ /** PKCE S256 pair: a random verifier + its base64url(SHA-256) challenge. */
56
+ export function generatePkcePair(): { verifier: string; challenge: string } {
57
+ const verifier = base64url(randomBytes(32));
58
+ const challenge = base64url(createHash("sha256").update(verifier).digest());
59
+ return { verifier, challenge };
60
+ }
61
+
62
+ /** Random `state` value for the authorize URL + paste check. */
63
+ export function generateState(): string {
64
+ return base64url(randomBytes(16));
65
+ }
66
+
67
+ /**
68
+ * Build the provider's authorize URL (response_type=code + PKCE + state).
69
+ * `redirectUri` is the URI sent as `redirect_uri` — the paste flow always
70
+ * passes the `REDIRECT_URI` convention; it is a parameter so tests can pin
71
+ * the wiring.
72
+ */
73
+ export function buildAuthorizeUrl(
74
+ auth: OAuth2Auth,
75
+ redirectUri: string,
76
+ challenge: string,
77
+ state: string,
78
+ /** The client id VALUE — resolved from the secrets store by the caller
79
+ * (`clientId` is a store name, not a literal). */
80
+ clientIdValue: string,
81
+ ): string {
82
+ const base = auth.authorizeUrl;
83
+ if (!base) {
84
+ throw new Error("oauth2 authorization_code guide is missing authorizeUrl");
85
+ }
86
+ let url: URL;
87
+ try {
88
+ url = new URL(base);
89
+ } catch {
90
+ throw new Error(`oauth2 authorizeUrl is not a valid URL: ${base}`);
91
+ }
92
+ url.searchParams.set("response_type", "code");
93
+ url.searchParams.set("client_id", clientIdValue);
94
+ url.searchParams.set("redirect_uri", redirectUri);
95
+ if (auth.scopes && auth.scopes.length > 0) {
96
+ url.searchParams.set("scope", auth.scopes.join(" "));
97
+ }
98
+ url.searchParams.set("state", state);
99
+ url.searchParams.set("code_challenge", challenge);
100
+ url.searchParams.set("code_challenge_method", "S256");
101
+ return url.toString();
102
+ }
103
+
104
+ /** A successfully parsed paste: the code plus the state (if the URL had one). */
105
+ export interface PastedAuthResult {
106
+ code: string;
107
+ state?: string;
108
+ }
109
+
110
+ /**
111
+ * Parse the user's pasted authorization result. Tolerant by design — accepts
112
+ * the full redirect URL from the browser's address bar (documented default),
113
+ * a host-less `127.0.0.1/callback?code=…&state=…`, a bare `code=…&state=…`
114
+ * query, or just the bare code (which skips the state check — pi never sees
115
+ * it). A provider rejection (`?error=…`) surfaces the provider's actual
116
+ * reason instead of a generic "exchange failed".
117
+ */
118
+ export function parsePastedRedirect(input: string): PastedAuthResult {
119
+ const trimmed = input.trim();
120
+ if (!trimmed) {
121
+ throw new Error("Pasted OAuth2 authorization result is empty.");
122
+ }
123
+ // Only treat as query-ish when it actually carries an OAuth param —
124
+ // a bare base64-padded code contains `=` but is not a query.
125
+ if (/(^|[?&])(code|error|state)=/.test(trimmed)) {
126
+ // Query-ish: after a "?" if present, else the whole string.
127
+ const qs = trimmed.includes("?")
128
+ ? trimmed.slice(trimmed.indexOf("?") + 1)
129
+ : trimmed;
130
+ const params = new URLSearchParams(qs);
131
+ const error = params.get("error");
132
+ if (error) {
133
+ const desc = params.get("error_description");
134
+ throw new Error(
135
+ `OAuth2 authorization error: ${error}${desc ? ` — ${desc}` : ""}`,
136
+ );
137
+ }
138
+ const code = params.get("code");
139
+ if (!code) {
140
+ throw new Error(
141
+ "Pasted value carries no `code` parameter — paste the full redirect URL from the browser's address bar (or just the code).",
142
+ );
143
+ }
144
+ const state = params.get("state");
145
+ return state ? { code, state } : { code };
146
+ }
147
+ return { code: trimmed };
148
+ }
149
+
150
+ /** Validate a paste against the pending flow's state and return the code. */
151
+ function validatePasted(pasted: string, state: string): string {
152
+ const parsed = parsePastedRedirect(pasted);
153
+ if (parsed.state !== undefined && parsed.state !== state) {
154
+ throw new Error(
155
+ "OAuth2 state mismatch — the pasted URL doesn't match the authorize URL pi generated. " +
156
+ "Re-run /api oauth <domain> and paste the fresh result.",
157
+ );
158
+ }
159
+ return parsed.code;
160
+ }
161
+
162
+ /** Exchange the code and stamp the token store (slot-keyed by the auth). */
163
+ async function exchangeAndStamp(
164
+ auth: OAuth2Auth,
165
+ storeDomain: string,
166
+ code: string,
167
+ verifier: string,
168
+ redirectUri: string,
169
+ ): Promise<OAuthToken> {
170
+ const token = await exchangeAuthCode(
171
+ auth,
172
+ storeDomain,
173
+ code,
174
+ redirectUri,
175
+ verifier,
176
+ );
177
+ writeToken(storeDomain, auth.grant, auth.tokenUrl, token);
178
+ return token;
179
+ }
180
+
181
+ /** Options for `mintAuthCodeToken`. */
182
+ export interface AuthCodeMintOptions {
183
+ /** Pasted redirect URL (or bare code) — the `--code` escape valve. */
184
+ code?: string;
185
+ /** Force a refresh via the stored refresh token (no re-consent). */
186
+ refresh?: boolean;
187
+ /** Override of the default redirect URI — sent as `redirect_uri` in the
188
+ * authorize request AND stored on the pending flow so the `--code`
189
+ * completion exchanges with the same value (RFC 6749 §4.1.3). */
190
+ redirectUri?: string;
191
+ }
192
+
193
+ /**
194
+ * The human trust-gate for the secret-bearing token endpoint — the one
195
+ * message every mint-on-demand path must confirm before exchanging
196
+ * credentials there (the human is the trust root for agent-researched
197
+ * token URLs). Shared by oauth-mint and api-probe's inline mint.
198
+ */
199
+ export async function confirmTokenUrl(
200
+ ctx: ExtensionContext,
201
+ domain: string,
202
+ tokenUrl: string,
203
+ clientId: string,
204
+ ): Promise<boolean> {
205
+ return ctx.ui.confirm(
206
+ `Confirm the token endpoint for '${domain}'`,
207
+ `Exchange credentials at ${tokenUrl} (client: '${clientId}')? The client secret is sent to this URL.`,
208
+ );
209
+ }
210
+
211
+ /**
212
+ * Mint (or refresh) a token for an authorization_code guide. Order:
213
+ * 1. `--code` → parse the pasted redirect URL / code and complete the
214
+ * pending flow (headless scripting; interactive users get an inline
215
+ * prompt instead).
216
+ * 2. `--refresh` → force a refresh via the stored refresh token; falls back
217
+ * to a fresh authorize flow when there is no refresh token.
218
+ * 3. Otherwise → print the authorize URL, persist the pending flow, and
219
+ * either prompt for the paste (`ctx.hasUI`) or throw
220
+ * `OAuthTokenMissingError` (headless — awaiting `--code`).
221
+ */
222
+ export async function mintAuthCodeToken(
223
+ auth: OAuth2Auth,
224
+ storeDomain: string,
225
+ // ExtensionContext (not the command subtype): tools drive the flow too
226
+ // (oauth-mint). Only ui.notify/ui.input/hasUI are used.
227
+ ctx: ExtensionContext,
228
+ opts: AuthCodeMintOptions = {},
229
+ ): Promise<OAuthToken> {
230
+ // The `--code` and start branches both end in a fresh stamp that clobbers
231
+ // the slot; `--refresh` is exempt (same-slot refresh, never a scope
232
+ // change — and its fresh-flow fallback warns below).
233
+ const warnOverwrite = (): void => {
234
+ const warning = slotOverwriteWarning(auth, storeDomain);
235
+ if (warning) ctx.ui.notify(warning, "warning");
236
+ };
237
+ if (opts.code !== undefined) {
238
+ warnOverwrite();
239
+ return completePastedCode(auth, storeDomain, opts.code);
240
+ }
241
+ if (opts.refresh) {
242
+ try {
243
+ return await forceRefreshToken(auth, storeDomain);
244
+ } catch (err) {
245
+ if (!(err instanceof OAuthTokenMissingError)) throw err;
246
+ // no refresh token → fall through to a fresh authorize flow
247
+ }
248
+ }
249
+ warnOverwrite();
250
+ return startAuthCodeFlow(auth, storeDomain, ctx, opts.redirectUri);
251
+ }
252
+
253
+ /**
254
+ * The authorize URL as the user should see it. With OSC 8 support the visible
255
+ * text is just origin + path (always fits one line — no wrapping, so no
256
+ * space-inserted copies and no link split across lines); the hyperlink
257
+ * target carries the FULL URL, so click / copy-link always gets the intact
258
+ * authorize URL including the query string. Without OSC 8 the visible text
259
+ * is all the user gets, so print the full URL — plus a wrap warning, since
260
+ * the long query string will wrap and terminal copy inserts spaces at the
261
+ * breaks.
262
+ */
263
+ function printableAuthorizeUrl(url: string): string {
264
+ if (getCapabilities().hyperlinks) {
265
+ try {
266
+ const u = new URL(url);
267
+ return hyperlink(`\x1b[1m${u.origin}${u.pathname}\x1b[22m`, url);
268
+ } catch {
269
+ // unreachable — buildAuthorizeUrl already validated the URL
270
+ }
271
+ }
272
+ return (
273
+ `\x1b[1m${url}\x1b[22m` +
274
+ `\n(if the URL wraps across lines, remove the extra spaces at each line break after copying)`
275
+ );
276
+ }
277
+
278
+ /**
279
+ * The primary — and only — authorize path. Generates the PKCE pair + state,
280
+ * builds the authorize URL with the redirect URI (default: the
281
+ * `http://127.0.0.1/callback` convention, overridable per invocation),
282
+ * persists the pending flow (the verifier MUST survive so the later exchange
283
+ * matches the challenge sent in the authorize URL), prints the URL, and
284
+ * either prompts for the paste (TUI) or throws awaiting `--code` (headless).
285
+ */
286
+ async function startAuthCodeFlow(
287
+ auth: OAuth2Auth,
288
+ storeDomain: string,
289
+ ctx: ExtensionContext,
290
+ redirectUri: string = REDIRECT_URI,
291
+ ): Promise<OAuthToken> {
292
+ const { verifier, challenge } = generatePkcePair();
293
+ const state = generateState();
294
+ const authorizeUrl = buildAuthorizeUrl(
295
+ auth,
296
+ redirectUri,
297
+ challenge,
298
+ state,
299
+ resolveClientCredentials(auth, storeDomain).clientId,
300
+ );
301
+ writePendingFlow(storeDomain, auth.grant, auth.tokenUrl, {
302
+ verifier,
303
+ state,
304
+ redirectUri,
305
+ });
306
+ ctx.ui.notify(
307
+ `🔑 Open this URL in YOUR browser and authorize (log in with your own credentials — the agent never sees them). ` +
308
+ `Your OAuth app needs '${redirectUri}' registered as its redirect URI (default: RFC 8252 §7.3 — loopback, any port). ` +
309
+ `After consenting, copy the redirect URL from the browser's address bar.\n\n` +
310
+ printableAuthorizeUrl(authorizeUrl),
311
+ "info",
312
+ );
313
+ if (ctx.hasUI) {
314
+ // The paste dialog is what's on screen while the user acts — repeat the
315
+ // URL + instructions in its title (accent-colored, multi-line, ANSI-aware
316
+ // wrap) so they never have to hunt for it in the scrollback above.
317
+ // Retry loop: a bad paste (typo, state mismatch, exchange hiccup) just
318
+ // re-prompts — the pending flow (verifier + state) is unchanged, so a
319
+ // retry is always safe. Escape/cancel exits to the --code nudge below.
320
+ for (;;) {
321
+ const pasted = await ctx.ui.input(
322
+ `Open this URL in YOUR browser and authorize, then paste the redirect URL (or just the code) for '${storeDomain}':\n` +
323
+ printableAuthorizeUrl(authorizeUrl),
324
+ "paste the address-bar URL after consenting",
325
+ );
326
+ // Cancelled → fall through to the --code nudge (pending flow survives).
327
+ if (pasted === undefined) break;
328
+ try {
329
+ return await completePastedCode(auth, storeDomain, pasted);
330
+ } catch (err) {
331
+ ctx.ui.notify(
332
+ `🔑 ${err instanceof Error ? err.message : String(err)} — paste again, or escape to cancel.`,
333
+ "warning",
334
+ );
335
+ }
336
+ }
337
+ }
338
+ throw new OAuthTokenMissingError(
339
+ `Awaiting the OAuth2 authorization result for '${storeDomain}'. ` +
340
+ `Open the URL above, authorize, then paste the redirect URL: /api oauth ${storeDomain} --code <redirect-url-or-code>.`,
341
+ );
342
+ }
343
+
344
+ /** `--code` (or interactive-prompt) completion: parse, validate state, exchange.
345
+ * The pending flow is read/written under the slot derived from the synthetic
346
+ * (or guide-backed) auth, so two auth-code issuers on one domain can't
347
+ * consume each other's verifier. */
348
+ async function completePastedCode(
349
+ auth: OAuth2Auth,
350
+ storeDomain: string,
351
+ pasted: string,
352
+ ): Promise<OAuthToken> {
353
+ const pending = readPendingFlow(storeDomain, auth.grant, auth.tokenUrl);
354
+ if (!pending) {
355
+ throw new OAuthTokenMissingError(
356
+ `No pending OAuth2 authorization flow for '${storeDomain}'. ` +
357
+ `Run /api oauth ${storeDomain} (or /api oauth init ${storeDomain} guide-less) ` +
358
+ `first to get the authorize URL.`,
359
+ );
360
+ }
361
+ const code = validatePasted(pasted, pending.state);
362
+ // The exchange's redirect_uri must match the authorize request's exactly
363
+ // (RFC 6749 §4.1.3) — read it back from the pending flow, which remembers
364
+ // what was sent. Records missing the field are rejected at read time, so
365
+ // a pre-field pending entry just reads as "no pending flow" (re-run the
366
+ // authorize step — tokens/pending are re-mintable, no migration).
367
+ const token = await exchangeAndStamp(
368
+ auth,
369
+ storeDomain,
370
+ code,
371
+ pending.verifier,
372
+ pending.redirectUri,
373
+ );
374
+ deletePendingFlow(storeDomain, auth.grant, auth.tokenUrl);
375
+ return token;
376
+ }
@@ -0,0 +1,306 @@
1
+ /**
2
+ * OAuth2 token store — per-domain, per-slot token persistence.
3
+ *
4
+ * File backend: `~/.pi/agent/pi-lean-host/oauth/<domain>.json`, one file per
5
+ * domain holding `Record<slot, StampedToken>` — the secrets-store's per-domain
6
+ * name-keyed shape, not a filename-as-database layout. The slot key derives
7
+ * from `(grant, tokenUrl)` via `slotKey`: the same domain can
8
+ * hold an app token and a user token (and tokens from two issuers) without
9
+ * clobbering, while multi-recipe domains sharing one grant + issuer keep
10
+ * sharing a slot. `slotKey` takes the two facts structurally — the store
11
+ * layer stays free of `auth.ts` types.
12
+ *
13
+ * SEPARATE from the secrets store because tokens rotate and have structure
14
+ * (`expiresAt`, `refreshToken`) — raw secrets don't. Two 0600 file stores
15
+ * with the same interface shape is simpler than one overloaded file.
16
+ * `client_secret` stays in the secrets store (a raw credential provisioned
17
+ * once); only minted tokens live here.
18
+ *
19
+ * Security posture mirrors secrets-store.ts: 0600 files, lazy-mkdir on write
20
+ * only, names-only listing. The store is swappable (the `TokenStore`
21
+ * interface + `createTokenStore`) so a deferred OS-keychain backend is a
22
+ * drop-in without touching callers.
23
+ *
24
+ * Kept free of any `auth.ts` import — the edge is one-way (auth.ts → here),
25
+ * so no import cycle can form.
26
+ */
27
+
28
+ import { join } from "node:path";
29
+ import { homedir } from "node:os";
30
+ import { createHash } from "node:crypto";
31
+ import { existsSync, readdirSync, rmSync } from "node:fs";
32
+ import { assertSafeDomain } from "./path-template.js";
33
+ import { readJsonObject, writeJson0600 } from "./fs-0600.js";
34
+
35
+ /** A minted token set for one (domain, grant, tokenUrl) slot. */
36
+ export interface OAuthToken {
37
+ accessToken: string;
38
+ refreshToken?: string;
39
+ /** Epoch ms when the access token expires. Absent → treat as never-expiring. */
40
+ expiresAt?: number;
41
+ scope?: string;
42
+ }
43
+
44
+ /** A stored token with its mint facts. The store layer requires the stamp:
45
+ * every entry must be self-describing, so slot enumeration can render real
46
+ * grant/issuer and the orphan arms can round-trip a slot's key from its
47
+ * record (unstamped/legacy records fail validation → ignored, re-minted). */
48
+ type StampedToken = OAuthToken & { grant: string; tokenUrl: string };
49
+
50
+ /**
51
+ * The token-slot key: `<grant>__<hash(tokenUrl)>`. Two tokens share a slot
52
+ * iff they share store domain + grant + token URL — same domain + same grant
53
+ * + same issuer → same slot (multi-recipe domains keep sharing); any
54
+ * difference → a different slot key in the same file. Hash the FULL URL
55
+ * (never just the path): two issuers behind one API domain can differ by
56
+ * host only (tenant-a vs tenant-b auth0). ≥16 hex chars of SHA-256 so
57
+ * tenant-farm issuers don't collide. TokenUrl *spelling* differences
58
+ * fragment slots rather than clobber — harmless, just expected.
59
+ */
60
+ export function slotKey(grant: string, tokenUrl: string): string {
61
+ const hash = createHash("sha256").update(tokenUrl).digest("hex").slice(0, 16);
62
+ return `${grant}__${hash}`;
63
+ }
64
+
65
+ /** One slot's stored token, with the facts status rows render. */
66
+ export interface TokenSlotInfo {
67
+ slot: string;
68
+ grant: string;
69
+ tokenUrl: string;
70
+ token: OAuthToken;
71
+ }
72
+
73
+ /** Read a slot map file: whole-file object read + per-entry validation
74
+ * (entries failing `isEntry` are dropped). Shared by the token file and
75
+ * the pending-flow scratch file — one loop over readJsonObject's result. */
76
+ function readSlotMap<T>(
77
+ p: string,
78
+ isEntry: (value: Record<string, unknown>) => boolean,
79
+ ): Record<string, T> {
80
+ const map: Record<string, T> = {};
81
+ for (const [key, value] of Object.entries(readJsonObject(p))) {
82
+ if (
83
+ value &&
84
+ typeof value === "object" &&
85
+ !Array.isArray(value) &&
86
+ isEntry(value as Record<string, unknown>)
87
+ ) {
88
+ map[key] = value as T;
89
+ }
90
+ }
91
+ return map;
92
+ }
93
+
94
+ /**
95
+ * A token store: read/write/delete one (domain, slot) token; enumerate a
96
+ * domain's slots and the store's domains. One `<domain>.json` per domain
97
+ * holding `Record<slot, StampedToken>` — slot enumeration is `Object.keys`
98
+ * of the file (the secrets store's `listNames` pattern), never filename
99
+ * parsing. Writes require the stamp: every entry must carry the grant +
100
+ * tokenUrl it was minted under, so records are self-describing.
101
+ */
102
+ export interface TokenStore {
103
+ read(domain: string, slot: string): StampedToken | null;
104
+ write(domain: string, slot: string, token: StampedToken): void;
105
+ delete(domain: string, slot: string): void;
106
+ listSlots(domain: string): TokenSlotInfo[];
107
+ listDomains(): string[];
108
+ }
109
+
110
+ /** File-backed store rooted at `dir` (one `<domain>.json` per domain). */
111
+ export function createTokenStore(dir: string): TokenStore {
112
+ const domainPath = (domain: string): string => {
113
+ assertSafeDomain(domain);
114
+ return join(dir, `${domain}.json`);
115
+ };
116
+
117
+ // Read a domain file as a slot→token map. Missing/corrupt file → {}.
118
+ // Entries must carry the write() stamp (grant + tokenUrl); anything else —
119
+ // a foreign or hand-edited file — fails the check and reads as empty.
120
+ // Tokens are re-minted, no migration.
121
+ const readFileMap = (domain: string): Record<string, StampedToken> =>
122
+ readSlotMap(
123
+ domainPath(domain),
124
+ (v) =>
125
+ typeof v.accessToken === "string" &&
126
+ typeof v.grant === "string" &&
127
+ typeof v.tokenUrl === "string",
128
+ );
129
+
130
+ const toSlotInfo = (slot: string, token: StampedToken): TokenSlotInfo => ({
131
+ slot,
132
+ grant: token.grant,
133
+ tokenUrl: token.tokenUrl,
134
+ token,
135
+ });
136
+
137
+ return {
138
+ read(domain, slot) {
139
+ return readFileMap(domain)[slot] ?? null;
140
+ },
141
+ write(domain, slot, token) {
142
+ const map = readFileMap(domain); // sync RMW: atomic wrt the event loop
143
+ map[slot] = token;
144
+ writeJson0600(domainPath(domain), map);
145
+ },
146
+ delete(domain, slot) {
147
+ const map = readFileMap(domain);
148
+ if (!Object.hasOwn(map, slot)) return;
149
+ delete map[slot];
150
+ if (Object.keys(map).length === 0) {
151
+ // Prune the empty file so the domain drops out of listDomains.
152
+ rmSync(domainPath(domain), { force: true });
153
+ } else {
154
+ writeJson0600(domainPath(domain), map);
155
+ }
156
+ },
157
+ listSlots(domain) {
158
+ return Object.entries(readFileMap(domain))
159
+ .map(([slot, token]) => toSlotInfo(slot, token))
160
+ .sort((a, b) => a.slot.localeCompare(b.slot));
161
+ },
162
+ listDomains() {
163
+ if (!existsSync(dir)) return [];
164
+ // Exclude `<domain>.pending.json` — the pending-flow scratch file is
165
+ // not a token domain (a live pending flow must not surface as a
166
+ // bogus "unreadable" row in bare /api oauth).
167
+ return readdirSync(dir)
168
+ .filter((f) => f.endsWith(".json") && !f.endsWith(".pending.json"))
169
+ .map((f) => f.slice(0, -".json".length))
170
+ .sort((a, b) => a.localeCompare(b));
171
+ },
172
+ };
173
+ }
174
+
175
+ // ═══════════════════════════════════════════════════════════════════
176
+ // Module singleton (default file backend) + override hooks
177
+ // ═══════════════════════════════════════════════════════════════════
178
+
179
+ const DEFAULT_DIR = join(homedir(), ".pi", "agent", "pi-lean-host", "oauth");
180
+
181
+ let _dir = DEFAULT_DIR;
182
+ let _store: TokenStore = createTokenStore(_dir);
183
+
184
+ /** Resolve the active store's directory (file backend). */
185
+ export function getOAuthDir(): string {
186
+ return _dir;
187
+ }
188
+
189
+ /** Point the file backend at a different directory (test hook). */
190
+ export function setOAuthDir(dir: string): void {
191
+ _dir = dir;
192
+ _store = createTokenStore(dir);
193
+ }
194
+
195
+ // Convenience API (delegates to the active store). Slot derivation is
196
+ // INTERNAL to the store layer: callers pass the `grant` + `tokenUrl` facts
197
+ // they already carry in their `OAuth2Auth` object — never a precomputed slot.
198
+ export function readToken(
199
+ domain: string,
200
+ grant: string,
201
+ tokenUrl: string,
202
+ ): OAuthToken | null {
203
+ return _store.read(domain, slotKey(grant, tokenUrl));
204
+ }
205
+ export function writeToken(
206
+ domain: string,
207
+ grant: string,
208
+ tokenUrl: string,
209
+ token: OAuthToken,
210
+ ): void {
211
+ // Stamp the record so the store is self-describing (status rows render the
212
+ // real issuer instead of the opaque hash).
213
+ _store.write(domain, slotKey(grant, tokenUrl), { ...token, grant, tokenUrl });
214
+ }
215
+ export function deleteToken(
216
+ domain: string,
217
+ grant: string,
218
+ tokenUrl: string,
219
+ ): void {
220
+ _store.delete(domain, slotKey(grant, tokenUrl));
221
+ }
222
+ export function listSlots(domain: string): TokenSlotInfo[] {
223
+ return _store.listSlots(domain);
224
+ }
225
+ export function listTokenDomains(): string[] {
226
+ return _store.listDomains();
227
+ }
228
+
229
+ // ═══════════════════════════════════════════════════════════════════
230
+ // Pending auth-code flow (manual-code handoff)
231
+ // ═══════════════════════════════════════════════════════════════════
232
+
233
+ /**
234
+ * A pending authorization-code flow — the PKCE verifier + state + redirect_uri
235
+ * generated at the authorize step, persisted so the later paste/`--code`
236
+ * completion step can exchange with the SAME verifier (the code exchange
237
+ * fails if the verifier doesn't match the challenge sent in the authorize
238
+ * URL) and validate the pasted `state`. Written by the authorize step,
239
+ * consumed once at completion. Ephemeral scratch — lives on the file dir
240
+ * even if a keychain token backend is swapped in. Stored as
241
+ * `Record<slot, PendingAuthCodeFlow>` in `<domain>.pending.json` (slot-keyed
242
+ * like the token file; only `authorization_code` ever writes entries, so a
243
+ * pending slot is always an auth-code slot). Kept OUTSIDE the `TokenStore`
244
+ * interface on purpose — a keychain backend swap must not carry it.
245
+ */
246
+ export interface PendingAuthCodeFlow {
247
+ verifier: string;
248
+ state: string;
249
+ /** The redirect URI sent in the authorize request — the token exchange
250
+ * must send the SAME URI (RFC 6749 §4.1.3). Defaulted to REDIRECT_URI
251
+ * by the flow; user-overridable per invocation (e.g. Twitch requires
252
+ * https or the `localhost` spelling). Read back on `--code` completion. */
253
+ redirectUri: string;
254
+ }
255
+
256
+ function pendingPath(domain: string): string {
257
+ assertSafeDomain(domain);
258
+ return join(_dir, `${domain}.pending.json`);
259
+ }
260
+
261
+ function readPendingMap(domain: string): Record<string, PendingAuthCodeFlow> {
262
+ return readSlotMap(
263
+ pendingPath(domain),
264
+ (v) =>
265
+ typeof v.verifier === "string" &&
266
+ typeof v.redirectUri === "string" &&
267
+ typeof v.state === "string",
268
+ );
269
+ }
270
+
271
+ export function writePendingFlow(
272
+ domain: string,
273
+ grant: string,
274
+ tokenUrl: string,
275
+ flow: PendingAuthCodeFlow,
276
+ ): void {
277
+ const map = readPendingMap(domain);
278
+ map[slotKey(grant, tokenUrl)] = flow;
279
+ writeJson0600(pendingPath(domain), map);
280
+ }
281
+
282
+ export function readPendingFlow(
283
+ domain: string,
284
+ grant: string,
285
+ tokenUrl: string,
286
+ ): PendingAuthCodeFlow | null {
287
+ return readPendingMap(domain)[slotKey(grant, tokenUrl)] ?? null;
288
+ }
289
+
290
+ export function deletePendingFlow(
291
+ domain: string,
292
+ grant: string,
293
+ tokenUrl: string,
294
+ ): void {
295
+ const p = pendingPath(domain);
296
+ if (!existsSync(p)) return;
297
+ const map = readPendingMap(domain);
298
+ const slot = slotKey(grant, tokenUrl);
299
+ if (!Object.hasOwn(map, slot)) return;
300
+ delete map[slot];
301
+ if (Object.keys(map).length === 0) {
302
+ rmSync(p, { force: true });
303
+ } else {
304
+ writeJson0600(p, map);
305
+ }
306
+ }