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.
- package/README.md +144 -43
- package/core/api-guide-types.ts +22 -1
- package/core/api-toggle.ts +20 -1
- package/core/auth.ts +149 -0
- package/core/helpers.ts +146 -50
- package/core/parse-api-guide.ts +219 -42
- package/core/secrets-command.ts +315 -0
- package/core/secrets-store.ts +170 -0
- package/core/transport.ts +126 -24
- package/package.json +4 -1
- package/tools/api-fetch.ts +110 -17
- package/tools/api-guide.ts +10 -6
- package/tools/api-probe.ts +298 -15
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 {
|
|
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,7 +256,7 @@ const xmlParser = new XMLParser({
|
|
|
241
256
|
textNodeName: "#text",
|
|
242
257
|
parseAttributeValue: true,
|
|
243
258
|
trimValues: true,
|
|
244
|
-
//
|
|
259
|
+
// Strip element-name prefixes (message:GenericData → GenericData) so
|
|
245
260
|
// itemsPath/totalCountPath use stable local names across XML providers.
|
|
246
261
|
removeNSPrefix: true,
|
|
247
262
|
});
|
|
@@ -303,30 +318,27 @@ function buildUrl(
|
|
|
303
318
|
|
|
304
319
|
/**
|
|
305
320
|
* Check auth.kind and branch accordingly.
|
|
306
|
-
* v1 realizes
|
|
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).
|
|
307
323
|
*
|
|
308
324
|
* This dispatch is a deliberate seam, not dead code: keeping the field +
|
|
309
325
|
* dispatch now makes the future keyed-auth build additive (a new `kind`
|
|
310
326
|
* behind this same `if`/`throw`) rather than a retrofit of every `restGet`/
|
|
311
|
-
* `paginate` call site and the guide schema.
|
|
312
|
-
* callers to "simplify" — that burns the additive path. See
|
|
327
|
+
* `paginate` call site and the guide schema. See
|
|
313
328
|
* `docs/design/api-secrets-roadmap.md` for the build-out plan.
|
|
314
329
|
*/
|
|
315
330
|
function checkAuth(auth: ApiGuide["auth"]): void {
|
|
316
331
|
const kind = auth.kind;
|
|
317
|
-
if (kind === "none"
|
|
332
|
+
if (kind === "none" || kind === "static-key") return;
|
|
318
333
|
|
|
319
|
-
//
|
|
334
|
+
// oauth2 — unrealized seam. A parsed guide can't reach here (oauth2 is
|
|
335
|
+
// rejected at parse), but guard for hand-constructed guides/tests.
|
|
320
336
|
throw new HelperError(
|
|
321
337
|
"auth.kind",
|
|
322
338
|
`Auth kind "${kind}" is not supported in this version`,
|
|
323
|
-
"one of: none",
|
|
339
|
+
"one of: none | static-key",
|
|
324
340
|
kind,
|
|
325
|
-
kind
|
|
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",
|
|
341
|
+
"OAuth2 is not yet implemented. Use kind: none or kind: static-key.",
|
|
330
342
|
);
|
|
331
343
|
}
|
|
332
344
|
|
|
@@ -340,11 +352,17 @@ function fetchWithOpts(
|
|
|
340
352
|
extraHeaders?: Record<string, string>,
|
|
341
353
|
guardRedirects?: boolean,
|
|
342
354
|
fallbackCharset?: string,
|
|
355
|
+
secretHeaderNames?: Set<string>,
|
|
356
|
+
hasQuerySecret?: boolean,
|
|
357
|
+
secretQueryParamNames?: Set<string>,
|
|
343
358
|
): ReturnType<typeof fetchUrl> {
|
|
344
359
|
const opts: FetchOptions = { headers: { accept, ...extraHeaders } };
|
|
345
360
|
if (fresh !== undefined) opts.fresh = fresh;
|
|
346
361
|
if (guardRedirects) opts.guardRedirects = true;
|
|
347
362
|
if (fallbackCharset) opts.fallbackCharset = fallbackCharset;
|
|
363
|
+
if (secretHeaderNames) opts.secretHeaderNames = secretHeaderNames;
|
|
364
|
+
if (hasQuerySecret) opts.hasQuerySecret = true;
|
|
365
|
+
if (secretQueryParamNames) opts.secretQueryParamNames = secretQueryParamNames;
|
|
348
366
|
return fetchUrl(url, opts);
|
|
349
367
|
}
|
|
350
368
|
|
|
@@ -358,11 +376,14 @@ function fetchWithOpts(
|
|
|
358
376
|
* For XML error bodies (common in REST APIs), the `<text>` element is
|
|
359
377
|
* extracted for a cleaner human message.
|
|
360
378
|
*/
|
|
361
|
-
function checkResponseStatus(
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
379
|
+
function checkResponseStatus(
|
|
380
|
+
result: {
|
|
381
|
+
status: number;
|
|
382
|
+
body: string;
|
|
383
|
+
url?: string;
|
|
384
|
+
},
|
|
385
|
+
secretValues?: string[],
|
|
386
|
+
): void {
|
|
366
387
|
if (result.status < 400) return;
|
|
367
388
|
|
|
368
389
|
// Cap the raw body to avoid flooding the error output.
|
|
@@ -373,6 +394,15 @@ function checkResponseStatus(result: {
|
|
|
373
394
|
message = textMatch[1]!.trim();
|
|
374
395
|
}
|
|
375
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
|
+
|
|
376
406
|
throw new HelperError(
|
|
377
407
|
"response",
|
|
378
408
|
`Unexpected HTTP ${result.status}: ${message}`,
|
|
@@ -390,6 +420,16 @@ function checkResponseStatus(result: {
|
|
|
390
420
|
export interface RestGetOptions {
|
|
391
421
|
/** Skip cache — force fresh fetch. */
|
|
392
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>;
|
|
393
433
|
}
|
|
394
434
|
|
|
395
435
|
/**
|
|
@@ -397,7 +437,7 @@ export interface RestGetOptions {
|
|
|
397
437
|
*
|
|
398
438
|
* 1. Replaces `{token}` path params from `params`.
|
|
399
439
|
* 2. Assembles query params with defaults and required validation.
|
|
400
|
-
* 3. Checks auth dispatch (
|
|
440
|
+
* 3. Checks auth dispatch (`none` / `static-key` realized; `oauth2` rejected at parse).
|
|
401
441
|
* 4. Constructs the full URL.
|
|
402
442
|
* 5. Builds the Accept header.
|
|
403
443
|
* 6. Fetches via the transport layer.
|
|
@@ -416,17 +456,30 @@ export async function restGet(
|
|
|
416
456
|
transformFn?: TransformFn,
|
|
417
457
|
dirName?: string,
|
|
418
458
|
): Promise<RestGetResult> {
|
|
419
|
-
// 1
|
|
459
|
+
// Steps 1/2 unchanged: fill path, build query (agent-supplied only —
|
|
460
|
+
// secret param names are excluded, incl. from the passthrough branch).
|
|
420
461
|
const resolvedPath = fillPathStrict(operation.path, params);
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
const query = buildQueryParams(operation, params);
|
|
462
|
+
const secretParamNames = opts?.secretQueryParamNames ?? new Set<string>();
|
|
463
|
+
const query = buildQueryParams(operation, params, secretParamNames);
|
|
424
464
|
|
|
425
465
|
// 3. Auth dispatch.
|
|
426
466
|
checkAuth(guide.auth);
|
|
427
467
|
|
|
428
|
-
//
|
|
429
|
-
|
|
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);
|
|
430
483
|
|
|
431
484
|
// 5. Build Accept header — json/xml shorthands expand; everything
|
|
432
485
|
// else passes through as-is (e.g. application/atom+xml, */*).
|
|
@@ -437,18 +490,24 @@ export async function restGet(
|
|
|
437
490
|
// APIs); an explicit header charset always wins.
|
|
438
491
|
const shape = operation.parse ?? guide.responseShape;
|
|
439
492
|
const result = await fetchWithOpts(
|
|
440
|
-
|
|
493
|
+
fetchUrlRaw,
|
|
441
494
|
accept,
|
|
442
495
|
opts?.fresh,
|
|
443
|
-
|
|
496
|
+
extraHeaders,
|
|
444
497
|
undefined,
|
|
445
498
|
shape.charset,
|
|
499
|
+
opts?.secretHeaderNames,
|
|
500
|
+
hasQuerySecret,
|
|
501
|
+
opts?.secretQueryParamNames,
|
|
446
502
|
);
|
|
447
503
|
|
|
448
504
|
// 7. Check HTTP status before attempting to parse the body.
|
|
449
505
|
// This turns "Invalid JSON response: <?xml..." into a clean
|
|
450
|
-
// "Unexpected HTTP 400: El parámetro fecha..." message.
|
|
451
|
-
|
|
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);
|
|
452
511
|
|
|
453
512
|
// 8. Parse response using the effective shape resolved above.
|
|
454
513
|
let data = parseResponse(result.body, shape);
|
|
@@ -475,7 +534,7 @@ export async function restGet(
|
|
|
475
534
|
headers: result.headers,
|
|
476
535
|
url,
|
|
477
536
|
params: query,
|
|
478
|
-
...(transformWarning
|
|
537
|
+
...(transformWarning === undefined ? {} : { transformWarning }),
|
|
479
538
|
};
|
|
480
539
|
}
|
|
481
540
|
|
|
@@ -492,6 +551,16 @@ export interface PaginateOptions {
|
|
|
492
551
|
fresh?: boolean;
|
|
493
552
|
/** Bypass the nextLink SSRF guard (for testing against local servers). */
|
|
494
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>;
|
|
495
564
|
}
|
|
496
565
|
|
|
497
566
|
/**
|
|
@@ -542,6 +611,11 @@ export async function paginate(
|
|
|
542
611
|
// Auth dispatch — checked once up front (auth is constant per guide).
|
|
543
612
|
checkAuth(guide.auth);
|
|
544
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
|
+
|
|
545
619
|
// State for the styles.
|
|
546
620
|
let cursor: string | undefined;
|
|
547
621
|
let nextUrl: string | undefined;
|
|
@@ -553,20 +627,27 @@ export async function paginate(
|
|
|
553
627
|
|
|
554
628
|
// Seed offset/page params.
|
|
555
629
|
if (style === "offset-limit" || style === "page") {
|
|
556
|
-
// Caller value, else the recipe's declared default for this page
|
|
557
|
-
// else
|
|
558
|
-
//
|
|
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;
|
|
559
636
|
const rawPage =
|
|
560
637
|
params[pagCfg.pageParam!] ??
|
|
561
638
|
operation.params[pagCfg.pageParam!]?.default ??
|
|
562
|
-
|
|
563
|
-
page =
|
|
564
|
-
|
|
565
|
-
if (isNaN(page)) page = 0;
|
|
639
|
+
fallback;
|
|
640
|
+
page = typeof rawPage === "number" ? rawPage : parseInt(String(rawPage), 10);
|
|
641
|
+
if (isNaN(page)) page = fallback;
|
|
566
642
|
}
|
|
567
643
|
|
|
568
644
|
// Compute effective params once — used for both per-page building and result transparency.
|
|
569
|
-
|
|
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;
|
|
570
651
|
const urls: string[] = [];
|
|
571
652
|
|
|
572
653
|
while (true) {
|
|
@@ -599,10 +680,16 @@ export async function paginate(
|
|
|
599
680
|
? nextUrl
|
|
600
681
|
: new URL(nextUrl, apiHost).toString();
|
|
601
682
|
} else {
|
|
602
|
-
|
|
683
|
+
// Append secret query params below the agent-supplied page params.
|
|
684
|
+
url = buildUrl(apiHost, resolvedPath, {
|
|
685
|
+
...pageParams,
|
|
686
|
+
...secretParams,
|
|
687
|
+
});
|
|
603
688
|
}
|
|
604
689
|
|
|
605
|
-
|
|
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));
|
|
606
693
|
|
|
607
694
|
// NextLink guard — the URL comes from the remote server, so this is
|
|
608
695
|
// the one place SSRF protection is load-bearing. `guardThisFetch`
|
|
@@ -615,13 +702,14 @@ export async function paginate(
|
|
|
615
702
|
if (guardThisFetch) {
|
|
616
703
|
const guard = ssrfGuard(url);
|
|
617
704
|
if (!guard.ok) {
|
|
705
|
+
const errUrl = redactSecretParams(url, secretParamNames);
|
|
618
706
|
throw new HelperError(
|
|
619
707
|
"url",
|
|
620
708
|
`URL blocked during pagination: ${guard.reason}`,
|
|
621
709
|
"a safe, public URL",
|
|
622
|
-
|
|
710
|
+
errUrl,
|
|
623
711
|
undefined,
|
|
624
|
-
|
|
712
|
+
errUrl,
|
|
625
713
|
);
|
|
626
714
|
}
|
|
627
715
|
}
|
|
@@ -631,13 +719,21 @@ export async function paginate(
|
|
|
631
719
|
url,
|
|
632
720
|
accept,
|
|
633
721
|
opts?.fresh,
|
|
634
|
-
|
|
722
|
+
extraHeaders,
|
|
635
723
|
guardThisFetch,
|
|
636
724
|
shape.charset,
|
|
725
|
+
opts?.secretHeaderNames,
|
|
726
|
+
hasQuerySecret,
|
|
727
|
+
opts?.secretQueryParamNames,
|
|
637
728
|
);
|
|
638
729
|
|
|
639
|
-
// Check HTTP status before attempting to parse.
|
|
640
|
-
|
|
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
|
+
);
|
|
641
737
|
|
|
642
738
|
// Parse.
|
|
643
739
|
const data = parseResponse(result.body, shape);
|
|
@@ -660,7 +756,7 @@ export async function paginate(
|
|
|
660
756
|
|
|
661
757
|
// Extract items from this page.
|
|
662
758
|
let pageItems = resolveJsonPath(data, pagCfg.itemsPath);
|
|
663
|
-
//
|
|
759
|
+
// Normalize a single XML record (or scalar) into an array so the
|
|
664
760
|
// declared list path always yields an array even with one element
|
|
665
761
|
// (e.g. arXiv max_results=1, PubMed retmax=1 box a single record).
|
|
666
762
|
if (pageItems != null && !Array.isArray(pageItems)) {
|
|
@@ -725,7 +821,7 @@ export async function paginate(
|
|
|
725
821
|
items,
|
|
726
822
|
totalFetched: items.length + failed.length,
|
|
727
823
|
...(failed.length > 0 ? { failedItems: failed } : {}),
|
|
728
|
-
...(serverTotal
|
|
824
|
+
...(serverTotal === undefined ? {} : { serverTotal }),
|
|
729
825
|
ceilingHit,
|
|
730
826
|
urls,
|
|
731
827
|
pages: urls.length,
|