pi-lean-host 0.1.0 → 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.
package/core/helpers.ts CHANGED
@@ -21,7 +21,15 @@ 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 {
25
+ fetchUrl,
26
+ redactSecretParams,
27
+ type FetchOptions,
28
+ } from "./transport.js";
29
+ // Re-export for callers (api-probe.ts) that surface redacted URLs; the
30
+ // implementation now lives in transport.ts so the fetch layer can self-
31
+ // redact any URL it embeds in an error message.
32
+ export { redactSecretParams };
25
33
  import { fillPathTemplate, joinUrl } from "./path-template.js";
26
34
  import type { TransformFn } from "./local-helpers.js"; // type-only — no runtime import (flat dependency direction)
27
35
  import type {
@@ -118,10 +126,16 @@ function fillPathStrict(path: string, params: Record<string, unknown>): string {
118
126
  /**
119
127
  * Build query-string params: apply defaults for query params,
120
128
  * validate required params, and exclude path params.
129
+ *
130
+ * `secretParamNames`: the query-param names that are code-injected from
131
+ * the secrets store. They are excluded from the returned agent-supplied map
132
+ * AND skipped in the `passthrough` branch so an agent-supplied value can't
133
+ * override or race the injection.
121
134
  */
122
135
  function buildQueryParams(
123
136
  operation: Operation,
124
137
  params: Record<string, unknown>,
138
+ secretParamNames?: Set<string>,
125
139
  ): Record<string, string> {
126
140
  const query: Record<string, string> = {};
127
141
  const pathParamSet = new Set(operation.pathParams);
@@ -155,9 +169,7 @@ function buildQueryParams(
155
169
  // params (e.g. BOE's ES query_string DSL) reach the wire as
156
170
  // JSON, not `[object Object]`. Scalars stay as String(val).
157
171
  query[key] =
158
- typeof val === "object" && val !== null
159
- ? JSON.stringify(val)
160
- : String(val);
172
+ typeof val === "object" && val !== null ? JSON.stringify(val) : String(val);
161
173
  }
162
174
  }
163
175
 
@@ -171,6 +183,9 @@ function buildQueryParams(
171
183
  for (const [key, val] of Object.entries(params)) {
172
184
  if (pathParamSet.has(key)) continue; // path params stay in path
173
185
  if (key in operation.params) continue; // already handled above
186
+ // A secretQueryRefs param name is code-injected below the map —
187
+ // drop any agent-supplied value so it can't override or race it.
188
+ if (secretParamNames && secretParamNames.has(key)) continue;
174
189
  if (val === undefined) continue;
175
190
  let v: unknown = val;
176
191
  if (operation.dateParams && key in operation.dateParams) {
@@ -241,6 +256,9 @@ const xmlParser = new XMLParser({
241
256
  textNodeName: "#text",
242
257
  parseAttributeValue: true,
243
258
  trimValues: true,
259
+ // Strip element-name prefixes (message:GenericData → GenericData) so
260
+ // itemsPath/totalCountPath use stable local names across XML providers.
261
+ removeNSPrefix: true,
244
262
  });
245
263
 
246
264
  /**
@@ -300,30 +318,27 @@ function buildUrl(
300
318
 
301
319
  /**
302
320
  * Check auth.kind and branch accordingly.
303
- * v1 realizes only `none`; any other kind throws a structured error.
321
+ * v1 realizes `none` and `static-key` (header injection is resolved by
322
+ * api-fetch and passed via opts.authHeaders — the store is not read here).
304
323
  *
305
324
  * This dispatch is a deliberate seam, not dead code: keeping the field +
306
325
  * dispatch now makes the future keyed-auth build additive (a new `kind`
307
326
  * behind this same `if`/`throw`) rather than a retrofit of every `restGet`/
308
- * `paginate` call site and the guide schema. Do not inline "none" into the
309
- * callers to "simplify" — that burns the additive path. See
327
+ * `paginate` call site and the guide schema. See
310
328
  * `docs/design/api-secrets-roadmap.md` for the build-out plan.
311
329
  */
312
330
  function checkAuth(auth: ApiGuide["auth"]): void {
313
331
  const kind = auth.kind;
314
- if (kind === "none") return; // no auth header needed
332
+ if (kind === "none" || kind === "static-key") return;
315
333
 
316
- // V1 only realizes `none`. The seam exists; error informingly.
334
+ // oauth2 — unrealized seam. A parsed guide can't reach here (oauth2 is
335
+ // rejected at parse), but guard for hand-constructed guides/tests.
317
336
  throw new HelperError(
318
337
  "auth.kind",
319
338
  `Auth kind "${kind}" is not supported in this version`,
320
- "one of: none",
339
+ "one of: none | static-key",
321
340
  kind,
322
- kind === "static-key"
323
- ? "Static-key auth is not yet implemented. Use kind: none for public APIs."
324
- : kind === "oauth2"
325
- ? "OAuth2 is not yet implemented. Use kind: none for public APIs."
326
- : "Use auth.kind: none for public APIs",
341
+ "OAuth2 is not yet implemented. Use kind: none or kind: static-key.",
327
342
  );
328
343
  }
329
344
 
@@ -337,11 +352,17 @@ function fetchWithOpts(
337
352
  extraHeaders?: Record<string, string>,
338
353
  guardRedirects?: boolean,
339
354
  fallbackCharset?: string,
355
+ secretHeaderNames?: Set<string>,
356
+ hasQuerySecret?: boolean,
357
+ secretQueryParamNames?: Set<string>,
340
358
  ): ReturnType<typeof fetchUrl> {
341
359
  const opts: FetchOptions = { headers: { accept, ...extraHeaders } };
342
360
  if (fresh !== undefined) opts.fresh = fresh;
343
361
  if (guardRedirects) opts.guardRedirects = true;
344
362
  if (fallbackCharset) opts.fallbackCharset = fallbackCharset;
363
+ if (secretHeaderNames) opts.secretHeaderNames = secretHeaderNames;
364
+ if (hasQuerySecret) opts.hasQuerySecret = true;
365
+ if (secretQueryParamNames) opts.secretQueryParamNames = secretQueryParamNames;
345
366
  return fetchUrl(url, opts);
346
367
  }
347
368
 
@@ -355,11 +376,14 @@ function fetchWithOpts(
355
376
  * For XML error bodies (common in REST APIs), the `<text>` element is
356
377
  * extracted for a cleaner human message.
357
378
  */
358
- function checkResponseStatus(result: {
359
- status: number;
360
- body: string;
361
- url?: string;
362
- }): void {
379
+ function checkResponseStatus(
380
+ result: {
381
+ status: number;
382
+ body: string;
383
+ url?: string;
384
+ },
385
+ secretValues?: string[],
386
+ ): void {
363
387
  if (result.status < 400) return;
364
388
 
365
389
  // Cap the raw body to avoid flooding the error output.
@@ -370,6 +394,15 @@ function checkResponseStatus(result: {
370
394
  message = textMatch[1]!.trim();
371
395
  }
372
396
 
397
+ // Output-channel audit: scrub known store-injected secret values from the
398
+ // error excerpt so a 401 body echoing an auth header can't leak the key
399
+ // into agent context.
400
+ if (secretValues && secretValues.length > 0) {
401
+ for (const v of secretValues) {
402
+ if (v && v.length > 0) message = message.split(v).join("***");
403
+ }
404
+ }
405
+
373
406
  throw new HelperError(
374
407
  "response",
375
408
  `Unexpected HTTP ${result.status}: ${message}`,
@@ -387,6 +420,16 @@ function checkResponseStatus(result: {
387
420
  export interface RestGetOptions {
388
421
  /** Skip cache — force fresh fetch. */
389
422
  fresh?: boolean;
423
+ /** Store-injected secret headers (kind: static-key). Merged with guide.auth.headers. */
424
+ authHeaders?: Record<string, string>;
425
+ /** Lowercased injected header names — stripped on cross-domain redirects. */
426
+ secretHeaderNames?: Set<string>;
427
+ /** Store-injected secret values — scrubbed from error bodies (output-channel audit). */
428
+ secretValues?: string[];
429
+ /** Store-injected secret query params — appended below the agent params map. */
430
+ secretQueryParams?: Record<string, string>;
431
+ /** The injected query-param names — redacted from every surfaced URL. */
432
+ secretQueryParamNames?: Set<string>;
390
433
  }
391
434
 
392
435
  /**
@@ -394,7 +437,7 @@ export interface RestGetOptions {
394
437
  *
395
438
  * 1. Replaces `{token}` path params from `params`.
396
439
  * 2. Assembles query params with defaults and required validation.
397
- * 3. Checks auth dispatch (only `none` realised in v1).
440
+ * 3. Checks auth dispatch (`none` / `static-key` realized; `oauth2` rejected at parse).
398
441
  * 4. Constructs the full URL.
399
442
  * 5. Builds the Accept header.
400
443
  * 6. Fetches via the transport layer.
@@ -413,17 +456,30 @@ export async function restGet(
413
456
  transformFn?: TransformFn,
414
457
  dirName?: string,
415
458
  ): Promise<RestGetResult> {
416
- // 1. Fill path template.
459
+ // Steps 1/2 unchanged: fill path, build query (agent-supplied only —
460
+ // secret param names are excluded, incl. from the passthrough branch).
417
461
  const resolvedPath = fillPathStrict(operation.path, params);
418
-
419
- // 2. Build query params.
420
- const query = buildQueryParams(operation, params);
462
+ const secretParamNames = opts?.secretQueryParamNames ?? new Set<string>();
463
+ const query = buildQueryParams(operation, params, secretParamNames);
421
464
 
422
465
  // 3. Auth dispatch.
423
466
  checkAuth(guide.auth);
424
467
 
425
- // 4. Build URL.
426
- const url = buildUrl(apiHost, resolvedPath, query);
468
+ // Merge store-injected secret headers with literal auth.headers. The
469
+ // injected names are tracked for cross-domain redirect stripping.
470
+ const extraHeaders = { ...guide.auth.headers, ...opts?.authHeaders };
471
+
472
+ // 4. Build URL. Secret query params are injected BELOW the
473
+ // agent-supplied map — never into it — so the returned `params` stays
474
+ // agent-supplied-only. The fetch uses the raw URL; every surfaced copy
475
+ // (result.url, the URL stored on HelperError.url) is redacted.
476
+ const secretParams = opts?.secretQueryParams ?? {};
477
+ const hasQuerySecret = Object.keys(secretParams).length > 0;
478
+ const fetchUrlRaw = buildUrl(apiHost, resolvedPath, {
479
+ ...query,
480
+ ...secretParams,
481
+ });
482
+ const url = redactSecretParams(fetchUrlRaw, secretParamNames);
427
483
 
428
484
  // 5. Build Accept header — json/xml shorthands expand; everything
429
485
  // else passes through as-is (e.g. application/atom+xml, */*).
@@ -434,18 +490,24 @@ export async function restGet(
434
490
  // APIs); an explicit header charset always wins.
435
491
  const shape = operation.parse ?? guide.responseShape;
436
492
  const result = await fetchWithOpts(
437
- url,
493
+ fetchUrlRaw,
438
494
  accept,
439
495
  opts?.fresh,
440
- guide.auth.headers,
496
+ extraHeaders,
441
497
  undefined,
442
498
  shape.charset,
499
+ opts?.secretHeaderNames,
500
+ hasQuerySecret,
501
+ opts?.secretQueryParamNames,
443
502
  );
444
503
 
445
504
  // 7. Check HTTP status before attempting to parse the body.
446
505
  // This turns "Invalid JSON response: <?xml..." into a clean
447
- // "Unexpected HTTP 400: El parámetro fecha..." message.
448
- checkResponseStatus({ ...result, url });
506
+ // "Unexpected HTTP 400: El parámetro fecha..." message. Secret values are
507
+ // scrubbed from the error excerpt so an auth-echo body can't leak a key.
508
+ // The URL stored on the error object is the REDACTED one (computed
509
+ // upstream of checkResponseStatus) so the secret never reaches the error.
510
+ checkResponseStatus({ ...result, url }, opts?.secretValues);
449
511
 
450
512
  // 8. Parse response using the effective shape resolved above.
451
513
  let data = parseResponse(result.body, shape);
@@ -472,7 +534,7 @@ export async function restGet(
472
534
  headers: result.headers,
473
535
  url,
474
536
  params: query,
475
- ...(transformWarning !== undefined ? { transformWarning } : {}),
537
+ ...(transformWarning === undefined ? {} : { transformWarning }),
476
538
  };
477
539
  }
478
540
 
@@ -489,6 +551,16 @@ export interface PaginateOptions {
489
551
  fresh?: boolean;
490
552
  /** Bypass the nextLink SSRF guard (for testing against local servers). */
491
553
  skipSsrfGuard?: boolean;
554
+ /** Store-injected secret headers (kind: static-key). Merged with guide.auth.headers. */
555
+ authHeaders?: Record<string, string>;
556
+ /** Lowercased injected header names — stripped on cross-domain redirects. */
557
+ secretHeaderNames?: Set<string>;
558
+ /** Store-injected secret values — scrubbed from error bodies (output-channel audit). */
559
+ secretValues?: string[];
560
+ /** Store-injected secret query params — appended below the agent params map. */
561
+ secretQueryParams?: Record<string, string>;
562
+ /** The injected query-param names — redacted from every surfaced URL. */
563
+ secretQueryParamNames?: Set<string>;
492
564
  }
493
565
 
494
566
  /**
@@ -539,6 +611,11 @@ export async function paginate(
539
611
  // Auth dispatch — checked once up front (auth is constant per guide).
540
612
  checkAuth(guide.auth);
541
613
 
614
+ // Merge store-injected secret headers with literal auth.headers once,
615
+ // reused for every page. Injected names are tracked for cross-domain
616
+ // redirect stripping.
617
+ const extraHeaders = { ...guide.auth.headers, ...opts?.authHeaders };
618
+
542
619
  // State for the styles.
543
620
  let cursor: string | undefined;
544
621
  let nextUrl: string | undefined;
@@ -550,20 +627,27 @@ export async function paginate(
550
627
 
551
628
  // Seed offset/page params.
552
629
  if (style === "offset-limit" || style === "page") {
553
- // Caller value, else the recipe's declared default for this page param,
554
- // else 0. Some APIs are 1-based and reject offset=0 (USGS FDSN); a
555
- // recipe expresses that as `params: { offset: { default: 1 } }`.
630
+ // Caller value, else the recipe's declared default for this page
631
+ // param, else the style's framework default: 0 for offset-limit (row
632
+ // offsets start at 0) and 1 for page (nearly all page-indexed APIs are
633
+ // 1-based; a rare 0-based page API overrides with
634
+ // `params: { page: { default: 0 } }`).
635
+ const fallback = style === "page" ? 1 : 0;
556
636
  const rawPage =
557
637
  params[pagCfg.pageParam!] ??
558
638
  operation.params[pagCfg.pageParam!]?.default ??
559
- 0;
560
- page =
561
- typeof rawPage === "number" ? rawPage : parseInt(String(rawPage), 10);
562
- if (isNaN(page)) page = 0;
639
+ fallback;
640
+ page = typeof rawPage === "number" ? rawPage : parseInt(String(rawPage), 10);
641
+ if (isNaN(page)) page = fallback;
563
642
  }
564
643
 
565
644
  // Compute effective params once — used for both per-page building and result transparency.
566
- const effectiveParams = buildQueryParams(operation, params);
645
+ // Agent-supplied only (secret param names excluded, incl. passthrough).
646
+ const secretParamNames = opts?.secretQueryParamNames ?? new Set<string>();
647
+ const effectiveParams = buildQueryParams(operation, params, secretParamNames);
648
+ // Secret query params injected below the agent map on every page's fetch URL.
649
+ const secretParams = opts?.secretQueryParams ?? {};
650
+ const hasQuerySecret = Object.keys(secretParams).length > 0;
567
651
  const urls: string[] = [];
568
652
 
569
653
  while (true) {
@@ -596,10 +680,16 @@ export async function paginate(
596
680
  ? nextUrl
597
681
  : new URL(nextUrl, apiHost).toString();
598
682
  } else {
599
- url = buildUrl(apiHost, resolvedPath, pageParams);
683
+ // Append secret query params below the agent-supplied page params.
684
+ url = buildUrl(apiHost, resolvedPath, {
685
+ ...pageParams,
686
+ ...secretParams,
687
+ });
600
688
  }
601
689
 
602
- urls.push(url);
690
+ // Every surfaced URL (incl. a server-supplied nextUrl that may
691
+ // already carry the secret) is redacted at the capture point.
692
+ urls.push(redactSecretParams(url, secretParamNames));
603
693
 
604
694
  // NextLink guard — the URL comes from the remote server, so this is
605
695
  // the one place SSRF protection is load-bearing. `guardThisFetch`
@@ -612,13 +702,14 @@ export async function paginate(
612
702
  if (guardThisFetch) {
613
703
  const guard = ssrfGuard(url);
614
704
  if (!guard.ok) {
705
+ const errUrl = redactSecretParams(url, secretParamNames);
615
706
  throw new HelperError(
616
707
  "url",
617
708
  `URL blocked during pagination: ${guard.reason}`,
618
709
  "a safe, public URL",
619
- url,
710
+ errUrl,
620
711
  undefined,
621
- url,
712
+ errUrl,
622
713
  );
623
714
  }
624
715
  }
@@ -628,13 +719,21 @@ export async function paginate(
628
719
  url,
629
720
  accept,
630
721
  opts?.fresh,
631
- guide.auth.headers,
722
+ extraHeaders,
632
723
  guardThisFetch,
633
724
  shape.charset,
725
+ opts?.secretHeaderNames,
726
+ hasQuerySecret,
727
+ opts?.secretQueryParamNames,
634
728
  );
635
729
 
636
- // Check HTTP status before attempting to parse.
637
- checkResponseStatus({ ...result, url });
730
+ // Check HTTP status before attempting to parse. Secret values scrubbed
731
+ // from the error excerpt (output-channel audit). The URL stored on
732
+ // the error object is redacted, computed upstream of checkResponseStatus.
733
+ checkResponseStatus(
734
+ { ...result, url: redactSecretParams(url, secretParamNames) },
735
+ opts?.secretValues,
736
+ );
638
737
 
639
738
  // Parse.
640
739
  const data = parseResponse(result.body, shape);
@@ -656,7 +755,13 @@ export async function paginate(
656
755
  }
657
756
 
658
757
  // Extract items from this page.
659
- const pageItems = resolveJsonPath(data, pagCfg.itemsPath);
758
+ let pageItems = resolveJsonPath(data, pagCfg.itemsPath);
759
+ // Normalize a single XML record (or scalar) into an array so the
760
+ // declared list path always yields an array even with one element
761
+ // (e.g. arXiv max_results=1, PubMed retmax=1 box a single record).
762
+ if (pageItems != null && !Array.isArray(pageItems)) {
763
+ pageItems = [pageItems];
764
+ }
660
765
  if (Array.isArray(pageItems)) {
661
766
  if (pageItems.length === 0) break; // empty page → exhaustion
662
767
  // Apply the post-response transform per item. A throwing transform
@@ -716,7 +821,7 @@ export async function paginate(
716
821
  items,
717
822
  totalFetched: items.length + failed.length,
718
823
  ...(failed.length > 0 ? { failedItems: failed } : {}),
719
- ...(serverTotal !== undefined ? { serverTotal } : {}),
824
+ ...(serverTotal === undefined ? {} : { serverTotal }),
720
825
  ceilingHit,
721
826
  urls,
722
827
  pages: urls.length,