pi-lean-host 0.1.1 → 0.2.1

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 ADDED
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Static-key auth — store-backed secret resolution + metadata-only footer.
3
+ *
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
7
+ * map (which only the fetch pipeline consumes, never agent context).
8
+ */
9
+
10
+ import type { AuthConfig, ApiGuide } from "./api-guide-types.js";
11
+ import { readSecret, provisionedDomainsSuffix } from "./secrets-store.js";
12
+
13
+ /**
14
+ * The canonical secret-store key for a guide: its primary browsable domain.
15
+ * `domains:` is parser-required (an `ApiGuide` always has a non-empty
16
+ * `domains` array), so `domains[0]` is always present. No override field,
17
+ * no organization chain, no dirName fallback.
18
+ */
19
+ export function canonicalStoreDomain(guide: ApiGuide): string {
20
+ // `domains` is optional on the Guide base for web-guides, but parser-required
21
+ // (non-empty) on any ApiGuide — see requireStringArray in parse-api-guide.ts.
22
+ return guide.domains![0]!;
23
+ }
24
+
25
+ /** Result of resolving a guide's `auth.secretRefs` against the store. */
26
+ export interface SecretResolution {
27
+ /** headerName → resolved value (with prefix applied), ready to merge into the request. */
28
+ headers: Record<string, string>;
29
+ /**
30
+ * The unprefixed (raw) resolved secret values, for the output-channel
31
+ * audit — a server may echo the bare token, not just the prefixed form.
32
+ */
33
+ rawHeaderValues: string[];
34
+ /** secret names referenced by `requires` that are absent from the store. */
35
+ absentRequired: string[];
36
+ /** secret names referenced by `optional` that are absent from the store. */
37
+ absentOptional: string[];
38
+ }
39
+
40
+ /** Resolve store-secret headers for a `static-key` guide (no-op otherwise). */
41
+ export function resolveSecretHeaders(
42
+ auth: AuthConfig,
43
+ domain: string,
44
+ ): SecretResolution {
45
+ const headers: Record<string, string> = {};
46
+ const rawHeaderValues: string[] = [];
47
+ const absentRequired: string[] = [];
48
+ const absentOptional: string[] = [];
49
+ const requires = auth.requires ?? [];
50
+ for (const [headerName, secretName] of Object.entries(auth.secretRefs ?? {})) {
51
+ const value = readSecret(domain, secretName);
52
+ if (value === null) {
53
+ if (requires.includes(secretName)) absentRequired.push(secretName);
54
+ else absentOptional.push(secretName);
55
+ } else {
56
+ headers[headerName] = (auth.headerPrefixes?.[headerName] ?? "") + value;
57
+ rawHeaderValues.push(value);
58
+ }
59
+ }
60
+ return { headers, rawHeaderValues, absentRequired, absentOptional };
61
+ }
62
+
63
+ /** Result of resolving a guide's `auth.secretQueryRefs` against the store. */
64
+ export interface QuerySecretResolution {
65
+ /** paramName → resolved value, injected below the agent params map. */
66
+ queryParams: Record<string, string>;
67
+ /** secret names referenced by `requires` that are absent from the store. */
68
+ absentRequired: string[];
69
+ /** secret names referenced by `optional` that are absent from the store. */
70
+ absentOptional: string[];
71
+ }
72
+
73
+ /**
74
+ * 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.
78
+ */
79
+ export function resolveSecretQueryParams(
80
+ auth: AuthConfig,
81
+ domain: string,
82
+ ): QuerySecretResolution {
83
+ const queryParams: Record<string, string> = {};
84
+ const absentRequired: string[] = [];
85
+ 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);
91
+ if (value === null) {
92
+ if (requires.includes(secretName)) absentRequired.push(secretName);
93
+ else absentOptional.push(secretName);
94
+ } else {
95
+ queryParams[paramName] = value;
96
+ }
97
+ }
98
+ return { queryParams, absentRequired, absentOptional };
99
+ }
100
+
101
+ /**
102
+ * 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.
107
+ */
108
+ export function authStatusLine(
109
+ auth: AuthConfig,
110
+ domain: string,
111
+ ): 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
+ );
153
+ }
154
+ return "🔑 auth: ok (optional provisioned)";
155
+ }
156
+ return "🔑 auth: ok";
157
+ }
158
+
159
+ /**
160
+ * Output-channel audit — true when `value` contains any known store-injected
161
+ * secret value. Shared by the body/error scrub and the response-header
162
+ * echo drop.
163
+ */
164
+ export function containsSecret(
165
+ value: string,
166
+ secretValues?: string[],
167
+ ): boolean {
168
+ if (!secretValues) return false;
169
+ return secretValues.some((s) => s && s.length > 0 && value.includes(s));
170
+ }
171
+
172
+ /**
173
+ * Output-channel audit — replace every occurrence of a known store-injected
174
+ * secret value in `text` with `***`, so a request/response body or error
175
+ * echoing the key can't leak it into agent context. No-op when no secrets.
176
+ */
177
+ export function scrubSecretValues(
178
+ text: string,
179
+ secretValues?: string[],
180
+ ): string {
181
+ if (!secretValues) return text;
182
+ for (const v of secretValues) {
183
+ if (v && v.length > 0) text = text.split(v).join("***");
184
+ }
185
+ return text;
186
+ }
@@ -50,32 +50,6 @@ export function invalidateCache(): void {
50
50
  _cache = null;
51
51
  }
52
52
 
53
- /**
54
- * Reject a `domain` that could escape the guides dir via path traversal.
55
- *
56
- * Domains are used in `join(guidesDir, domain, ...)` for helper lookups
57
- * and guide writes. A user-typed `/api helpers ../../foo` or an agent
58
- * `api-learn({domain: "../x"})` must not read or write outside the
59
- * guides dir. Returns the domain if safe, throws otherwise.
60
- */
61
- export function assertSafeDomain(domain: string): string {
62
- // A safe domain is a single path segment: no separators, no NUL,
63
- // and not "."/".." (self/parent). Anything else is a literal dir name.
64
- if (
65
- domain.length === 0 ||
66
- domain.includes("/") ||
67
- domain.includes("\\") ||
68
- domain.includes("\0") ||
69
- domain === "." ||
70
- domain === ".."
71
- ) {
72
- throw new Error(
73
- `Invalid domain '${domain}': must be a single path segment with no '/', '\\', or '..'.`,
74
- );
75
- }
76
- return domain;
77
- }
78
-
79
53
  // ═══════════════════════════════════════════════════════════════════
80
54
  // Internal load
81
55
  // ═══════════════════════════════════════════════════════════════════
package/core/helpers.ts CHANGED
@@ -21,7 +21,12 @@ function expandAccept(accept: string): string {
21
21
 
22
22
  import { XMLParser } from "fast-xml-parser";
23
23
  import { ssrfGuard } from "./ssrf-guard.js";
24
- import { fetchUrl, type FetchOptions } from "./transport.js";
24
+ import { scrubSecretValues } from "./auth.js";
25
+ import {
26
+ fetchUrl,
27
+ redactSecretParams,
28
+ type FetchOptions,
29
+ } from "./transport.js";
25
30
  import { fillPathTemplate, joinUrl } from "./path-template.js";
26
31
  import type { TransformFn } from "./local-helpers.js"; // type-only — no runtime import (flat dependency direction)
27
32
  import type {
@@ -118,10 +123,16 @@ function fillPathStrict(path: string, params: Record<string, unknown>): string {
118
123
  /**
119
124
  * Build query-string params: apply defaults for query params,
120
125
  * validate required params, and exclude path params.
126
+ *
127
+ * `secretParamNames`: the query-param names that are code-injected from
128
+ * the secrets store. They are excluded from the returned agent-supplied map
129
+ * AND skipped in the `passthrough` branch so an agent-supplied value can't
130
+ * override or race the injection.
121
131
  */
122
132
  function buildQueryParams(
123
133
  operation: Operation,
124
134
  params: Record<string, unknown>,
135
+ secretParamNames?: Set<string>,
125
136
  ): Record<string, string> {
126
137
  const query: Record<string, string> = {};
127
138
  const pathParamSet = new Set(operation.pathParams);
@@ -155,9 +166,7 @@ function buildQueryParams(
155
166
  // params (e.g. BOE's ES query_string DSL) reach the wire as
156
167
  // JSON, not `[object Object]`. Scalars stay as String(val).
157
168
  query[key] =
158
- typeof val === "object" && val !== null
159
- ? JSON.stringify(val)
160
- : String(val);
169
+ typeof val === "object" && val !== null ? JSON.stringify(val) : String(val);
161
170
  }
162
171
  }
163
172
 
@@ -171,6 +180,9 @@ function buildQueryParams(
171
180
  for (const [key, val] of Object.entries(params)) {
172
181
  if (pathParamSet.has(key)) continue; // path params stay in path
173
182
  if (key in operation.params) continue; // already handled above
183
+ // A secretQueryRefs param name is code-injected below the map —
184
+ // drop any agent-supplied value so it can't override or race it.
185
+ if (secretParamNames && secretParamNames.has(key)) continue;
174
186
  if (val === undefined) continue;
175
187
  let v: unknown = val;
176
188
  if (operation.dateParams && key in operation.dateParams) {
@@ -241,7 +253,7 @@ const xmlParser = new XMLParser({
241
253
  textNodeName: "#text",
242
254
  parseAttributeValue: true,
243
255
  trimValues: true,
244
- // A2: strip element-name prefixes (message:GenericData → GenericData) so
256
+ // Strip element-name prefixes (message:GenericData → GenericData) so
245
257
  // itemsPath/totalCountPath use stable local names across XML providers.
246
258
  removeNSPrefix: true,
247
259
  });
@@ -303,30 +315,26 @@ function buildUrl(
303
315
 
304
316
  /**
305
317
  * Check auth.kind and branch accordingly.
306
- * v1 realizes only `none`; any other kind throws a structured error.
318
+ * v1 realizes `none` and `static-key` (header injection is resolved by
319
+ * api-fetch and passed via opts.authHeaders — the store is not read here).
307
320
  *
308
321
  * This dispatch is a deliberate seam, not dead code: keeping the field +
309
322
  * dispatch now makes the future keyed-auth build additive (a new `kind`
310
323
  * behind this same `if`/`throw`) rather than a retrofit of every `restGet`/
311
- * `paginate` call site and the guide schema. Do not inline "none" into the
312
- * callers to "simplify" — that burns the additive path. See
313
- * `docs/design/api-secrets-roadmap.md` for the build-out plan.
324
+ * `paginate` call site and the guide schema.
314
325
  */
315
326
  function checkAuth(auth: ApiGuide["auth"]): void {
316
327
  const kind = auth.kind;
317
- if (kind === "none") return; // no auth header needed
328
+ if (kind === "none" || kind === "static-key") return;
318
329
 
319
- // V1 only realizes `none`. The seam exists; error informingly.
330
+ // oauth2 — unrealized seam. A parsed guide can't reach here (oauth2 is
331
+ // rejected at parse), but guard for hand-constructed guides/tests.
320
332
  throw new HelperError(
321
333
  "auth.kind",
322
334
  `Auth kind "${kind}" is not supported in this version`,
323
- "one of: none",
335
+ "one of: none | static-key",
324
336
  kind,
325
- kind === "static-key"
326
- ? "Static-key auth is not yet implemented. Use kind: none for public APIs."
327
- : kind === "oauth2"
328
- ? "OAuth2 is not yet implemented. Use kind: none for public APIs."
329
- : "Use auth.kind: none for public APIs",
337
+ "OAuth2 is not yet implemented. Use kind: none or kind: static-key.",
330
338
  );
331
339
  }
332
340
 
@@ -340,11 +348,15 @@ function fetchWithOpts(
340
348
  extraHeaders?: Record<string, string>,
341
349
  guardRedirects?: boolean,
342
350
  fallbackCharset?: string,
351
+ secretHeaderNames?: Set<string>,
352
+ hasQuerySecret?: boolean,
343
353
  ): ReturnType<typeof fetchUrl> {
344
354
  const opts: FetchOptions = { headers: { accept, ...extraHeaders } };
345
355
  if (fresh !== undefined) opts.fresh = fresh;
346
356
  if (guardRedirects) opts.guardRedirects = true;
347
357
  if (fallbackCharset) opts.fallbackCharset = fallbackCharset;
358
+ if (secretHeaderNames) opts.secretHeaderNames = secretHeaderNames;
359
+ if (hasQuerySecret) opts.hasQuerySecret = true;
348
360
  return fetchUrl(url, opts);
349
361
  }
350
362
 
@@ -358,11 +370,14 @@ function fetchWithOpts(
358
370
  * For XML error bodies (common in REST APIs), the `<text>` element is
359
371
  * extracted for a cleaner human message.
360
372
  */
361
- function checkResponseStatus(result: {
362
- status: number;
363
- body: string;
364
- url?: string;
365
- }): void {
373
+ function checkResponseStatus(
374
+ result: {
375
+ status: number;
376
+ body: string;
377
+ url?: string;
378
+ },
379
+ secretValues?: string[],
380
+ ): void {
366
381
  if (result.status < 400) return;
367
382
 
368
383
  // Cap the raw body to avoid flooding the error output.
@@ -373,6 +388,11 @@ function checkResponseStatus(result: {
373
388
  message = textMatch[1]!.trim();
374
389
  }
375
390
 
391
+ // Output-channel audit: scrub known store-injected secret values from the
392
+ // error excerpt so a 401 body echoing an auth header can't leak the key
393
+ // into agent context.
394
+ message = scrubSecretValues(message, secretValues);
395
+
376
396
  throw new HelperError(
377
397
  "response",
378
398
  `Unexpected HTTP ${result.status}: ${message}`,
@@ -390,6 +410,16 @@ function checkResponseStatus(result: {
390
410
  export interface RestGetOptions {
391
411
  /** Skip cache — force fresh fetch. */
392
412
  fresh?: boolean;
413
+ /** Store-injected secret headers (kind: static-key). Merged with guide.auth.headers. */
414
+ authHeaders?: Record<string, string>;
415
+ /** Lowercased injected header names — stripped on cross-domain redirects. */
416
+ secretHeaderNames?: Set<string>;
417
+ /** Store-injected secret values — scrubbed from error bodies (output-channel audit). */
418
+ secretValues?: string[];
419
+ /** Store-injected secret query params — appended below the agent params map. */
420
+ secretQueryParams?: Record<string, string>;
421
+ /** The injected query-param names — redacted from every surfaced URL. */
422
+ secretQueryParamNames?: Set<string>;
393
423
  }
394
424
 
395
425
  /**
@@ -397,7 +427,7 @@ export interface RestGetOptions {
397
427
  *
398
428
  * 1. Replaces `{token}` path params from `params`.
399
429
  * 2. Assembles query params with defaults and required validation.
400
- * 3. Checks auth dispatch (only `none` realised in v1).
430
+ * 3. Checks auth dispatch (`none` / `static-key` realized; `oauth2` rejected at parse).
401
431
  * 4. Constructs the full URL.
402
432
  * 5. Builds the Accept header.
403
433
  * 6. Fetches via the transport layer.
@@ -416,17 +446,30 @@ export async function restGet(
416
446
  transformFn?: TransformFn,
417
447
  dirName?: string,
418
448
  ): Promise<RestGetResult> {
419
- // 1. Fill path template.
449
+ // Steps 1/2 unchanged: fill path, build query (agent-supplied only —
450
+ // secret param names are excluded, incl. from the passthrough branch).
420
451
  const resolvedPath = fillPathStrict(operation.path, params);
421
-
422
- // 2. Build query params.
423
- const query = buildQueryParams(operation, params);
452
+ const secretParamNames = opts?.secretQueryParamNames ?? new Set<string>();
453
+ const query = buildQueryParams(operation, params, secretParamNames);
424
454
 
425
455
  // 3. Auth dispatch.
426
456
  checkAuth(guide.auth);
427
457
 
428
- // 4. Build URL.
429
- const url = buildUrl(apiHost, resolvedPath, query);
458
+ // Merge store-injected secret headers with literal auth.headers. The
459
+ // injected names are tracked for cross-domain redirect stripping.
460
+ const extraHeaders = { ...guide.auth.headers, ...opts?.authHeaders };
461
+
462
+ // 4. Build URL. Secret query params are injected BELOW the
463
+ // agent-supplied map — never into it — so the returned `params` stays
464
+ // agent-supplied-only. The fetch uses the raw URL; every surfaced copy
465
+ // (result.url, the URL stored on HelperError.url) is redacted.
466
+ const secretParams = opts?.secretQueryParams ?? {};
467
+ const hasQuerySecret = Object.keys(secretParams).length > 0;
468
+ const fetchUrlRaw = buildUrl(apiHost, resolvedPath, {
469
+ ...query,
470
+ ...secretParams,
471
+ });
472
+ const url = redactSecretParams(fetchUrlRaw, secretParamNames);
430
473
 
431
474
  // 5. Build Accept header — json/xml shorthands expand; everything
432
475
  // else passes through as-is (e.g. application/atom+xml, */*).
@@ -437,18 +480,23 @@ export async function restGet(
437
480
  // APIs); an explicit header charset always wins.
438
481
  const shape = operation.parse ?? guide.responseShape;
439
482
  const result = await fetchWithOpts(
440
- url,
483
+ fetchUrlRaw,
441
484
  accept,
442
485
  opts?.fresh,
443
- guide.auth.headers,
486
+ extraHeaders,
444
487
  undefined,
445
488
  shape.charset,
489
+ opts?.secretHeaderNames,
490
+ hasQuerySecret,
446
491
  );
447
492
 
448
493
  // 7. Check HTTP status before attempting to parse the body.
449
494
  // This turns "Invalid JSON response: <?xml..." into a clean
450
- // "Unexpected HTTP 400: El parámetro fecha..." message.
451
- checkResponseStatus({ ...result, url });
495
+ // "Unexpected HTTP 400: El parámetro fecha..." message. Secret values are
496
+ // scrubbed from the error excerpt so an auth-echo body can't leak a key.
497
+ // The URL stored on the error object is the REDACTED one (computed
498
+ // upstream of checkResponseStatus) so the secret never reaches the error.
499
+ checkResponseStatus({ ...result, url }, opts?.secretValues);
452
500
 
453
501
  // 8. Parse response using the effective shape resolved above.
454
502
  let data = parseResponse(result.body, shape);
@@ -475,7 +523,7 @@ export async function restGet(
475
523
  headers: result.headers,
476
524
  url,
477
525
  params: query,
478
- ...(transformWarning !== undefined ? { transformWarning } : {}),
526
+ ...(transformWarning === undefined ? {} : { transformWarning }),
479
527
  };
480
528
  }
481
529
 
@@ -492,6 +540,16 @@ export interface PaginateOptions {
492
540
  fresh?: boolean;
493
541
  /** Bypass the nextLink SSRF guard (for testing against local servers). */
494
542
  skipSsrfGuard?: boolean;
543
+ /** Store-injected secret headers (kind: static-key). Merged with guide.auth.headers. */
544
+ authHeaders?: Record<string, string>;
545
+ /** Lowercased injected header names — stripped on cross-domain redirects. */
546
+ secretHeaderNames?: Set<string>;
547
+ /** Store-injected secret values — scrubbed from error bodies (output-channel audit). */
548
+ secretValues?: string[];
549
+ /** Store-injected secret query params — appended below the agent params map. */
550
+ secretQueryParams?: Record<string, string>;
551
+ /** The injected query-param names — redacted from every surfaced URL. */
552
+ secretQueryParamNames?: Set<string>;
495
553
  }
496
554
 
497
555
  /**
@@ -542,6 +600,11 @@ export async function paginate(
542
600
  // Auth dispatch — checked once up front (auth is constant per guide).
543
601
  checkAuth(guide.auth);
544
602
 
603
+ // Merge store-injected secret headers with literal auth.headers once,
604
+ // reused for every page. Injected names are tracked for cross-domain
605
+ // redirect stripping.
606
+ const extraHeaders = { ...guide.auth.headers, ...opts?.authHeaders };
607
+
545
608
  // State for the styles.
546
609
  let cursor: string | undefined;
547
610
  let nextUrl: string | undefined;
@@ -553,20 +616,46 @@ export async function paginate(
553
616
 
554
617
  // Seed offset/page params.
555
618
  if (style === "offset-limit" || style === "page") {
556
- // Caller value, else the recipe's declared default for this page param,
557
- // else 0. Some APIs are 1-based and reject offset=0 (USGS FDSN); a
558
- // recipe expresses that as `params: { offset: { default: 1 } }`.
619
+ // Caller value, else `pagination.base` (where this API's index
620
+ // starts), else the recipe's declared default for this page param,
621
+ // else the style's framework default: 0 for offset-limit (row
622
+ // offsets start at 0) and 1 for page (nearly all page-indexed APIs are
623
+ // 1-based; a rare 0-based page API overrides with
624
+ // `base: 0` or `params: { page: { default: 0 } }`).
625
+ const fallback = style === "page" ? 1 : 0;
559
626
  const rawPage =
560
627
  params[pagCfg.pageParam!] ??
628
+ pagCfg.base ??
561
629
  operation.params[pagCfg.pageParam!]?.default ??
562
- 0;
563
- page =
564
- typeof rawPage === "number" ? rawPage : parseInt(String(rawPage), 10);
565
- if (isNaN(page)) page = 0;
630
+ fallback;
631
+ page = typeof rawPage === "number" ? rawPage : parseInt(String(rawPage), 10);
632
+ if (isNaN(page)) page = fallback;
566
633
  }
567
634
 
568
635
  // Compute effective params once — used for both per-page building and result transparency.
569
- const effectiveParams = buildQueryParams(operation, params);
636
+ // Agent-supplied only (secret param names excluded, incl. passthrough).
637
+ const secretParamNames = opts?.secretQueryParamNames ?? new Set<string>();
638
+ const effectiveParams = buildQueryParams(operation, params, secretParamNames);
639
+
640
+ // Resolve the effective page size once for the seeding styles — the
641
+ // caller's value, else the op's declared default (both already folded into
642
+ // effectiveParams), else pagCfg.pageSize, else 50. Used for the per-page
643
+ // pageSizeParam set AND the offset-limit advance, so a caller-supplied
644
+ // size is honored end-to-end (the row-offset increment must match the size
645
+ // the server honored, or pages overlap/skip).
646
+ let effectivePageSize: number | undefined;
647
+ if (style === "offset-limit" || style === "page") {
648
+ const rawSize =
649
+ pagCfg.pageSizeParam === undefined
650
+ ? undefined
651
+ : (params[pagCfg.pageSizeParam] ?? effectiveParams[pagCfg.pageSizeParam]);
652
+ effectivePageSize =
653
+ rawSize === undefined ? (pagCfg.pageSize ?? 50) : Number(rawSize);
654
+ if (isNaN(effectivePageSize)) effectivePageSize = 50;
655
+ }
656
+ // Secret query params injected below the agent map on every page's fetch URL.
657
+ const secretParams = opts?.secretQueryParams ?? {};
658
+ const hasQuerySecret = Object.keys(secretParams).length > 0;
570
659
  const urls: string[] = [];
571
660
 
572
661
  while (true) {
@@ -578,8 +667,9 @@ export async function paginate(
578
667
 
579
668
  if (style === "offset-limit" || style === "page") {
580
669
  pageParams[pagCfg.pageParam!] = String(page ?? 0);
670
+ // effectivePageSize is always resolved (a number) in this branch.
581
671
  if (pagCfg.pageSizeParam) {
582
- pageParams[pagCfg.pageSizeParam] = String(pagCfg.pageSize ?? 50);
672
+ pageParams[pagCfg.pageSizeParam] = String(effectivePageSize);
583
673
  }
584
674
  } else if (style === "cursor" && cursor !== undefined) {
585
675
  pageParams[pagCfg.cursorParam!] = cursor;
@@ -599,10 +689,16 @@ export async function paginate(
599
689
  ? nextUrl
600
690
  : new URL(nextUrl, apiHost).toString();
601
691
  } else {
602
- url = buildUrl(apiHost, resolvedPath, pageParams);
692
+ // Append secret query params below the agent-supplied page params.
693
+ url = buildUrl(apiHost, resolvedPath, {
694
+ ...pageParams,
695
+ ...secretParams,
696
+ });
603
697
  }
604
698
 
605
- urls.push(url);
699
+ // Every surfaced URL (incl. a server-supplied nextUrl that may
700
+ // already carry the secret) is redacted at the capture point.
701
+ urls.push(redactSecretParams(url, secretParamNames));
606
702
 
607
703
  // NextLink guard — the URL comes from the remote server, so this is
608
704
  // the one place SSRF protection is load-bearing. `guardThisFetch`
@@ -615,13 +711,14 @@ export async function paginate(
615
711
  if (guardThisFetch) {
616
712
  const guard = ssrfGuard(url);
617
713
  if (!guard.ok) {
714
+ const errUrl = redactSecretParams(url, secretParamNames);
618
715
  throw new HelperError(
619
716
  "url",
620
717
  `URL blocked during pagination: ${guard.reason}`,
621
718
  "a safe, public URL",
622
- url,
719
+ errUrl,
623
720
  undefined,
624
- url,
721
+ errUrl,
625
722
  );
626
723
  }
627
724
  }
@@ -631,13 +728,20 @@ export async function paginate(
631
728
  url,
632
729
  accept,
633
730
  opts?.fresh,
634
- guide.auth.headers,
731
+ extraHeaders,
635
732
  guardThisFetch,
636
733
  shape.charset,
734
+ opts?.secretHeaderNames,
735
+ hasQuerySecret,
637
736
  );
638
737
 
639
- // Check HTTP status before attempting to parse.
640
- checkResponseStatus({ ...result, url });
738
+ // Check HTTP status before attempting to parse. Secret values scrubbed
739
+ // from the error excerpt (output-channel audit). The URL stored on
740
+ // the error object is redacted, computed upstream of checkResponseStatus.
741
+ checkResponseStatus(
742
+ { ...result, url: redactSecretParams(url, secretParamNames) },
743
+ opts?.secretValues,
744
+ );
641
745
 
642
746
  // Parse.
643
747
  const data = parseResponse(result.body, shape);
@@ -660,7 +764,7 @@ export async function paginate(
660
764
 
661
765
  // Extract items from this page.
662
766
  let pageItems = resolveJsonPath(data, pagCfg.itemsPath);
663
- // A1: normalize a single XML record (or scalar) into an array so the
767
+ // Normalize a single XML record (or scalar) into an array so the
664
768
  // declared list path always yields an array even with one element
665
769
  // (e.g. arXiv max_results=1, PubMed retmax=1 box a single record).
666
770
  if (pageItems != null && !Array.isArray(pageItems)) {
@@ -710,7 +814,13 @@ export async function paginate(
710
814
  }
711
815
 
712
816
  // Determine next page.
713
- const advanced = advancePagination(style, pagCfg, data, page);
817
+ const advanced = advancePagination(
818
+ style,
819
+ pagCfg,
820
+ data,
821
+ page,
822
+ effectivePageSize,
823
+ );
714
824
 
715
825
  if (!advanced) break;
716
826
 
@@ -725,7 +835,7 @@ export async function paginate(
725
835
  items,
726
836
  totalFetched: items.length + failed.length,
727
837
  ...(failed.length > 0 ? { failedItems: failed } : {}),
728
- ...(serverTotal !== undefined ? { serverTotal } : {}),
838
+ ...(serverTotal === undefined ? {} : { serverTotal }),
729
839
  ceilingHit,
730
840
  urls,
731
841
  pages: urls.length,
@@ -750,13 +860,19 @@ function advancePagination(
750
860
  cfg: NonNullable<Operation["pagination"]>,
751
861
  data: unknown,
752
862
  prevPage?: number,
863
+ effectivePageSize?: number,
753
864
  ): PaginationState | null {
754
865
  if (style === "offset-limit") {
755
866
  // Row-offset semantics: the API skips `offset` items, so the next page
756
- // must advance by the page size, not by 1 (a +1 advance re-reads the
757
- // same rows and overlaps pages). APIs whose param is a true page index
758
- // use style: page, which keeps the +1 advance.
759
- return { page: (prevPage ?? 0) + (cfg.pageSize ?? 50) };
867
+ // must advance by the effective page size (caller value → op default →
868
+ // cfg.pageSize → 50) — the size actually sent — not by 1 (a +1 advance
869
+ // re-reads the same rows and overlaps pages) and not by a stale
870
+ // pageSize (overlaps/skips when the caller overrides the size). APIs
871
+ // whose param is a true page index use style: page, which keeps the +1
872
+ // advance.
873
+ return {
874
+ page: (prevPage ?? 0) + (effectivePageSize ?? cfg.pageSize ?? 50),
875
+ };
760
876
  }
761
877
 
762
878
  if (style === "page") {
@@ -28,7 +28,8 @@
28
28
  import { join } from "node:path";
29
29
  import { pathToFileURL } from "node:url";
30
30
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
31
- import { getUserGuidesDir, assertSafeDomain } from "./guide-store.js";
31
+ import { getUserGuidesDir } from "./guide-store.js";
32
+ import { assertSafeDomain } from "./path-template.js";
32
33
 
33
34
  // ═══════════════════════════════════════════════════════════════════
34
35
  // Session-level state