pi-lean-host 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +201 -513
- package/core/api-guide-types.ts +263 -46
- package/core/api-toggle.ts +245 -40
- package/core/auth.ts +996 -76
- package/core/delete-command.ts +1 -1
- package/core/fs-0600.ts +39 -0
- package/core/guide-catalog.ts +349 -0
- package/core/guide-picker.ts +76 -61
- package/core/guide-store.ts +21 -6
- package/core/helpers-command.ts +6 -5
- package/core/helpers.ts +551 -148
- package/core/local-helpers.ts +17 -2
- package/core/oauth-command.ts +911 -0
- package/core/oauth-flow.ts +376 -0
- package/core/oauth-store.ts +306 -0
- package/core/parse-api-guide.ts +1153 -542
- package/core/path-template.ts +147 -0
- package/core/portal-projection.ts +3 -4
- package/core/resolve-op.ts +113 -67
- package/core/response-spill.ts +10 -7
- package/core/secrets-command.ts +18 -13
- package/core/secrets-store.ts +11 -44
- package/core/select-picker.ts +171 -0
- package/core/staging.ts +29 -0
- package/core/status-hint.ts +61 -0
- package/core/transport.ts +321 -34
- package/core/verify-command.ts +215 -116
- package/docs/migration-v1.md +56 -0
- package/index.ts +24 -7
- package/package.json +18 -6
- package/tools/api-fetch.ts +49 -21
- package/tools/api-guide.ts +21 -12
- package/tools/api-learn.ts +515 -126
- package/tools/api-probe.ts +473 -323
- package/tools/api-scaffold.ts +413 -0
- package/tools/api-store.ts +381 -0
- package/tools/oauth-mint.ts +338 -0
- package/tools/utils.ts +1 -1
- package/core/verify-ship-manifest.ts +0 -118
- package/tools/index.ts +0 -7
package/core/helpers.ts
CHANGED
|
@@ -22,17 +22,26 @@ function expandAccept(accept: string): string {
|
|
|
22
22
|
import { XMLParser } from "fast-xml-parser";
|
|
23
23
|
import { ssrfGuard } from "./ssrf-guard.js";
|
|
24
24
|
import { scrubSecretValues } from "./auth.js";
|
|
25
|
+
import { serverMessage, isPlanGated } from "./status-hint.js";
|
|
25
26
|
import {
|
|
26
27
|
fetchUrl,
|
|
27
28
|
redactSecretParams,
|
|
29
|
+
redactSecretPathValues,
|
|
28
30
|
type FetchOptions,
|
|
29
31
|
} from "./transport.js";
|
|
30
|
-
import {
|
|
32
|
+
import {
|
|
33
|
+
fillPathTemplate,
|
|
34
|
+
joinUrl,
|
|
35
|
+
tokenizeJsonPath,
|
|
36
|
+
wireParamName,
|
|
37
|
+
} from "./path-template.js";
|
|
31
38
|
import type { TransformFn } from "./local-helpers.js"; // type-only — no runtime import (flat dependency direction)
|
|
32
39
|
import type {
|
|
33
40
|
ApiGuide,
|
|
34
41
|
DateParamFormat,
|
|
42
|
+
ListStyle,
|
|
35
43
|
Operation,
|
|
44
|
+
QueryParamSpec,
|
|
36
45
|
ResponseShape,
|
|
37
46
|
} from "./api-guide-types.js";
|
|
38
47
|
|
|
@@ -71,10 +80,15 @@ export interface RestGetResult {
|
|
|
71
80
|
headers: Record<string, string>;
|
|
72
81
|
/** The full resolved URL that was fetched. */
|
|
73
82
|
url: string;
|
|
74
|
-
/** Effective query params actually sent (post-defaults, post-validation).
|
|
75
|
-
|
|
83
|
+
/** Effective query params actually sent (post-defaults, post-validation).
|
|
84
|
+
* A `listStyle` param's multi-value array surfaces as a real `string[]`
|
|
85
|
+
* keyed by the declared param name (the URL shows the true wire form). */
|
|
86
|
+
params: Record<string, string | string[]>;
|
|
76
87
|
/** Set when a post-response transform throws (raw `data` preserved). */
|
|
77
88
|
transformWarning?: string;
|
|
89
|
+
/** True when the transport served this response from cache (header hit
|
|
90
|
+
* or 304 revalidation). Absent for live fetches. */
|
|
91
|
+
cached?: boolean;
|
|
78
92
|
}
|
|
79
93
|
|
|
80
94
|
export interface PaginateResult {
|
|
@@ -97,8 +111,10 @@ export interface PaginateResult {
|
|
|
97
111
|
urls: string[];
|
|
98
112
|
/** Number of pages fetched (= urls.length). */
|
|
99
113
|
pages: number;
|
|
100
|
-
/** Effective query params actually sent (post-defaults, post-validation).
|
|
101
|
-
|
|
114
|
+
/** Effective query params actually sent (post-defaults, post-validation).
|
|
115
|
+
* A `listStyle` param's multi-value array surfaces as a real `string[]`
|
|
116
|
+
* keyed by the declared param name (the URL shows the true wire form). */
|
|
117
|
+
params: Record<string, string | string[]>;
|
|
102
118
|
}
|
|
103
119
|
|
|
104
120
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -133,8 +149,8 @@ function buildQueryParams(
|
|
|
133
149
|
operation: Operation,
|
|
134
150
|
params: Record<string, unknown>,
|
|
135
151
|
secretParamNames?: Set<string>,
|
|
136
|
-
): Record<string, string> {
|
|
137
|
-
const query: Record<string, string> = {};
|
|
152
|
+
): Record<string, string | string[]> {
|
|
153
|
+
const query: Record<string, string | string[]> = {};
|
|
138
154
|
const pathParamSet = new Set(operation.pathParams);
|
|
139
155
|
|
|
140
156
|
for (const [key, spec] of Object.entries(operation.params)) {
|
|
@@ -158,15 +174,26 @@ function buildQueryParams(
|
|
|
158
174
|
}
|
|
159
175
|
|
|
160
176
|
if (val !== undefined) {
|
|
161
|
-
// Date param normalization — convert to target format before
|
|
177
|
+
// Date param normalization — convert to target format before
|
|
178
|
+
// serialization. An array here is a loud error BEFORE normalization
|
|
179
|
+
// (normalizeDateParam operates on scalars; an array would be
|
|
180
|
+
// silently mangled on the wire as String(val) garbage).
|
|
162
181
|
if (operation.dateParams && key in operation.dateParams) {
|
|
182
|
+
if (Array.isArray(val)) {
|
|
183
|
+
throw new HelperError(
|
|
184
|
+
`params.${key}`,
|
|
185
|
+
`Array value for date param "${key}" — date params are single-valued`,
|
|
186
|
+
"a scalar date value",
|
|
187
|
+
"an array",
|
|
188
|
+
`Pass one date for params.${key} (remove it from dateParams if the API truly accepts multi-value dates — then declare listStyle:).`,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
163
191
|
val = normalizeDateParam(val, operation.dateParams[key]!);
|
|
164
192
|
}
|
|
165
|
-
//
|
|
166
|
-
//
|
|
167
|
-
//
|
|
168
|
-
query[key] =
|
|
169
|
-
typeof val === "object" && val !== null ? JSON.stringify(val) : String(val);
|
|
193
|
+
// Scalars as today; nested objects as JSON (BOE's query_string DSL);
|
|
194
|
+
// arrays only with a declared listStyle (multi-value). Shared with
|
|
195
|
+
// the passthrough loop below — one validator, both sites.
|
|
196
|
+
query[key] = serializeParamValue(key, val, spec.listStyle);
|
|
170
197
|
}
|
|
171
198
|
}
|
|
172
199
|
|
|
@@ -206,16 +233,105 @@ function buildQueryParams(
|
|
|
206
233
|
if (val === undefined) continue;
|
|
207
234
|
let v: unknown = val;
|
|
208
235
|
if (operation.dateParams && key in operation.dateParams) {
|
|
236
|
+
if (Array.isArray(v)) {
|
|
237
|
+
throw new HelperError(
|
|
238
|
+
`params.${key}`,
|
|
239
|
+
`Array value for date param "${key}" — date params are single-valued`,
|
|
240
|
+
"a scalar date value",
|
|
241
|
+
"an array",
|
|
242
|
+
);
|
|
243
|
+
}
|
|
209
244
|
v = normalizeDateParam(v, operation.dateParams[key]!);
|
|
210
245
|
}
|
|
211
|
-
|
|
212
|
-
|
|
246
|
+
// Passthrough keys have no schema and can't declare a listStyle —
|
|
247
|
+
// passing `undefined` makes any array a loud error. Escape valve:
|
|
248
|
+
// declare the param (with a style) instead of passing it undeclared.
|
|
249
|
+
query[key] = serializeParamValue(key, v, undefined);
|
|
213
250
|
}
|
|
214
251
|
}
|
|
215
252
|
|
|
216
253
|
return query;
|
|
217
254
|
}
|
|
218
255
|
|
|
256
|
+
/**
|
|
257
|
+
* Serialize one query-param value — the shared array-rules validator used by
|
|
258
|
+
* BOTH serialization loops (declared params + passthrough) in
|
|
259
|
+
* `buildQueryParams`. The parser's array-`default` validation mirrors these
|
|
260
|
+
* rules at authoring time.
|
|
261
|
+
*
|
|
262
|
+
* - Scalars: exactly as today (`String(val)`).
|
|
263
|
+
* - Nested objects: JSON (BOE's `query_string` DSL must not regress).
|
|
264
|
+
* - Arrays: multi-value, only on a `listStyle`-declared param. Empty arrays
|
|
265
|
+
* and arrays of non-scalars are loud errors (an empty array would silently
|
|
266
|
+
* drop a param that already passed the `required`/`requiresAnyOf` guards;
|
|
267
|
+
* `[object Object]` on the wire is the silent-wrong-wire class this
|
|
268
|
+
* exists to kill). For `comma`, an element containing a `,` is also loud:
|
|
269
|
+
* the joined wire form is indistinguishable from a longer list.
|
|
270
|
+
* - An array without a `listStyle` (including every passthrough array) is a
|
|
271
|
+
* loud error naming the param and the fix.
|
|
272
|
+
*
|
|
273
|
+
* Returns the stored value: a scalar string, or a real `string[]` for
|
|
274
|
+
* multi-value (expanded to wire pairs in `buildUrl`, the one
|
|
275
|
+
* Record→query-string boundary).
|
|
276
|
+
*/
|
|
277
|
+
function serializeParamValue(
|
|
278
|
+
key: string,
|
|
279
|
+
val: unknown,
|
|
280
|
+
listStyle: ListStyle | undefined,
|
|
281
|
+
): string | string[] {
|
|
282
|
+
if (Array.isArray(val)) {
|
|
283
|
+
if (listStyle === undefined) {
|
|
284
|
+
throw new HelperError(
|
|
285
|
+
`params.${key}`,
|
|
286
|
+
`Array value for query param "${key}" but the param declares no listStyle`,
|
|
287
|
+
"a scalar, or an array on a listStyle-declared param",
|
|
288
|
+
"an array",
|
|
289
|
+
`Declare listStyle: comma | repeat | bracket on params.${key}, or pass a scalar`,
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
if (val.length === 0) {
|
|
293
|
+
throw new HelperError(
|
|
294
|
+
`params.${key}`,
|
|
295
|
+
`Empty array for multi-value query param "${key}" — the param would be silently dropped from the request`,
|
|
296
|
+
"a non-empty array of scalar (string | number | boolean) elements",
|
|
297
|
+
"[]",
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
const out: string[] = [];
|
|
301
|
+
for (const el of val) {
|
|
302
|
+
if (
|
|
303
|
+
el === null ||
|
|
304
|
+
(typeof el !== "string" &&
|
|
305
|
+
typeof el !== "number" &&
|
|
306
|
+
typeof el !== "boolean")
|
|
307
|
+
) {
|
|
308
|
+
throw new HelperError(
|
|
309
|
+
`params.${key}`,
|
|
310
|
+
`Non-scalar element in multi-value query param "${key}"`,
|
|
311
|
+
"an array of scalar (string | number | boolean) elements",
|
|
312
|
+
typeof el === "object" && el !== null ? "an object" : String(el),
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
if (listStyle === "comma" && typeof el === "string" && el.includes(",")) {
|
|
316
|
+
throw new HelperError(
|
|
317
|
+
`params.${key}`,
|
|
318
|
+
`Element of "${key}" contains a comma — listStyle: comma joins with ',' and the joined wire form would be indistinguishable from a longer list`,
|
|
319
|
+
"comma-free elements",
|
|
320
|
+
`"${el}"`,
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
out.push(String(el));
|
|
324
|
+
}
|
|
325
|
+
return out;
|
|
326
|
+
}
|
|
327
|
+
// Nested objects/arrays-of-last-resort serialize as JSON so structured
|
|
328
|
+
// query params (e.g. BOE's ES query_string DSL) reach the wire as JSON,
|
|
329
|
+
// not `[object Object]`. Scalars stay as String(val).
|
|
330
|
+
return typeof val === "object" && val !== null
|
|
331
|
+
? JSON.stringify(val)
|
|
332
|
+
: String(val);
|
|
333
|
+
}
|
|
334
|
+
|
|
219
335
|
/**
|
|
220
336
|
* Normalize a date string to a target format.
|
|
221
337
|
* Accepts ISO 8601 (YYYY-MM-DD or with time tail), already-target format,
|
|
@@ -238,19 +354,17 @@ export function normalizeDateParam(
|
|
|
238
354
|
|
|
239
355
|
/**
|
|
240
356
|
* Resolve a simple dot-delimited JSON path against an object.
|
|
241
|
-
* Supports `data.items`, `resultados[0].campo`,
|
|
357
|
+
* Supports `data.items`, `resultados[0].campo`, negative array indexes
|
|
358
|
+
* addressing from the end (`results[-1].id`), `$.items` prefix, and
|
|
359
|
+
* quoted-bracket atomic keys for dot-containing names (`['@odata.nextLink']`).
|
|
242
360
|
*
|
|
243
361
|
* Returns `unknown` by design — the value at an arbitrary JSON path has no
|
|
244
362
|
* named domain type until the caller knows the path they asked for.
|
|
245
363
|
*/
|
|
246
364
|
// pi-lens-ignore: ast-grep:no-unknown-returns
|
|
247
365
|
export function resolveJsonPath(obj: unknown, path: string): unknown {
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
.replace(/^\$\.?/, "")
|
|
251
|
-
.replace(/\[['"](.*?)['"]\]/g, ".$1")
|
|
252
|
-
.replace(/\[(\d+)\]/g, ".$1");
|
|
253
|
-
const parts = normalised.split(".").filter((p) => p.length > 0);
|
|
366
|
+
const parts = tokenizeJsonPath(path);
|
|
367
|
+
if (parts === null) return undefined; // malformed path → miss, never a wrong match
|
|
254
368
|
if (parts.length === 0) return obj;
|
|
255
369
|
|
|
256
370
|
let current: unknown = obj;
|
|
@@ -259,7 +373,10 @@ export function resolveJsonPath(obj: unknown, path: string): unknown {
|
|
|
259
373
|
if (Array.isArray(current)) {
|
|
260
374
|
const idx = parseInt(part, 10);
|
|
261
375
|
if (isNaN(idx)) return undefined;
|
|
262
|
-
|
|
376
|
+
// Negative index addresses from the end; out of bounds → miss.
|
|
377
|
+
const j = idx < 0 ? idx + current.length : idx;
|
|
378
|
+
if (j < 0 || j >= current.length) return undefined;
|
|
379
|
+
current = current[j];
|
|
263
380
|
} else {
|
|
264
381
|
current = (current as Record<string, unknown>)[part];
|
|
265
382
|
}
|
|
@@ -336,9 +453,33 @@ export function parseResponse(body: string, shape: ResponseShape): unknown {
|
|
|
336
453
|
function buildUrl(
|
|
337
454
|
apiHost: string,
|
|
338
455
|
resolvedPath: string,
|
|
339
|
-
query: Record<string, string>,
|
|
456
|
+
query: Record<string, string | string[]>,
|
|
457
|
+
paramSpecs?: Record<string, QueryParamSpec>,
|
|
340
458
|
): string {
|
|
341
|
-
|
|
459
|
+
// The one Record→query-string boundary. Scalars pass through as one
|
|
460
|
+
// pair; a listStyle param's array expands here — `comma` joins (one
|
|
461
|
+
// pair; elements were validated comma-free at build time), `repeat`
|
|
462
|
+
// fans out one pair per element under the declared name, `bracket`
|
|
463
|
+
// fans out with the wire key dressed +"[]". URLSearchParams encodes the
|
|
464
|
+
// brackets (`id%5B%5D=`) and preserves insertion order (secret params
|
|
465
|
+
// ride below the agent pairs — merge-order contract).
|
|
466
|
+
const pairs: [string, string][] = [];
|
|
467
|
+
for (const [key, val] of Object.entries(query)) {
|
|
468
|
+
if (Array.isArray(val)) {
|
|
469
|
+
const style = paramSpecs?.[key]?.listStyle;
|
|
470
|
+
if (style === "comma") {
|
|
471
|
+
pairs.push([key, val.join(",")]);
|
|
472
|
+
} else if (style === "bracket") {
|
|
473
|
+
const wireKey = `${key}[]`;
|
|
474
|
+
for (const el of val) pairs.push([wireKey, el]);
|
|
475
|
+
} else {
|
|
476
|
+
for (const el of val) pairs.push([key, el]); // repeat
|
|
477
|
+
}
|
|
478
|
+
} else {
|
|
479
|
+
pairs.push([key, val]);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return joinUrl(apiHost, resolvedPath, new URLSearchParams(pairs).toString());
|
|
342
483
|
}
|
|
343
484
|
|
|
344
485
|
/**
|
|
@@ -352,39 +493,108 @@ function buildUrl(
|
|
|
352
493
|
* `paginate` call site and the guide schema.
|
|
353
494
|
*/
|
|
354
495
|
function checkAuth(auth: ApiGuide["auth"]): void {
|
|
355
|
-
|
|
356
|
-
|
|
496
|
+
switch (auth.kind) {
|
|
497
|
+
case "none":
|
|
498
|
+
case "static-key":
|
|
499
|
+
case "oauth2":
|
|
500
|
+
return;
|
|
501
|
+
default: {
|
|
502
|
+
// Exhaustiveness: a future fourth kind is a compile error here.
|
|
503
|
+
const _exhaustive: never = auth;
|
|
504
|
+
throw new HelperError(
|
|
505
|
+
"auth.kind",
|
|
506
|
+
`Auth kind "${_exhaustive}" is not supported in this version`,
|
|
507
|
+
"one of: none | static-key | oauth2",
|
|
508
|
+
String(_exhaustive),
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
357
513
|
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
514
|
+
/**
|
|
515
|
+
* Split the caller params around secret-owned path tokens: the
|
|
516
|
+
* path fill sees the merged map (store value wins; any agent-supplied value
|
|
517
|
+
* for a secret-owned token is dropped), while the query builder gets a
|
|
518
|
+
* deletion-only copy. The merged map must never reach buildQueryParams — a
|
|
519
|
+
* `passthrough: true` op without {token} in its path would otherwise leak
|
|
520
|
+
* the plaintext token into the query string and result.params.
|
|
521
|
+
*/
|
|
522
|
+
export function splitPathSecretParams(
|
|
523
|
+
params: Record<string, unknown>,
|
|
524
|
+
pathSecrets: Record<string, string>,
|
|
525
|
+
): {
|
|
526
|
+
fillParams: Record<string, unknown>;
|
|
527
|
+
queryParamsForBuild: Record<string, unknown>;
|
|
528
|
+
} {
|
|
529
|
+
if (Object.keys(pathSecrets).length === 0)
|
|
530
|
+
return { fillParams: params, queryParamsForBuild: params };
|
|
531
|
+
return {
|
|
532
|
+
fillParams: { ...params, ...pathSecrets },
|
|
533
|
+
queryParamsForBuild: Object.fromEntries(
|
|
534
|
+
Object.entries(params).filter(([k]) => !(k in pathSecrets)),
|
|
535
|
+
),
|
|
536
|
+
};
|
|
367
537
|
}
|
|
368
538
|
|
|
369
539
|
/**
|
|
370
|
-
*
|
|
540
|
+
* Compose the two URL redaction channels for a surfaced URL — query params
|
|
541
|
+
* by name, path tokens by value. Both helpers early-return when their
|
|
542
|
+
* input is empty, so callers may pass values/set unconditionally.
|
|
371
543
|
*/
|
|
544
|
+
function redactSurfacedUrl(
|
|
545
|
+
url: string,
|
|
546
|
+
secretParamNames: Set<string>,
|
|
547
|
+
pathValues: string[],
|
|
548
|
+
): string {
|
|
549
|
+
return redactSecretPathValues(
|
|
550
|
+
redactSecretParams(url, secretParamNames),
|
|
551
|
+
pathValues,
|
|
552
|
+
);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** Named args for fetchWithOpts — replaced an 11-param positional tail
|
|
556
|
+
* (review nit #4). Optional fields carry `| undefined` so callers can pass
|
|
557
|
+
* through possibly-undefined values without spreads; falsy booleans are
|
|
558
|
+
* no-ops (truthiness-checked below). */
|
|
559
|
+
interface FetchWithOptsArgs {
|
|
560
|
+
/** Expanded Accept header value. */
|
|
561
|
+
accept: string;
|
|
562
|
+
/** Store-injected secret headers + literal auth.headers, merged. */
|
|
563
|
+
extraHeaders?: Record<string, string> | undefined;
|
|
564
|
+
/** Skip cache — force fresh fetch. */
|
|
565
|
+
fresh?: boolean | undefined;
|
|
566
|
+
/** Route through the transport's SSRF-guarded redirect path. */
|
|
567
|
+
guardRedirects?: boolean | undefined;
|
|
568
|
+
/** Charset fallback for servers that omit Content-Type charset. */
|
|
569
|
+
fallbackCharset?: string | undefined;
|
|
570
|
+
/** Lowercased injected header names — stripped on cross-domain redirects. */
|
|
571
|
+
secretHeaderNames?: Set<string> | undefined;
|
|
572
|
+
/** Suppress ETag cache when query secrets ride the URL. */
|
|
573
|
+
hasQuerySecret?: boolean | undefined;
|
|
574
|
+
/** Injected query-secret names — redacted from every surfaced URL. */
|
|
575
|
+
secretQueryParamNames?: Set<string> | undefined;
|
|
576
|
+
/** Path secrets present — cache-skip + guarded redirects. */
|
|
577
|
+
hasPathSecret?: boolean | undefined;
|
|
578
|
+
/** Redaction closure for cross-domain redirect hops. */
|
|
579
|
+
redactPathSecret?: ((url: string) => string) | undefined;
|
|
580
|
+
}
|
|
581
|
+
|
|
372
582
|
function fetchWithOpts(
|
|
373
583
|
url: string,
|
|
374
|
-
|
|
375
|
-
fresh: boolean | undefined,
|
|
376
|
-
extraHeaders?: Record<string, string>,
|
|
377
|
-
guardRedirects?: boolean,
|
|
378
|
-
fallbackCharset?: string,
|
|
379
|
-
secretHeaderNames?: Set<string>,
|
|
380
|
-
hasQuerySecret?: boolean,
|
|
584
|
+
args: FetchWithOptsArgs,
|
|
381
585
|
): ReturnType<typeof fetchUrl> {
|
|
382
|
-
const opts: FetchOptions = {
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
if (
|
|
386
|
-
if (
|
|
387
|
-
if (
|
|
586
|
+
const opts: FetchOptions = {
|
|
587
|
+
headers: { accept: args.accept, ...args.extraHeaders },
|
|
588
|
+
};
|
|
589
|
+
if (args.fresh !== undefined) opts.fresh = args.fresh;
|
|
590
|
+
if (args.guardRedirects) opts.guardRedirects = true;
|
|
591
|
+
if (args.fallbackCharset) opts.fallbackCharset = args.fallbackCharset;
|
|
592
|
+
if (args.secretHeaderNames) opts.secretHeaderNames = args.secretHeaderNames;
|
|
593
|
+
if (args.hasQuerySecret) opts.hasQuerySecret = true;
|
|
594
|
+
if (args.secretQueryParamNames)
|
|
595
|
+
opts.secretQueryParamNames = args.secretQueryParamNames;
|
|
596
|
+
if (args.hasPathSecret) opts.hasPathSecret = true;
|
|
597
|
+
if (args.redactPathSecret) opts.redactPathSecret = args.redactPathSecret;
|
|
388
598
|
return fetchUrl(url, opts);
|
|
389
599
|
}
|
|
390
600
|
|
|
@@ -408,18 +618,33 @@ function checkResponseStatus(
|
|
|
408
618
|
): void {
|
|
409
619
|
if (result.status < 400) return;
|
|
410
620
|
|
|
621
|
+
// Output-channel audit: scrub known store-injected secret values from the
|
|
622
|
+
// error excerpt so a 401 body echoing an auth header can't leak the key
|
|
623
|
+
// into agent context.
|
|
624
|
+
const scrubbed = scrubSecretValues(result.body, secretValues);
|
|
411
625
|
// Cap the raw body to avoid flooding the error output.
|
|
412
|
-
let message =
|
|
626
|
+
let message = scrubbed.slice(0, 500);
|
|
413
627
|
// Try to extract <text> from BOE-style XML error bodies.
|
|
414
|
-
const textMatch =
|
|
628
|
+
const textMatch = scrubbed.match(/<text>([\s\S]*?)<\/text>/i);
|
|
415
629
|
if (textMatch) {
|
|
416
630
|
message = textMatch[1]!.trim();
|
|
417
631
|
}
|
|
418
632
|
|
|
419
|
-
//
|
|
420
|
-
//
|
|
421
|
-
//
|
|
422
|
-
|
|
633
|
+
// 403 + structured JSON: surface the server's own reason and flag
|
|
634
|
+
// plan-gating so a "plan doesn't support this endpoint" reads as a
|
|
635
|
+
// key/subscription limitation, not a recipe bug. Same classifier as
|
|
636
|
+
// api-probe — one implementation, two call sites. Parses the scrubbed
|
|
637
|
+
// body (full, for the best chance the JSON is intact), never the raw one.
|
|
638
|
+
// Unlike probe, fetch has no auth context, so it only adds the
|
|
639
|
+
// plan-gating hint — no "auth configured correctly" claim.
|
|
640
|
+
if (result.status === 403) {
|
|
641
|
+
const reason = serverMessage(scrubbed);
|
|
642
|
+
if (reason) {
|
|
643
|
+
message = isPlanGated(scrubbed)
|
|
644
|
+
? `${reason} (plan/subscription limitation on the key, not the recipe)`
|
|
645
|
+
: reason;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
423
648
|
|
|
424
649
|
throw new HelperError(
|
|
425
650
|
"response",
|
|
@@ -431,13 +656,106 @@ function checkResponseStatus(
|
|
|
431
656
|
);
|
|
432
657
|
}
|
|
433
658
|
|
|
659
|
+
/**
|
|
660
|
+
* Check a parsed 200 body for a declared present-only-on-error envelope
|
|
661
|
+
* element (`Operation.errorPath`). Resolution of anything other than
|
|
662
|
+
* `undefined` fails the call — presence is the signal, so `null`/""/`0`/
|
|
663
|
+
* `false` all fire (an empty XML element parses to "" and must not read as
|
|
664
|
+
* success); declared-absent is the API's not-an-error signal. Deliberately
|
|
665
|
+
* the inverse of hasMorePath's truthiness (where a RESOLVED falsy value is
|
|
666
|
+
* the stop signal).
|
|
667
|
+
*
|
|
668
|
+
* Generic capped stringify — no API-specific shape sniffing. Known secret
|
|
669
|
+
* values are scrubbed and the (already-redacted) request URL rides the
|
|
670
|
+
* error, same output-channel contract as checkResponseStatus.
|
|
671
|
+
*
|
|
672
|
+
* Placement (paginate loop): the very next statement after parseResponse —
|
|
673
|
+
* BEFORE totalCountPath extraction and both exhaustion breaks. An error page
|
|
674
|
+
* often misses itemsPath entirely (World Bank: error `[{"message":[…]}]` vs
|
|
675
|
+
* success `[meta, records]`), so a check after the breaks never fires — the
|
|
676
|
+
* walk exits with silent `items: []`.
|
|
677
|
+
*/
|
|
678
|
+
function checkErrorEnvelope(
|
|
679
|
+
data: unknown,
|
|
680
|
+
errorPath: string,
|
|
681
|
+
url: string | undefined,
|
|
682
|
+
secretValues?: string[],
|
|
683
|
+
): void {
|
|
684
|
+
const resolved = resolveJsonPath(data, errorPath);
|
|
685
|
+
if (resolved === undefined) return;
|
|
686
|
+
const scrubbed = scrubSecretValues(JSON.stringify(resolved), secretValues);
|
|
687
|
+
throw new HelperError(
|
|
688
|
+
"response",
|
|
689
|
+
`API error envelope at ${errorPath} (HTTP status was 200): ${scrubbed.slice(0, 500)}`,
|
|
690
|
+
`nothing at ${errorPath} (declared-absent = not an error)`,
|
|
691
|
+
undefined,
|
|
692
|
+
undefined,
|
|
693
|
+
url,
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/** Shared secret-handling prelude for both executors (restGet + paginate).
|
|
698
|
+
* Derives every store-secret-derived value the executors need — path-token
|
|
699
|
+
* fill, query assembly inputs, redaction inputs, and the merged header set —
|
|
700
|
+
* from the same inputs in the same way, so a hardening change to one
|
|
701
|
+
* executor can't silently miss the other. Security-critical: keep both
|
|
702
|
+
* executors on this one implementation. */
|
|
703
|
+
function buildExecutorEnv(
|
|
704
|
+
guide: ApiGuide,
|
|
705
|
+
params: Record<string, unknown>,
|
|
706
|
+
opts?: SecretAuthOpts,
|
|
707
|
+
) {
|
|
708
|
+
// Secret-owned path tokens (see splitPathSecretParams): the store fills
|
|
709
|
+
// them BELOW the agent params map — agent-supplied values are dropped.
|
|
710
|
+
const pathSecrets = opts?.secretPathParams ?? {};
|
|
711
|
+
const pathValues = Object.values(pathSecrets);
|
|
712
|
+
const hasPathSecrets = pathValues.length > 0;
|
|
713
|
+
const { fillParams, queryParamsForBuild } = splitPathSecretParams(
|
|
714
|
+
params,
|
|
715
|
+
pathSecrets,
|
|
716
|
+
);
|
|
717
|
+
// Secret query params are injected BELOW the agent-supplied map — never
|
|
718
|
+
// into it — so the returned `params` stays agent-supplied-only.
|
|
719
|
+
const secretParamNames = opts?.secretQueryParamNames ?? new Set<string>();
|
|
720
|
+
const secretParams = opts?.secretQueryParams ?? {};
|
|
721
|
+
const hasQuerySecret = Object.keys(secretParams).length > 0;
|
|
722
|
+
// Redaction closure for cross-domain redirect hops — built here where
|
|
723
|
+
// the values are already in scope; the transport stays value-agnostic.
|
|
724
|
+
const redactPathSecret = hasPathSecrets
|
|
725
|
+
? (u: string) => redactSecretPathValues(u, pathValues)
|
|
726
|
+
: undefined;
|
|
727
|
+
// Merge store-injected secret headers with literal auth.headers. oauth2
|
|
728
|
+
// carries no literal headers (the resolved Bearer token arrives via
|
|
729
|
+
// opts.authHeaders).
|
|
730
|
+
const literalHeaders =
|
|
731
|
+
guide.auth.kind === "oauth2" ? undefined : guide.auth.headers;
|
|
732
|
+
const extraHeaders = { ...literalHeaders, ...opts?.authHeaders };
|
|
733
|
+
return {
|
|
734
|
+
fillParams,
|
|
735
|
+
queryParamsForBuild,
|
|
736
|
+
pathValues,
|
|
737
|
+
secretParamNames,
|
|
738
|
+
secretParams,
|
|
739
|
+
hasQuerySecret,
|
|
740
|
+
hasPathSecrets,
|
|
741
|
+
redactPathSecret,
|
|
742
|
+
extraHeaders,
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
|
|
434
746
|
// ═══════════════════════════════════════════════════════════════════
|
|
435
747
|
// restGet
|
|
436
748
|
// ═══════════════════════════════════════════════════════════════════
|
|
437
749
|
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
750
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
751
|
+
// Store-injected secret auth opts (single source of truth)
|
|
752
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
753
|
+
|
|
754
|
+
/** Store-injected auth opts, forwarded to the executor and reused by the
|
|
755
|
+
* caller for the output-channel audit (secret scrub). Declared once here;
|
|
756
|
+
* RestGetOptions / PaginateOptions / resolve-op's AuthOpts extend it so a
|
|
757
|
+
* producer-side field can't be silently dropped at the executor boundary. */
|
|
758
|
+
export interface SecretAuthOpts {
|
|
441
759
|
/** Store-injected secret headers (kind: static-key). Merged with guide.auth.headers. */
|
|
442
760
|
authHeaders?: Record<string, string>;
|
|
443
761
|
/** Lowercased injected header names — stripped on cross-domain redirects. */
|
|
@@ -448,6 +766,17 @@ export interface RestGetOptions {
|
|
|
448
766
|
secretQueryParams?: Record<string, string>;
|
|
449
767
|
/** The injected query-param names — redacted from every surfaced URL. */
|
|
450
768
|
secretQueryParamNames?: Set<string>;
|
|
769
|
+
/** Store-injected path tokens (kind: static-key secretPathRefs) — pathTokenName → resolved value. Fills {name} in the op path below the agent params map. */
|
|
770
|
+
secretPathParams?: Record<string, string>;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
export interface RestGetOptions extends SecretAuthOpts {
|
|
774
|
+
/** Skip cache — force fresh fetch. */
|
|
775
|
+
fresh?: boolean;
|
|
776
|
+
/** Built-in post-response transform, applied when op.transform === true. */
|
|
777
|
+
transformFn?: TransformFn | undefined;
|
|
778
|
+
/** Guide directory name — transform context domain / helper routing. */
|
|
779
|
+
dirName?: string | undefined;
|
|
451
780
|
}
|
|
452
781
|
|
|
453
782
|
/**
|
|
@@ -471,33 +800,43 @@ export async function restGet(
|
|
|
471
800
|
params: Record<string, unknown>,
|
|
472
801
|
guide: ApiGuide,
|
|
473
802
|
opts?: RestGetOptions,
|
|
474
|
-
transformFn?: TransformFn,
|
|
475
|
-
dirName?: string,
|
|
476
803
|
): Promise<RestGetResult> {
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
804
|
+
const {
|
|
805
|
+
fillParams,
|
|
806
|
+
queryParamsForBuild,
|
|
807
|
+
pathValues,
|
|
808
|
+
secretParamNames,
|
|
809
|
+
secretParams,
|
|
810
|
+
hasQuerySecret,
|
|
811
|
+
hasPathSecrets,
|
|
812
|
+
redactPathSecret,
|
|
813
|
+
extraHeaders,
|
|
814
|
+
} = buildExecutorEnv(guide, params, opts);
|
|
815
|
+
|
|
816
|
+
// Steps 1/2: fill path, build query (agent-supplied only — secret
|
|
817
|
+
// param names are excluded, incl. from the passthrough branch).
|
|
818
|
+
const resolvedPath = fillPathStrict(operation.path, fillParams);
|
|
819
|
+
const query = buildQueryParams(
|
|
820
|
+
operation,
|
|
821
|
+
queryParamsForBuild,
|
|
822
|
+
secretParamNames,
|
|
823
|
+
);
|
|
482
824
|
|
|
483
825
|
// 3. Auth dispatch.
|
|
484
826
|
checkAuth(guide.auth);
|
|
485
827
|
|
|
486
|
-
//
|
|
487
|
-
//
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
//
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
...secretParams,
|
|
499
|
-
});
|
|
500
|
-
const url = redactSecretParams(fetchUrlRaw, secretParamNames);
|
|
828
|
+
// 4. Build URL. The fetch uses the raw URL; every surfaced copy
|
|
829
|
+
// (result.url, the URL stored on HelperError.url) is redacted. Path
|
|
830
|
+
// secrets redact via redactSecretPathValues (value replace, raw +
|
|
831
|
+
// both hex forms); they ride the path, not the query, so
|
|
832
|
+
// redactSecretParams alone can't touch them.
|
|
833
|
+
const fetchUrlRaw = buildUrl(
|
|
834
|
+
apiHost,
|
|
835
|
+
resolvedPath,
|
|
836
|
+
{ ...query, ...secretParams },
|
|
837
|
+
operation.params,
|
|
838
|
+
);
|
|
839
|
+
const url = redactSurfacedUrl(fetchUrlRaw, secretParamNames, pathValues);
|
|
501
840
|
|
|
502
841
|
// 5. Build Accept header — json/xml shorthands expand; everything
|
|
503
842
|
// else passes through as-is (e.g. application/atom+xml, */*).
|
|
@@ -507,16 +846,17 @@ export async function restGet(
|
|
|
507
846
|
// for servers that omit a Content-Type charset (e.g. legacy Latin-1
|
|
508
847
|
// APIs); an explicit header charset always wins.
|
|
509
848
|
const shape = operation.parse ?? guide.responseShape;
|
|
510
|
-
const result = await fetchWithOpts(
|
|
511
|
-
fetchUrlRaw,
|
|
849
|
+
const result = await fetchWithOpts(fetchUrlRaw, {
|
|
512
850
|
accept,
|
|
513
|
-
opts?.fresh,
|
|
514
851
|
extraHeaders,
|
|
515
|
-
|
|
516
|
-
shape.charset,
|
|
517
|
-
opts?.secretHeaderNames,
|
|
852
|
+
fresh: opts?.fresh,
|
|
853
|
+
fallbackCharset: shape.charset,
|
|
854
|
+
secretHeaderNames: opts?.secretHeaderNames,
|
|
518
855
|
hasQuerySecret,
|
|
519
|
-
|
|
856
|
+
secretQueryParamNames: opts?.secretQueryParamNames,
|
|
857
|
+
hasPathSecret: hasPathSecrets,
|
|
858
|
+
redactPathSecret,
|
|
859
|
+
});
|
|
520
860
|
|
|
521
861
|
// 7. Check HTTP status before attempting to parse the body.
|
|
522
862
|
// This turns "Invalid JSON response: <?xml..." into a clean
|
|
@@ -529,17 +869,23 @@ export async function restGet(
|
|
|
529
869
|
// 8. Parse response using the effective shape resolved above.
|
|
530
870
|
let data = parseResponse(result.body, shape);
|
|
531
871
|
|
|
872
|
+
// 8b. 200-with-error-envelope check (op.errorPath) — post-parse,
|
|
873
|
+
// pre-transform: the error envelope is the raw parsed shape.
|
|
874
|
+
if (operation.errorPath !== undefined) {
|
|
875
|
+
checkErrorEnvelope(data, operation.errorPath, url, opts?.secretValues);
|
|
876
|
+
}
|
|
877
|
+
|
|
532
878
|
// 9. Post-response transform (optional). When api-fetch supplied a
|
|
533
879
|
// `transformFn` (op.transform === true), apply it. A throwing transform is
|
|
534
880
|
// caught: keep the raw `data` and carry a `transformWarning` so the caller
|
|
535
881
|
// can surface "⚠ Transform failed:" — the op is NOT disabled, so a
|
|
536
882
|
// subsequent call re-attempts the transform.
|
|
537
883
|
let transformWarning: string | undefined;
|
|
538
|
-
if (transformFn) {
|
|
884
|
+
if (opts?.transformFn) {
|
|
539
885
|
try {
|
|
540
|
-
data = transformFn(data, {
|
|
886
|
+
data = opts.transformFn(data, {
|
|
541
887
|
operation: operation.name,
|
|
542
|
-
domain: dirName ?? "",
|
|
888
|
+
domain: opts.dirName ?? "",
|
|
543
889
|
});
|
|
544
890
|
} catch (err) {
|
|
545
891
|
transformWarning = err instanceof Error ? err.message : String(err);
|
|
@@ -552,6 +898,7 @@ export async function restGet(
|
|
|
552
898
|
url,
|
|
553
899
|
params: query,
|
|
554
900
|
...(transformWarning === undefined ? {} : { transformWarning }),
|
|
901
|
+
...(result.cached ? { cached: true } : {}),
|
|
555
902
|
};
|
|
556
903
|
}
|
|
557
904
|
|
|
@@ -559,7 +906,7 @@ export async function restGet(
|
|
|
559
906
|
// paginate
|
|
560
907
|
// ═══════════════════════════════════════════════════════════════════
|
|
561
908
|
|
|
562
|
-
export interface PaginateOptions {
|
|
909
|
+
export interface PaginateOptions extends SecretAuthOpts {
|
|
563
910
|
/** When true, gather items up to `gatherAllMax`. Default false. */
|
|
564
911
|
gatherAll?: boolean;
|
|
565
912
|
/** Max items to gather when `gatherAll` is true. Overrides guide/operation default. */
|
|
@@ -568,16 +915,10 @@ export interface PaginateOptions {
|
|
|
568
915
|
fresh?: boolean;
|
|
569
916
|
/** Bypass the nextLink SSRF guard (for testing against local servers). */
|
|
570
917
|
skipSsrfGuard?: boolean;
|
|
571
|
-
/**
|
|
572
|
-
|
|
573
|
-
/**
|
|
574
|
-
|
|
575
|
-
/** Store-injected secret values — scrubbed from error bodies (output-channel audit). */
|
|
576
|
-
secretValues?: string[];
|
|
577
|
-
/** Store-injected secret query params — appended below the agent params map. */
|
|
578
|
-
secretQueryParams?: Record<string, string>;
|
|
579
|
-
/** The injected query-param names — redacted from every surfaced URL. */
|
|
580
|
-
secretQueryParamNames?: Set<string>;
|
|
918
|
+
/** Built-in per-item transform, applied when op.transform === true. */
|
|
919
|
+
transformFn?: TransformFn | undefined;
|
|
920
|
+
/** Guide directory name — transform context domain / helper routing. */
|
|
921
|
+
dirName?: string | undefined;
|
|
581
922
|
}
|
|
582
923
|
|
|
583
924
|
/**
|
|
@@ -599,8 +940,6 @@ export async function paginate(
|
|
|
599
940
|
params: Record<string, unknown>,
|
|
600
941
|
guide: ApiGuide,
|
|
601
942
|
opts?: PaginateOptions,
|
|
602
|
-
transformFn?: TransformFn,
|
|
603
|
-
dirName?: string,
|
|
604
943
|
): Promise<PaginateResult> {
|
|
605
944
|
const pagCfg = operation.pagination ?? guide.pagination;
|
|
606
945
|
if (!pagCfg) {
|
|
@@ -628,10 +967,17 @@ export async function paginate(
|
|
|
628
967
|
// Auth dispatch — checked once up front (auth is constant per guide).
|
|
629
968
|
checkAuth(guide.auth);
|
|
630
969
|
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
970
|
+
const {
|
|
971
|
+
fillParams,
|
|
972
|
+
queryParamsForBuild,
|
|
973
|
+
pathValues,
|
|
974
|
+
secretParamNames,
|
|
975
|
+
secretParams,
|
|
976
|
+
hasQuerySecret,
|
|
977
|
+
hasPathSecrets,
|
|
978
|
+
redactPathSecret,
|
|
979
|
+
extraHeaders,
|
|
980
|
+
} = buildExecutorEnv(guide, params, opts);
|
|
635
981
|
|
|
636
982
|
// State for the styles.
|
|
637
983
|
let cursor: string | undefined;
|
|
@@ -662,8 +1008,11 @@ export async function paginate(
|
|
|
662
1008
|
|
|
663
1009
|
// Compute effective params once — used for both per-page building and result transparency.
|
|
664
1010
|
// Agent-supplied only (secret param names excluded, incl. passthrough).
|
|
665
|
-
const
|
|
666
|
-
|
|
1011
|
+
const effectiveParams = buildQueryParams(
|
|
1012
|
+
operation,
|
|
1013
|
+
queryParamsForBuild,
|
|
1014
|
+
secretParamNames,
|
|
1015
|
+
);
|
|
667
1016
|
|
|
668
1017
|
// Resolve the effective page size once for the seeding styles — the
|
|
669
1018
|
// caller's value, else the op's declared default (both already folded into
|
|
@@ -680,21 +1029,36 @@ export async function paginate(
|
|
|
680
1029
|
effectivePageSize =
|
|
681
1030
|
rawSize === undefined ? (pagCfg.pageSize ?? 50) : Number(rawSize);
|
|
682
1031
|
if (isNaN(effectivePageSize)) effectivePageSize = 50;
|
|
1032
|
+
} else if (style === "cursor") {
|
|
1033
|
+
// Terminal fallback for cursor is OMIT (server default applies) — no
|
|
1034
|
+
// fabricated 50 like offset-limit (which needs a real number to advance
|
|
1035
|
+
// row offsets; cursor's position comes from the response cursor). Seed
|
|
1036
|
+
// effectiveParams (not pageParams — rebuilt per iteration) so
|
|
1037
|
+
// result.params stays honest about what was sent.
|
|
1038
|
+
if (
|
|
1039
|
+
pagCfg.pageSizeParam !== undefined &&
|
|
1040
|
+
pagCfg.pageSize !== undefined &&
|
|
1041
|
+
params[pagCfg.pageSizeParam] === undefined &&
|
|
1042
|
+
effectiveParams[pagCfg.pageSizeParam] === undefined
|
|
1043
|
+
) {
|
|
1044
|
+
effectiveParams[pagCfg.pageSizeParam] = String(pagCfg.pageSize);
|
|
1045
|
+
}
|
|
683
1046
|
}
|
|
684
|
-
// Secret query params injected below the agent map on every page's fetch URL.
|
|
685
|
-
const secretParams = opts?.secretQueryParams ?? {};
|
|
686
|
-
const hasQuerySecret = Object.keys(secretParams).length > 0;
|
|
687
1047
|
const urls: string[] = [];
|
|
688
1048
|
|
|
689
1049
|
while (true) {
|
|
690
|
-
// Build per-page params.
|
|
691
|
-
|
|
1050
|
+
// Build per-page params. Keyed supersession: pagination/tokenBag
|
|
1051
|
+
// writes below REPLACE same-named base values via plain overwrite —
|
|
1052
|
+
// only genuinely multi-value (listStyle) keys hold arrays, and the
|
|
1053
|
+
// parse-time collision guard guarantees those never collide with a
|
|
1054
|
+
// pagination/tokenBag wire name, so every write here is a scalar.
|
|
1055
|
+
const pageParams: Record<string, string | string[]> = {};
|
|
692
1056
|
for (const [key, val] of Object.entries(effectiveParams)) {
|
|
693
1057
|
pageParams[key] = val;
|
|
694
1058
|
}
|
|
695
1059
|
|
|
696
1060
|
if (style === "offset-limit" || style === "page") {
|
|
697
|
-
pageParams[pagCfg.pageParam!] = String(page
|
|
1061
|
+
pageParams[pagCfg.pageParam!] = String(page);
|
|
698
1062
|
// effectivePageSize is always resolved (a number) in this branch.
|
|
699
1063
|
if (pagCfg.pageSizeParam) {
|
|
700
1064
|
pageParams[pagCfg.pageSizeParam] = String(effectivePageSize);
|
|
@@ -708,7 +1072,7 @@ export async function paginate(
|
|
|
708
1072
|
}
|
|
709
1073
|
|
|
710
1074
|
// Build URL.
|
|
711
|
-
const resolvedPath = fillPathStrict(operation.path,
|
|
1075
|
+
const resolvedPath = fillPathStrict(operation.path, fillParams);
|
|
712
1076
|
|
|
713
1077
|
let url: string;
|
|
714
1078
|
if (style === "nextLink" && nextUrl) {
|
|
@@ -718,15 +1082,18 @@ export async function paginate(
|
|
|
718
1082
|
: new URL(nextUrl, apiHost).toString();
|
|
719
1083
|
} else {
|
|
720
1084
|
// Append secret query params below the agent-supplied page params.
|
|
721
|
-
url = buildUrl(
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
1085
|
+
url = buildUrl(
|
|
1086
|
+
apiHost,
|
|
1087
|
+
resolvedPath,
|
|
1088
|
+
{ ...pageParams, ...secretParams },
|
|
1089
|
+
operation.params,
|
|
1090
|
+
);
|
|
725
1091
|
}
|
|
726
1092
|
|
|
727
1093
|
// Every surfaced URL (incl. a server-supplied nextUrl that may
|
|
728
|
-
// already carry the secret) is redacted at the capture point
|
|
729
|
-
|
|
1094
|
+
// already carry the secret) is redacted at the capture point — query
|
|
1095
|
+
// params by name, path tokens by value.
|
|
1096
|
+
urls.push(redactSurfacedUrl(url, secretParamNames, pathValues));
|
|
730
1097
|
|
|
731
1098
|
// NextLink guard — the URL comes from the remote server, so this is
|
|
732
1099
|
// the one place SSRF protection is load-bearing. `guardThisFetch`
|
|
@@ -739,7 +1106,9 @@ export async function paginate(
|
|
|
739
1106
|
if (guardThisFetch) {
|
|
740
1107
|
const guard = ssrfGuard(url);
|
|
741
1108
|
if (!guard.ok) {
|
|
742
|
-
|
|
1109
|
+
// The SSRF-block error's errUrl is built separately from the other
|
|
1110
|
+
// surfaced URLs — redact it the same way (query by name, path by value).
|
|
1111
|
+
const errUrl = redactSurfacedUrl(url, secretParamNames, pathValues);
|
|
743
1112
|
throw new HelperError(
|
|
744
1113
|
"url",
|
|
745
1114
|
`URL blocked during pagination: ${guard.reason}`,
|
|
@@ -752,34 +1121,48 @@ export async function paginate(
|
|
|
752
1121
|
}
|
|
753
1122
|
|
|
754
1123
|
// Fetch.
|
|
755
|
-
const result = await fetchWithOpts(
|
|
756
|
-
url,
|
|
1124
|
+
const result = await fetchWithOpts(url, {
|
|
757
1125
|
accept,
|
|
758
|
-
opts?.fresh,
|
|
759
1126
|
extraHeaders,
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
1127
|
+
fresh: opts?.fresh,
|
|
1128
|
+
guardRedirects: guardThisFetch,
|
|
1129
|
+
fallbackCharset: shape.charset,
|
|
1130
|
+
secretHeaderNames: opts?.secretHeaderNames,
|
|
763
1131
|
hasQuerySecret,
|
|
764
|
-
|
|
1132
|
+
secretQueryParamNames: opts?.secretQueryParamNames,
|
|
1133
|
+
hasPathSecret: hasPathSecrets,
|
|
1134
|
+
redactPathSecret,
|
|
1135
|
+
});
|
|
765
1136
|
|
|
766
1137
|
// Check HTTP status before attempting to parse. Secret values scrubbed
|
|
767
1138
|
// from the error excerpt (output-channel audit). The URL stored on
|
|
768
1139
|
// the error object is redacted, computed upstream of checkResponseStatus.
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
opts?.secretValues,
|
|
772
|
-
);
|
|
1140
|
+
const redactedPageUrl = redactSurfacedUrl(url, secretParamNames, pathValues);
|
|
1141
|
+
checkResponseStatus({ ...result, url: redactedPageUrl }, opts?.secretValues);
|
|
773
1142
|
|
|
774
1143
|
// Parse.
|
|
775
1144
|
const data = parseResponse(result.body, shape);
|
|
776
1145
|
|
|
777
|
-
//
|
|
778
|
-
//
|
|
779
|
-
//
|
|
780
|
-
//
|
|
781
|
-
//
|
|
782
|
-
|
|
1146
|
+
// 200-with-error-envelope check (op.errorPath) — placement pin: the
|
|
1147
|
+
// very next statement after parseResponse, BEFORE the totalCountPath
|
|
1148
|
+
// extraction and both exhaustion breaks below. An error page often
|
|
1149
|
+
// misses itemsPath entirely, so a check after the breaks never fires
|
|
1150
|
+
// (the walk exits with silent items: []).
|
|
1151
|
+
if (operation.errorPath !== undefined) {
|
|
1152
|
+
checkErrorEnvelope(
|
|
1153
|
+
data,
|
|
1154
|
+
operation.errorPath,
|
|
1155
|
+
redactedPageUrl,
|
|
1156
|
+
opts?.secretValues,
|
|
1157
|
+
);
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
// Extract the server's reported total from the first page that resolves
|
|
1161
|
+
// one — before the empty-page break below, so a zero-result page that
|
|
1162
|
+
// still carries the count (e.g. `total_count: 0`) surfaces it rather
|
|
1163
|
+
// than losing it to the early `break`. Accepts a number directly or a
|
|
1164
|
+
// numeric string (coerced via Number()); a page that misses the path
|
|
1165
|
+
// leaves it undefined and later pages can still supply it.
|
|
783
1166
|
if (serverTotal === undefined && pagCfg.totalCountPath) {
|
|
784
1167
|
const raw = resolveJsonPath(data, pagCfg.totalCountPath);
|
|
785
1168
|
if (typeof raw === "number" && Number.isFinite(raw)) {
|
|
@@ -811,12 +1194,12 @@ export async function paginate(
|
|
|
811
1194
|
? pageItems.slice(0, remaining)
|
|
812
1195
|
: pageItems;
|
|
813
1196
|
for (const item of toProcess) {
|
|
814
|
-
if (transformFn) {
|
|
1197
|
+
if (opts?.transformFn) {
|
|
815
1198
|
try {
|
|
816
1199
|
items.push(
|
|
817
|
-
transformFn(item, {
|
|
1200
|
+
opts.transformFn(item, {
|
|
818
1201
|
operation: operation.name,
|
|
819
|
-
domain: dirName ?? "",
|
|
1202
|
+
domain: opts.dirName ?? "",
|
|
820
1203
|
}),
|
|
821
1204
|
);
|
|
822
1205
|
} catch {
|
|
@@ -841,6 +1224,17 @@ export async function paginate(
|
|
|
841
1224
|
break;
|
|
842
1225
|
}
|
|
843
1226
|
|
|
1227
|
+
// hasMorePath done-flag (style-agnostic).
|
|
1228
|
+
// Sits after the ceiling checks so ceilingHit still wins when both fire
|
|
1229
|
+
// on the same page. The undefined carve-out is fail-open: a missing or
|
|
1230
|
+
// typo'd path never stops the walk (pre-existing exhaustion semantics
|
|
1231
|
+
// apply); a RESOLVED falsy value stops cleanly. Plain truthiness, no
|
|
1232
|
+
// coercion — the string "false" advances by design.
|
|
1233
|
+
if (pagCfg.hasMorePath !== undefined) {
|
|
1234
|
+
const v = resolveJsonPath(data, pagCfg.hasMorePath);
|
|
1235
|
+
if (v !== undefined && !v) break;
|
|
1236
|
+
}
|
|
1237
|
+
|
|
844
1238
|
// Determine next page.
|
|
845
1239
|
const advanced = advancePagination(
|
|
846
1240
|
style,
|
|
@@ -914,13 +1308,20 @@ function advancePagination(
|
|
|
914
1308
|
}
|
|
915
1309
|
|
|
916
1310
|
if (style === "cursor") {
|
|
917
|
-
|
|
1311
|
+
// Numeric cursors coerce to strings (tokenBag-style) BEFORE the
|
|
1312
|
+
// type/falsy check — a numeric 0 must advance like string "0", not die
|
|
1313
|
+
// at !next. nextLink stays string-strict (a numeric "next URL" is
|
|
1314
|
+
// garbage); booleans/objects don't coerce.
|
|
1315
|
+
const raw = resolveJsonPath(data, cfg.cursorPath!);
|
|
1316
|
+
const next = typeof raw === "number" ? String(raw) : raw;
|
|
918
1317
|
if (!next || typeof next !== "string") return null;
|
|
919
1318
|
return { cursor: next };
|
|
920
1319
|
}
|
|
921
1320
|
|
|
922
1321
|
if (style === "resumptionToken") {
|
|
923
|
-
|
|
1322
|
+
// No !next guard here by design — "" and missing are exhaustion.
|
|
1323
|
+
const raw = resolveJsonPath(data, cfg.tokenPath!);
|
|
1324
|
+
const t = typeof raw === "number" ? String(raw) : raw; // coercion, before the check
|
|
924
1325
|
if (typeof t !== "string" || t === "") return null;
|
|
925
1326
|
return { token: t };
|
|
926
1327
|
}
|
|
@@ -935,8 +1336,10 @@ function advancePagination(
|
|
|
935
1336
|
for (const key of cfg.continuationParams ?? []) {
|
|
936
1337
|
const v = resolveJsonPath(data, key);
|
|
937
1338
|
if (v === undefined || v === null) continue;
|
|
938
|
-
|
|
939
|
-
|
|
1339
|
+
// Wire param = wireParamName (last dot segment, bracket dress
|
|
1340
|
+
// stripped — shared with the parser's listStyle collision guard so
|
|
1341
|
+
// the derivation exists once).
|
|
1342
|
+
collected[wireParamName(key)] = String(v);
|
|
940
1343
|
}
|
|
941
1344
|
return Object.keys(collected).length > 0 ? { tokenBag: collected } : null;
|
|
942
1345
|
}
|