pi-lean-host 0.1.1 → 0.2.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,170 @@
1
+ /**
2
+ * Secrets store — per-domain secret name → value persistence.
3
+ *
4
+ * File backend: `~/.pi/agent/pi-lean-host/secrets/<domain>.json`, one flat
5
+ * JSON object per domain keyed by secret name → value (matches the `secretName`
6
+ * in the future `auth.secretRefs`/`auth.secretQueryRefs` schema fields).
7
+ *
8
+ * Security posture:
9
+ * - Files are written 0600.
10
+ * - The dir is created **lazily on write only**; reads/list never mkdir, so a
11
+ * read-only `$HOME` doesn't get a `secrets/` dir created under it.
12
+ * - Listing surfaces names only, never values.
13
+ *
14
+ * The store is swappable (the `SecretStore` interface + `setStore`) so the
15
+ * deferred OS-keychain backend is a drop-in without touching callers.
16
+ */
17
+
18
+ import { join } from "node:path";
19
+ import { homedir } from "node:os";
20
+ import {
21
+ chmodSync,
22
+ existsSync,
23
+ mkdirSync,
24
+ readFileSync,
25
+ readdirSync,
26
+ rmSync,
27
+ writeFileSync,
28
+ } from "node:fs";
29
+ import { assertSafeDomain } from "./guide-store.js";
30
+
31
+ /** A secret store: read/write/delete one name, list domain/name indexes. */
32
+ export interface SecretStore {
33
+ read(domain: string, name: string): string | null;
34
+ write(domain: string, name: string, value: string): void;
35
+ delete(domain: string, name: string): void;
36
+ deleteDomain(domain: string): void;
37
+ listDomains(): string[];
38
+ listNames(domain: string): string[];
39
+ }
40
+
41
+ /** Reject a secret name that isn't a clean JSON key. */
42
+ function assertSecretName(name: string): void {
43
+ if (name.length === 0 || /[/\\\0]/.test(name)) {
44
+ throw new Error(
45
+ `Invalid secret name '${name}': must be a single name with no '/', '\\', or NUL.`,
46
+ );
47
+ }
48
+ }
49
+
50
+ /** File-backed store rooted at `dir` (one `<domain>.json` per domain). */
51
+ export function createFileStore(dir: string): SecretStore {
52
+ const domainPath = (domain: string): string => {
53
+ assertSafeDomain(domain);
54
+ return join(dir, `${domain}.json`);
55
+ };
56
+
57
+ // Read a domain file as a flat name→value map. Missing/corrupt file → {}.
58
+ // Never touches the filesystem's dir structure (no mkdir).
59
+ const readFile = (domain: string): Record<string, string> => {
60
+ const p = domainPath(domain);
61
+ if (!existsSync(p)) return {};
62
+ try {
63
+ const parsed = JSON.parse(readFileSync(p, "utf-8"));
64
+ return parsed && typeof parsed === "object"
65
+ ? (parsed as Record<string, string>)
66
+ : {};
67
+ } catch {
68
+ return {};
69
+ }
70
+ };
71
+
72
+ return {
73
+ read(domain, name) {
74
+ const value = readFile(domain)[name];
75
+ return typeof value === "string" ? value : null;
76
+ },
77
+ write(domain, name, value) {
78
+ const p = domainPath(domain); // also asserts domain safety
79
+ assertSecretName(name);
80
+ // Lazy mkdir on write only — never on read/list.
81
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
82
+ const file = readFile(domain);
83
+ file[name] = value;
84
+ writeFileSync(p, JSON.stringify(file, null, 2) + "\n", { mode: 0o600 });
85
+ try {
86
+ chmodSync(p, 0o600); // guard against umask overriding the mode
87
+ } catch {
88
+ // best-effort; file was already written
89
+ }
90
+ },
91
+ delete(domain, name) {
92
+ const p = domainPath(domain); // also asserts domain safety
93
+ assertSecretName(name);
94
+ if (!existsSync(p)) return;
95
+ const file = readFile(domain);
96
+ if (!Object.hasOwn(file, name)) return;
97
+ delete file[name];
98
+ if (Object.keys(file).length === 0) {
99
+ // Prune the empty file so the domain drops out of listDomains.
100
+ rmSync(p, { force: true });
101
+ } else {
102
+ writeFileSync(p, JSON.stringify(file, null, 2) + "\n", { mode: 0o600 });
103
+ try {
104
+ chmodSync(p, 0o600);
105
+ } catch {
106
+ // best-effort; file was already written
107
+ }
108
+ }
109
+ },
110
+ deleteDomain(domain) {
111
+ const p = domainPath(domain); // also asserts domain safety
112
+ if (existsSync(p)) rmSync(p, { force: true });
113
+ },
114
+ listDomains() {
115
+ if (!existsSync(dir)) return [];
116
+ return readdirSync(dir)
117
+ .filter((f) => f.endsWith(".json"))
118
+ .map((f) => f.slice(0, -".json".length))
119
+ .sort((a, b) => a.localeCompare(b));
120
+ },
121
+ listNames(domain) {
122
+ return Object.keys(readFile(domain)).sort((a, b) => a.localeCompare(b));
123
+ },
124
+ };
125
+ }
126
+
127
+ // ═══════════════════════════════════════════════════════════════════
128
+ // Module singleton (default file backend) + override hooks
129
+ // ═══════════════════════════════════════════════════════════════════
130
+
131
+ const DEFAULT_DIR = join(homedir(), ".pi", "agent", "pi-lean-host", "secrets");
132
+
133
+ let _dir = DEFAULT_DIR;
134
+ let _store: SecretStore = createFileStore(_dir);
135
+
136
+ /** Resolve the active store's directory (file backend). */
137
+ export function getSecretsDir(): string {
138
+ return _dir;
139
+ }
140
+
141
+ /** Point the file backend at a different directory (test hook). */
142
+ export function setSecretsDir(dir: string): void {
143
+ _dir = dir;
144
+ _store = createFileStore(dir);
145
+ }
146
+
147
+ /** Swap in a different store backend (e.g. OS-keychain, deferred). */
148
+ export function setStore(store: SecretStore): void {
149
+ _store = store;
150
+ }
151
+
152
+ // Convenience API (delegates to the active store).
153
+ export function readSecret(domain: string, name: string): string | null {
154
+ return _store.read(domain, name);
155
+ }
156
+ export function writeSecret(domain: string, name: string, value: string): void {
157
+ _store.write(domain, name, value);
158
+ }
159
+ export function deleteSecret(domain: string, name: string): void {
160
+ _store.delete(domain, name);
161
+ }
162
+ export function deleteDomain(domain: string): void {
163
+ _store.deleteDomain(domain);
164
+ }
165
+ export function listDomains(): string[] {
166
+ return _store.listDomains();
167
+ }
168
+ export function listNames(domain: string): string[] {
169
+ return _store.listNames(domain);
170
+ }
package/core/transport.ts CHANGED
@@ -43,12 +43,35 @@ export interface FetchOptions {
43
43
  maxRetries?: number;
44
44
  /** Skip cache (force fresh fetch). */
45
45
  fresh?: boolean;
46
- /** SSRF-check each redirect target before following it. Use only for
46
+ /** SSRF-check each redirect target before following it. Use it for
47
47
  * server-supplied URLs (paginate nextLink) — a malicious API can 302
48
48
  * to an internal host, and when auth headers ship the Authorization
49
49
  * header would attach to the redirect. Agent-supplied URLs don't need
50
- * this (the agent already has bash). */
50
+ * this (the agent already has bash). Forced on automatically for any
51
+ * auth-bearing request (hasAuth), so a keyed call is always guarded. */
51
52
  guardRedirects?: boolean;
53
+ /**
54
+ * Lowercased header names whose values are secrets injected from the
55
+ * secrets store (kind: static-key). Stripped — along with `authorization`
56
+ * — on cross-domain redirect hops so a secret can't leak to another host.
57
+ * Only honored while the guarded-redirect path is active (forced for any
58
+ * auth-bearing request, so this always applies to keyed calls).
59
+ */
60
+ secretHeaderNames?: Set<string>;
61
+ /**
62
+ * True when this request carries a store-injected query-param secret
63
+ * (kind: static-key). Broadens `hasAuth` to cover query-secret-only
64
+ * guides (header-secret callers never set this): the response becomes
65
+ * private (never cached / served from cache) and redirects are guarded.
66
+ */
67
+ hasQuerySecret?: boolean;
68
+ /**
69
+ * Names of store-injected query-param secrets in the request URL. Used by
70
+ * `fetchUrl` to redact the URL in any error message it surfaces, so a raw
71
+ * query secret can never leak into agent context via a transport error
72
+ * (output-channel audit).
73
+ */
74
+ secretQueryParamNames?: Set<string>;
52
75
  /** Charset to decode the body with when the response's Content-Type
53
76
  * header omits one. Honors a guide's `responseShape.charset` for APIs
54
77
  * that serve e.g. ISO-8859-1 bytes without a charset parameter. An
@@ -126,6 +149,32 @@ function cacheKey(url: string, opts?: FetchOptions): string {
126
149
  return suffix ? `${url}${suffix}` : url;
127
150
  }
128
151
 
152
+ /**
153
+ * Output-channel audit — URL channel: redact every secret query param's
154
+ * value to `***` in a URL for surfacing. Returns the URL unchanged when no
155
+ * secret param names are in play (so non-secret guides never get URL-
156
+ * normalized by this). Defined here so the transport layer — the one place
157
+ * that holds a raw request URL and may embed it in an error message — can
158
+ * self-redact instead of relying on callers to remember. `helpers.ts`
159
+ * re-exports it for the capture points it owns (result.url, urls[],
160
+ * HelperError.url).
161
+ */
162
+ export function redactSecretParams(
163
+ url: string,
164
+ secretParamNames?: Set<string>,
165
+ ): string {
166
+ if (!secretParamNames || secretParamNames.size === 0) return url;
167
+ try {
168
+ const u = new URL(url);
169
+ for (const name of secretParamNames) {
170
+ if (u.searchParams.has(name)) u.searchParams.set(name, "***");
171
+ }
172
+ return u.toString();
173
+ } catch {
174
+ return url;
175
+ }
176
+ }
177
+
129
178
  function parseHeaders(
130
179
  hdrs: Dispatcher.ResponseData["headers"],
131
180
  ): Record<string, string> {
@@ -250,17 +299,50 @@ async function singleGet(
250
299
  }
251
300
  }
252
301
 
302
+ /** Host of a URL, or null when unparseable — treated as cross-domain (strip). */
303
+ function hostOf(url: string): string | null {
304
+ try {
305
+ return new URL(url).host;
306
+ } catch {
307
+ return null;
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Drop store-injected secret headers (plus `authorization`) from a request
313
+ * before it leaves the request's original host. Literal auth.headers (not in
314
+ * secretHeaderNames) survive. Used on cross-domain redirect hops only.
315
+ * Exported for the output-channel/SSRF structural tests (case c: cross-domain).
316
+ */
317
+ export function stripSecretHeaders(
318
+ headers: Record<string, string>,
319
+ secretHeaderNames?: Set<string>,
320
+ ): Record<string, string> {
321
+ const drop = new Set<string>(["authorization"]);
322
+ if (secretHeaderNames)
323
+ for (const h of secretHeaderNames) drop.add(h.toLowerCase());
324
+ const out: Record<string, string> = {};
325
+ for (const [k, v] of Object.entries(headers)) {
326
+ if (drop.has(k.toLowerCase())) continue;
327
+ out[k] = v;
328
+ }
329
+ return out;
330
+ }
331
+
253
332
  /**
254
- * Follow redirects manually, SSRF-checking each target. Used only for
255
- * server-supplied URLs (paginate nextLink). GET-only, so method is
256
- * preserved across 301/302/303/307/308 trivially. Returns the final
257
- * response; a redirect to a blocked host throws before it is fetched.
333
+ * Follow redirects manually, SSRF-checking each target. Used for
334
+ * server-supplied URLs (paginate nextLink) and — forced — any auth-bearing
335
+ * request. GET-only, so method is preserved across 301/302/303/307/308
336
+ * trivially. Returns the final response; a redirect to a blocked host
337
+ * throws before it is fetched. Store-injected secrets are stripped on
338
+ * cross-domain hops so a key can't attach to a different host.
258
339
  */
259
340
  async function getWithGuardedRedirects(
260
341
  url: string,
261
342
  reqHeaders: Record<string, string>,
262
343
  startTime: number,
263
344
  timeoutMs: number,
345
+ secretHeaderNames?: Set<string>,
264
346
  ): Promise<{
265
347
  status: number;
266
348
  headers: Record<string, string>;
@@ -268,14 +350,16 @@ async function getWithGuardedRedirects(
268
350
  finalUrl: string;
269
351
  }> {
270
352
  let current = url;
353
+ const originalHost = hostOf(url);
271
354
  for (let hops = 0; hops <= MAX_REDIRECTS; hops++) {
355
+ // Strip store-injected secrets (and Authorization) once a hop leaves
356
+ // the request's original host — a secret must never cross domains.
357
+ const hopHeaders =
358
+ hostOf(current) === originalHost
359
+ ? reqHeaders
360
+ : stripSecretHeaders(reqHeaders, secretHeaderNames);
272
361
  const remaining = timeoutMs - (Date.now() - startTime);
273
- const res = await singleGet(
274
- current,
275
- reqHeaders,
276
- remaining,
277
- noRedirectAgent,
278
- );
362
+ const res = await singleGet(current, hopHeaders, remaining, noRedirectAgent);
279
363
  const isRedirect =
280
364
  res.status >= 300 && res.status < 400 && res.status !== 304;
281
365
  if (!isRedirect || hops === MAX_REDIRECTS) return res;
@@ -337,10 +421,15 @@ export async function fetchUrl(
337
421
  const hasAuthHeaders =
338
422
  !!opts?.headers &&
339
423
  Object.keys(opts.headers).some((h) => h.toLowerCase() !== "accept");
424
+ // Broader hasAuth gate: header-secrets ∨ query-secrets. A query-secret-only
425
+ // guide carries no non-accept header, so hasAuthHeaders alone would
426
+ // miss it — hasQuerySecret closes that gap. Every auth gate below keys on
427
+ // hasAuth: cache-skip, If-None-Match, and the guarded-redirect force.
428
+ const hasAuth = hasAuthHeaders || (opts?.hasQuerySecret ?? false);
340
429
 
341
430
  // ── cache hit ───────────────────────────────────────────────
342
431
  const key = cacheKey(url, opts);
343
- if (!opts?.fresh && !hasAuthHeaders) {
432
+ if (!opts?.fresh && !hasAuth) {
344
433
  const entry = cache.get(key);
345
434
  if (entry && Date.now() < entry.expiresAt) {
346
435
  return { status: 200, headers: {}, body: entry.body, cached: true };
@@ -351,10 +440,10 @@ export async function fetchUrl(
351
440
  const reqHeaders: Record<string, string> = { ...opts?.headers };
352
441
  if (!reqHeaders["user-agent"]) {
353
442
  reqHeaders["user-agent"] =
354
- "pi-lean-host/0.1.0 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
443
+ "pi-lean-host/0.2.0 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
355
444
  }
356
445
 
357
- if (!opts?.fresh && !hasAuthHeaders) {
446
+ if (!opts?.fresh && !hasAuth) {
358
447
  const entry = cache.get(key);
359
448
  if (entry?.etag) {
360
449
  reqHeaders["If-None-Match"] = entry.etag;
@@ -368,16 +457,24 @@ export async function fetchUrl(
368
457
  if (remaining <= 0) throw new Error("Request timeout");
369
458
 
370
459
  try {
371
- // When guardRedirects is set, follow redirects manually and SSRF-
372
- // check each target (server-supplied URLs only). Otherwise let
373
- // undici auto-follow up to 5 redirects.
460
+ // Guarded redirects when explicitly requested (server-supplied
461
+ // nextLink) OR when the request is auth-bearing (hasAuth) — a keyed
462
+ // call is always SSRF-checked hop-by-hop and its secrets stripped on
463
+ // cross-domain redirects. Otherwise let undici auto-follow up to 5.
464
+ const useGuarded = (opts?.guardRedirects ?? false) || hasAuth;
374
465
  const {
375
466
  status,
376
467
  headers: respHeaders,
377
468
  rawBody,
378
469
  finalUrl,
379
- } = opts?.guardRedirects
380
- ? await getWithGuardedRedirects(url, reqHeaders, startTime, timeout)
470
+ } = useGuarded
471
+ ? await getWithGuardedRedirects(
472
+ url,
473
+ reqHeaders,
474
+ startTime,
475
+ timeout,
476
+ opts?.secretHeaderNames,
477
+ )
381
478
  : await singleGet(url, reqHeaders, remaining, redirectAgent);
382
479
 
383
480
  // ── 304 Not Modified ────────────────────────────────
@@ -393,7 +490,7 @@ export async function fetchUrl(
393
490
  headers: respHeaders,
394
491
  body: entry.body,
395
492
  cached: true,
396
- ...(finalUrl !== url ? { finalUrl } : {}),
493
+ ...(finalUrl === url ? {} : { finalUrl }),
397
494
  };
398
495
  }
399
496
  // No cached entry → fall through to process body.
@@ -412,7 +509,7 @@ export async function fetchUrl(
412
509
  const charset = charsetMatch?.[1] ?? opts?.fallbackCharset ?? "utf-8";
413
510
  const body = decodeBuffer(rawBody, charset);
414
511
 
415
- if (status >= 200 && status < 300 && !hasAuthHeaders) {
512
+ if (status >= 200 && status < 300 && !hasAuth) {
416
513
  const maxAge = parseMaxAge(respHeaders) ?? DEFAULT_TTL_MS;
417
514
  const etag = respHeaders["etag"];
418
515
 
@@ -427,7 +524,7 @@ export async function fetchUrl(
427
524
  headers: respHeaders,
428
525
  body,
429
526
  cached: false,
430
- ...(finalUrl !== url ? { finalUrl } : {}),
527
+ ...(finalUrl === url ? {} : { finalUrl }),
431
528
  };
432
529
  } catch (err) {
433
530
  const e = err instanceof Error ? err : new Error(String(err));
@@ -447,5 +544,10 @@ export async function fetchUrl(
447
544
  }
448
545
  }
449
546
 
450
- throw new Error(`Failed to fetch ${url} after ${maxRetries + 1} attempts`);
547
+ // Output-channel audit: never embed the raw request URL in a surfaced
548
+ // message. If a query secret is in play, redact it so the fallthrough
549
+ // (or any future reachable variant) can't leak the key.
550
+ throw new Error(
551
+ `Failed to fetch ${redactSecretParams(url, opts?.secretQueryParamNames)} after ${maxRetries + 1} attempts`,
552
+ );
451
553
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-lean-host",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "REST API client for Pi. A YAML file per API covers endpoints and pagination; the agent calls through a fixed executor so an API encoded once is reusable forever, not re-derived each session. It can probe a live endpoint and write the YAML for you, and a TypeScript file alongside can add custom auth or reshape the request and response freely.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -35,6 +35,9 @@
35
35
  "core/local-helpers.ts",
36
36
  "core/helpers-command.ts",
37
37
  "core/api-toggle.ts",
38
+ "core/secrets-store.ts",
39
+ "core/secrets-command.ts",
40
+ "core/auth.ts",
38
41
  "core/portal-projection.ts",
39
42
  "core/response-spill.ts",
40
43
  "core/verify-ship-manifest.ts",
@@ -20,6 +20,14 @@ import { Text } from "@earendil-works/pi-tui";
20
20
  import { restGet, paginate, HelperError } from "../core/helpers.js";
21
21
  import { findGuidesByDomain } from "../core/guide-store.js";
22
22
  import { callHelper, loadTransform } from "../core/local-helpers.js";
23
+ import {
24
+ resolveSecretHeaders,
25
+ resolveSecretQueryParams,
26
+ authStatusLine,
27
+ canonicalStoreDomain,
28
+ type SecretResolution,
29
+ type QuerySecretResolution,
30
+ } from "../core/auth.js";
23
31
  import { formatGuideListings } from "../core/parse-api-guide.js";
24
32
  import { spillResponse, formatSpillNotice } from "../core/response-spill.js";
25
33
  import { contentText, renderExpandedText } from "./utils.js";
@@ -92,9 +100,8 @@ export const apiFetchTool = defineTool({
92
100
  | Record<string, unknown>
93
101
  | undefined;
94
102
  const gatherAll =
95
- ((params as Record<string, unknown>)["gatherAll"] as
96
- | boolean
97
- | undefined) ?? (rawParams?.gatherAll as boolean | undefined);
103
+ ((params as Record<string, unknown>)["gatherAll"] as boolean | undefined) ??
104
+ (rawParams?.gatherAll as boolean | undefined);
98
105
  const userParams = rawParams ? { ...rawParams } : undefined;
99
106
  if (userParams && "gatherAll" in userParams) {
100
107
  delete userParams.gatherAll;
@@ -158,6 +165,12 @@ export const apiFetchTool = defineTool({
158
165
 
159
166
  const { guide, dirName: helperDirName, op } = opMatches[0]!;
160
167
 
168
+ // 2.5.5 The canonical secret-store key: `guide.domains[0]` (the plain
169
+ // browsable domain). Independent of the routing `domain` the agent
170
+ // passed — auth resolution, the fail-closed error, and the footer all
171
+ // key the store on this canonical value, not on `domain`.
172
+ const storeDomain = canonicalStoreDomain(guide);
173
+
161
174
  // 2.5 Resolve local helper if the operation declares one.
162
175
  // The helper is resolved by the matched guide's directory name
163
176
  // (helperDirName), not by a helper name — one helper per guide lives
@@ -165,11 +178,7 @@ export const apiFetchTool = defineTool({
165
178
  // routing `domain` in the multi-recipe case.
166
179
  let executeParams = userParams ?? {};
167
180
  if (op.helper === true) {
168
- const helperResult = await callHelper(
169
- helperDirName,
170
- op.name,
171
- executeParams,
172
- );
181
+ const helperResult = await callHelper(helperDirName, op.name, executeParams);
173
182
  if (!helperResult.ok) {
174
183
  return {
175
184
  content: [
@@ -207,6 +216,69 @@ export const apiFetchTool = defineTool({
207
216
  );
208
217
  }
209
218
 
219
+ // 2.7 Authentication (kind: static-key): resolve store-injected secret
220
+ // headers AND query params up front so a missing required secret
221
+ // fails closed BEFORE any request is made. Values never leave this
222
+ // scope — only header/param and secret NAMES ever surface to the agent.
223
+ let headerRes: SecretResolution | undefined;
224
+ let queryRes: QuerySecretResolution | undefined;
225
+ if (guide.auth.kind === "static-key") {
226
+ headerRes = resolveSecretHeaders(guide.auth, storeDomain);
227
+ queryRes = resolveSecretQueryParams(guide.auth, storeDomain);
228
+ const missingRequired = [
229
+ ...(headerRes.absentRequired ?? []),
230
+ ...(queryRes.absentRequired ?? []),
231
+ ];
232
+ if (missingRequired.length > 0) {
233
+ return {
234
+ content: [
235
+ {
236
+ type: "text",
237
+ text:
238
+ `🔑 ${guide.shortName} requires a secret not yet provisioned: ` +
239
+ `${missingRequired.join(", ")}.\n` +
240
+ `Run /api secrets ${storeDomain} to provision it, then retry this call.`,
241
+ },
242
+ ],
243
+ details: {
244
+ error: "auth_required_not_provisioned",
245
+ domain,
246
+ operation,
247
+ missing: missingRequired,
248
+ },
249
+ };
250
+ }
251
+ }
252
+ const headerValues = headerRes ? Object.values(headerRes.headers) : [];
253
+ const queryValues = queryRes ? Object.values(queryRes.queryParams) : [];
254
+ const authOpts: {
255
+ authHeaders?: Record<string, string>;
256
+ secretHeaderNames?: Set<string>;
257
+ secretValues?: string[];
258
+ secretQueryParams?: Record<string, string>;
259
+ secretQueryParamNames?: Set<string>;
260
+ } =
261
+ headerRes || queryRes
262
+ ? {
263
+ ...(headerRes
264
+ ? {
265
+ authHeaders: headerRes.headers,
266
+ secretHeaderNames: new Set(
267
+ Object.keys(headerRes.headers).map((h) => h.toLowerCase()),
268
+ ),
269
+ }
270
+ : {}),
271
+ ...(queryRes
272
+ ? {
273
+ secretQueryParams: queryRes.queryParams,
274
+ secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
275
+ }
276
+ : {}),
277
+ secretValues: [...headerValues, ...queryValues],
278
+ }
279
+ : {};
280
+ const authFooter = authStatusLine(guide.auth, storeDomain);
281
+
210
282
  // 3. Execute via the declared helper.
211
283
  try {
212
284
  const helperOpts = {
@@ -219,7 +291,7 @@ export const apiFetchTool = defineTool({
219
291
  op,
220
292
  executeParams,
221
293
  guide,
222
- undefined, // opts — restGet has no SSRF guard to bypass
294
+ authOpts, // opts — restGet has no SSRF bypass; auth headers injected here
223
295
  transformFn ?? undefined,
224
296
  helperDirName,
225
297
  );
@@ -232,6 +304,7 @@ export const apiFetchTool = defineTool({
232
304
  if (gatherAll) {
233
305
  text += `\n⚠ gatherAll ignored — ${operation} is not paginated (via: restGet).`;
234
306
  }
307
+ if (authFooter) text += `\n${authFooter}`;
235
308
  return {
236
309
  content: [{ type: "text", text }],
237
310
  details: {
@@ -240,7 +313,9 @@ export const apiFetchTool = defineTool({
240
313
  shortName: guide.shortName,
241
314
  via: "restGet",
242
315
  request: { method: "GET", url: result.url, params: result.params },
243
- headers: result.headers,
316
+ // Output-channel audit: drop response headers that echo a known
317
+ // secret value (an auth-bearing server must not leak the key).
318
+ headers: scrubSecretHeaders(result.headers, authOpts.secretValues),
244
319
  },
245
320
  };
246
321
  }
@@ -248,6 +323,7 @@ export const apiFetchTool = defineTool({
248
323
  if (op.via === "paginate") {
249
324
  const paginateOpts: Parameters<typeof paginate>[4] = {
250
325
  ...helperOpts,
326
+ ...authOpts,
251
327
  };
252
328
  if (gatherAll !== undefined) paginateOpts.gatherAll = gatherAll;
253
329
  const result = await paginate(
@@ -261,7 +337,7 @@ export const apiFetchTool = defineTool({
261
337
  );
262
338
  const firstUrl = result.urls[0] ?? "";
263
339
  const serverTotal = result.serverTotal;
264
- const text =
340
+ let text =
265
341
  result.items.length === 0 && !result.failedItems
266
342
  ? [
267
343
  `📦 0 item(s) fetched`,
@@ -279,6 +355,7 @@ export const apiFetchTool = defineTool({
279
355
  serverTotal,
280
356
  result.failedItems,
281
357
  );
358
+ if (authFooter) text += `\n${authFooter}`;
282
359
  return {
283
360
  content: [{ type: "text", text }],
284
361
  details: {
@@ -294,7 +371,7 @@ export const apiFetchTool = defineTool({
294
371
  urls: result.urls,
295
372
  },
296
373
  totalFetched: result.totalFetched,
297
- ...(serverTotal !== undefined ? { serverTotal } : {}),
374
+ ...(serverTotal === undefined ? {} : { serverTotal }),
298
375
  ceilingHit: result.ceilingHit,
299
376
  },
300
377
  };
@@ -372,8 +449,7 @@ export const apiFetchTool = defineTool({
372
449
 
373
450
  const shortName = (d?.shortName as string) || (d?.domain as string) || "?";
374
451
  const operation = (d?.operation as string) || "?";
375
- const reqUrl =
376
- ((d?.request as Record<string, unknown>)?.url as string) || "";
452
+ const reqUrl = ((d?.request as Record<string, unknown>)?.url as string) || "";
377
453
  const totalFetched = d?.totalFetched as number | undefined;
378
454
 
379
455
  let text = theme.fg("accent", theme.bold(`📡 ${shortName}`));
@@ -531,9 +607,7 @@ function formatAmbiguousOperation(
531
607
  lines.push(
532
608
  `then re-author one guide via api-learn({domain: "${first.dirName}", recipe: …}) with the colliding operation renamed so the names no longer clash.`,
533
609
  );
534
- lines.push(
535
- `Note: api-learn rewrites a whole recipe, not a single operation.`,
536
- );
610
+ lines.push(`Note: api-learn rewrites a whole recipe, not a single operation.`);
537
611
  return lines.join("\n");
538
612
  }
539
613
 
@@ -556,6 +630,25 @@ function formatHelperDisabled(
556
630
  return lines.join("\n");
557
631
  }
558
632
 
633
+ /**
634
+ * Output-channel audit — response-header echo: drop any response header
635
+ * whose value contains a known store-injected secret. An auth-bearing
636
+ * server must not echo the key back into `details.headers`. Returns the
637
+ * original map unchanged when no secrets are in play.
638
+ */
639
+ function scrubSecretHeaders(
640
+ headers: Record<string, string>,
641
+ secretValues?: string[],
642
+ ): Record<string, string> {
643
+ if (!secretValues || secretValues.length === 0) return headers;
644
+ const out: Record<string, string> = {};
645
+ for (const [k, v] of Object.entries(headers)) {
646
+ if (secretValues.some((s) => s && v.includes(s))) continue;
647
+ out[k] = v;
648
+ }
649
+ return out;
650
+ }
651
+
559
652
  function formatHelperError(
560
653
  err: HelperError,
561
654
  domain: string,