pi-lean-host 0.2.0 → 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/README.md +50 -31
- package/core/api-guide-types.ts +30 -0
- package/core/auth.ts +42 -5
- package/core/guide-store.ts +0 -26
- package/core/helpers.ts +44 -24
- package/core/local-helpers.ts +2 -1
- package/core/parse-api-guide.ts +138 -54
- package/core/path-template.ts +30 -1
- package/core/secrets-command.ts +25 -2
- package/core/secrets-store.ts +11 -1
- package/core/ssrf-guard.ts +5 -0
- package/core/transport.ts +2 -16
- package/package.json +11 -1
- package/tools/api-fetch.ts +14 -20
- package/tools/api-guide.ts +3 -9
- package/tools/api-learn.ts +16 -19
- package/tools/api-probe.ts +254 -62
- package/tools/utils.ts +21 -0
package/README.md
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
> SearXNG search, install
|
|
21
21
|
> [`pi-lean-search`](https://www.npmjs.com/package/pi-lean-search).
|
|
22
22
|
|
|
23
|
-
> ⚠️ **Early release (0.2.
|
|
23
|
+
> ⚠️ **Early release (0.2.1).** The API tools here work today, but this is a
|
|
24
24
|
> development preview. The recipe schema, tool surfaces, and guide format are
|
|
25
25
|
> still settling as we test more APIs to finalize the shape — **future
|
|
26
26
|
> compatibility is not guaranteed** until the package reaches lockstep with
|
|
@@ -127,13 +127,14 @@ demand. A skill is pure text with no in-process eval, whereas a loaded
|
|
|
127
127
|
|------|----------------|---------------|-------------------|-------|
|
|
128
128
|
| Built-in helpers | package source (`core/`) | maintainers | yes | reviewed |
|
|
129
129
|
| Local user helpers | `~/.pi/agent/pi-lean-host/api-guides/<domain>/helper.ts` | you, or the agent in `/api learn` | no | user-owned |
|
|
130
|
-
| Bundled recipes | `api-guides/<domain>/`
|
|
130
|
+
| Bundled recipes | `caritas` repo (`api-guides/<domain>/`) | maintainers | no (reference) | **inert — never auto-executed** |
|
|
131
131
|
|
|
132
132
|
Built-in helpers cover the common 90%. Local user helpers cover the weird 10%
|
|
133
133
|
(computed signatures, strange date transforms, custom auth). Bundled recipes
|
|
134
|
-
are inert reference material
|
|
135
|
-
from the package. You adopt one by
|
|
136
|
-
own directory; only then does it
|
|
134
|
+
are inert reference material in the [`caritas`](https://github.com/coreyryanhanson/caritas)
|
|
135
|
+
repo — the loader never reads `api-guides/` from the package. You adopt one by
|
|
136
|
+
copying the whole domain folder into your own directory; only then does it
|
|
137
|
+
load and execute.
|
|
137
138
|
|
|
138
139
|
---
|
|
139
140
|
|
|
@@ -262,7 +263,11 @@ real transport (same UA, charset, 429-retry, ETag cache as `api-fetch` — the
|
|
|
262
263
|
sanctioned way to reach even WAF'd hosts), summarizes the JSON shape, suggests
|
|
263
264
|
`via` / `itemsPath` / pagination style, echoes a representative record id, and
|
|
264
265
|
emits a **draft YAML operation block** to paste straight into a recipe. On 404
|
|
265
|
-
it
|
|
266
|
+
it walks the `apiHost` version backward (e.g. `/v3` → `/v2` → `/v1`) to recover
|
|
267
|
+
an over-claimed version; a draft carries the version prefix that was actually
|
|
268
|
+
fetched (disable with `walkVersions=false`). A stale version that still
|
|
269
|
+
returns 200 is not detected as old — read the provider's docs to supply the
|
|
270
|
+
newest version up front.
|
|
266
271
|
|
|
267
272
|
`api-probe` only **suggests** — it never writes the guide. The operation must
|
|
268
273
|
still be traceable to your plan source (the API docs or a working curl
|
|
@@ -357,6 +362,7 @@ laws (capped at 1000 by the op override). The `boe-datefmt` helper formats the
|
|
|
357
362
|
| `auth.kind` | guide | `none` | `none` \| `static-key` (store-backed header/query secrets). `oauth2` is a declared-but-unrealized seam (rejected at parse) |
|
|
358
363
|
| `auth.headers` | guide | — | literal extra headers merged into every request (e.g. X-Api-Key: DEMO_KEY) — **literal values only**, never the path for real credentials |
|
|
359
364
|
| `auth.secretRefs` | guide | — | `Record<headerName, secretName>` — store-backed header injection (`static-key`) |
|
|
365
|
+
| `auth.headerPrefixes` | guide | — | `Record<headerName, prefix>` — prefix prepended to a secretRefs header value, e.g. `Authorization: "Bearer "` (store holds the raw credential) |
|
|
360
366
|
| `auth.secretQueryRefs` | guide | — | `Record<paramName, secretName>` — store-backed query-param injection (`static-key`) |
|
|
361
367
|
| `auth.requires` | guide | — | secret names the guide hard-requires; absent → `api-fetch` fails closed before the request |
|
|
362
368
|
| `auth.optional` | guide | — | secret names used if present, skipped if absent (e.g. GitHub rate-limit token) |
|
|
@@ -505,11 +511,11 @@ Authoring is via `api-learn` in learn mode, or hand-editing the file.
|
|
|
505
511
|
## Pagination Styles
|
|
506
512
|
|
|
507
513
|
`paginate` follows the style declared in the recipe. Six styles cover the
|
|
508
|
-
patterns the
|
|
514
|
+
patterns the recipe library (caritas) pressure-tested:
|
|
509
515
|
|
|
510
516
|
| Style | What it sends | Key fields |
|
|
511
517
|
|-------|---------------|------------|
|
|
512
|
-
| `offset-limit` | absolute offset + page size | `pageParam`, `pageSizeParam`, `pageSize`, `itemsPath` |
|
|
518
|
+
| `offset-limit` | absolute offset + page size | `pageParam`, `pageSizeParam`, `pageSize`, `base`, `itemsPath` |
|
|
513
519
|
| `page` | 1-based page number + page size | same fields as `offset-limit` (semantic difference only) |
|
|
514
520
|
| `nextLink` | follows a URL from the response body | `nextLinkPath`, `itemsPath` — the **only** SSRF-guarded path (see [Security](#security--scope)) |
|
|
515
521
|
| `cursor` | echoes an opaque cursor query param | `cursorParam`, `cursorPath`, `itemsPath` |
|
|
@@ -562,9 +568,15 @@ you know you're in disambiguation territory.
|
|
|
562
568
|
|
|
563
569
|
## Bundled Reference Recipes
|
|
564
570
|
|
|
565
|
-
The
|
|
566
|
-
**
|
|
567
|
-
|
|
571
|
+
The comprehensive recipe library lives in the
|
|
572
|
+
[**caritas**](https://github.com/coreyryanhanson/caritas) repo — real,
|
|
573
|
+
verified recipes spanning the no-auth **and keyed** axes, each with a
|
|
574
|
+
per-recipe `verified:`-date provenance and the perpetual drift disclaimer.
|
|
575
|
+
They are inert reference material: nothing executes until you copy a recipe
|
|
576
|
+
into your own `~/.pi/agent/pi-lean-host/api-guides/<domain>/` directory.
|
|
577
|
+
|
|
578
|
+
The domains caritas covers (a discoverability index, may drift from the live
|
|
579
|
+
repo):
|
|
568
580
|
|
|
569
581
|
```
|
|
570
582
|
api.gbif.org api.github.com archive.org archive.org-wayback
|
|
@@ -575,19 +587,15 @@ musicbrainz.org openlibrary.org resources.data.gov servi
|
|
|
575
587
|
web.archive.org www.federalregister.gov www.wikidata.org
|
|
576
588
|
```
|
|
577
589
|
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
required/optional split (see [Authentication & Secrets](#authentication--secrets)).
|
|
590
|
+
Several are **keyed** (`auth.kind: static-key`), the spread that exercises
|
|
591
|
+
header-vs-query refs and the required/optional split (see [Authentication &
|
|
592
|
+
Secrets](#authentication--secrets)).
|
|
582
593
|
|
|
583
|
-
To use them, copy the guides into your own directory from a
|
|
584
|
-
the feature branch ([browse the folder on GitHub](https://github.com/coreyryanhanson/pi-lean-dimension/tree/feat/pi-lean-host-package/packages/pi-lean-host/api-guides)):
|
|
594
|
+
To use them, copy the guides into your own directory from a clone of caritas:
|
|
585
595
|
|
|
586
596
|
```bash
|
|
587
|
-
git clone
|
|
588
|
-
|
|
589
|
-
cp -r /tmp/pi-lean-dimension/packages/pi-lean-host/api-guides/* \
|
|
590
|
-
~/.pi/agent/pi-lean-host/api-guides/
|
|
597
|
+
git clone https://github.com/coreyryanhanson/caritas.git /tmp/caritas
|
|
598
|
+
cp -r /tmp/caritas/api-guides/* ~/.pi/agent/pi-lean-host/api-guides/
|
|
591
599
|
```
|
|
592
600
|
|
|
593
601
|
To grab a single domain instead of all of them, copy just its folder
|
|
@@ -596,11 +604,16 @@ To grab a single domain instead of all of them, copy just its folder
|
|
|
596
604
|
Only then does it load and execute. A recipe may carry
|
|
597
605
|
`operation.helper: true` plus an accompanying `helper.ts` in its domain
|
|
598
606
|
subdir as a worked example — but it stays inert until you copy the folder.
|
|
599
|
-
See
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
607
|
+
See caritas's `CONTRIBUTING.md` for authoring a recipe.
|
|
608
|
+
|
|
609
|
+
### What host ships instead
|
|
610
|
+
|
|
611
|
+
Host itself ships only a **synthetic axis-guide set** under `api-guides/` —
|
|
612
|
+
minimal coverage fixtures (no `verified:` date, no live endpoints) that keep
|
|
613
|
+
every guide-driven framework axis exercised via mocked transport. They are
|
|
614
|
+
framework fixtures for host's own tests, not recipes for you to copy. The
|
|
615
|
+
membership is pinned by `__tests__/axis-coverage.test.ts` (which encodes the
|
|
616
|
+
axis-set audit matrix).
|
|
604
617
|
|
|
605
618
|
---
|
|
606
619
|
|
|
@@ -778,10 +791,18 @@ auth:
|
|
|
778
791
|
requires: [api_key] # absent → api-fetch fails closed
|
|
779
792
|
# secretQueryRefs: { apikey: api_key } # query-param injection (?key=)
|
|
780
793
|
# optional: [api_key] # used if present, skipped if absent
|
|
794
|
+
# headerPrefixes: # headerName → prefix for scheme-style headers
|
|
795
|
+
# Authorization: "Bearer " # (GitHub/GitLab) — the store holds the
|
|
796
|
+
# # RAW token; the guide adds the prefix
|
|
781
797
|
```
|
|
782
798
|
|
|
783
799
|
- **`auth.secretRefs`** — `Record<headerName, secretName>`: inject the store
|
|
784
800
|
value into that request header.
|
|
801
|
+
- **`auth.headerPrefixes`** — `Record<headerName, prefix>`: prepend a scheme
|
|
802
|
+
prefix to the resolved value for that header (e.g. `Authorization: "Bearer "`).
|
|
803
|
+
The store holds the **raw credential**; the guide declares how it is
|
|
804
|
+
presented. Absent = verbatim value. Every key must also be a `secretRefs`
|
|
805
|
+
header (parser-enforced).
|
|
785
806
|
- **`auth.secretQueryRefs`** — `Record<paramName, secretName>`: inject the
|
|
786
807
|
store value as that query param.
|
|
787
808
|
- **`auth.requires`** — names the guide **hard-requires**. If one is absent
|
|
@@ -825,9 +846,9 @@ never the value, so it's safe anywhere it renders.
|
|
|
825
846
|
`api-probe` accepts an inline `auth` block (injection fields only) plus a
|
|
826
847
|
`domain` selector, so you can prove a keyed shape before writing the guide —
|
|
827
848
|
a store miss reports the name and fetches unauthenticated (authoring is
|
|
828
|
-
human-in-the-loop, not fail-closed). One of the
|
|
849
|
+
human-in-the-loop, not fail-closed). One of the keyed recipes in caritas is a
|
|
829
850
|
better starting template than `boe.es` for your first keyed guide — see
|
|
830
|
-
|
|
851
|
+
caritas's `CONTRIBUTING.md`.
|
|
831
852
|
|
|
832
853
|
## Security & Scope
|
|
833
854
|
|
|
@@ -882,8 +903,6 @@ machine; the package does not aim to make that easy.
|
|
|
882
903
|
> [pi-lean-dimension](https://github.com/coreyryanhanson/pi-lean-dimension)
|
|
883
904
|
> web-tools suite. For the security model behind the secrets store (the
|
|
884
905
|
> two-threat model and the output-channel audit), see
|
|
885
|
-
> [Authentication & Secrets](#authentication--secrets).
|
|
886
|
-
> escape-valve policy and the 23-recipe spread, see
|
|
887
|
-
> [`docs/design/api-helper-escape-valve.md`](docs/design/api-helper-escape-valve.md).
|
|
906
|
+
> [Authentication & Secrets](#authentication--secrets).
|
|
888
907
|
>
|
|
889
908
|
> License: AGPL-3.0-only
|
package/core/api-guide-types.ts
CHANGED
|
@@ -19,6 +19,14 @@ import type { Guide } from "./guide-loader.js";
|
|
|
19
19
|
*/
|
|
20
20
|
export const GATHER_ALL_MAX_FALLBACK = 1000;
|
|
21
21
|
|
|
22
|
+
/**
|
|
23
|
+
* The schema version of the guide recipe format. Metadata-only attribution:
|
|
24
|
+
* it is surfaced on the parsed guide but NEVER gates/warns/alters parse
|
|
25
|
+
* (see __tests__/schema-version.test.ts). Absent frontmatter defaults to the
|
|
26
|
+
* semantic 0. Bumped to 1 at lockstep (a label change, not a break).
|
|
27
|
+
*/
|
|
28
|
+
export const GUIDE_SCHEMA_VERSION = 0 as const;
|
|
29
|
+
|
|
22
30
|
/** Auth strategies recognized by the schema (the seam). v1 realizes `none` and `static-key`; `oauth2` is rejected at parse. */
|
|
23
31
|
export const KNOWN_AUTH_KINDS: ReadonlySet<string> = new Set([
|
|
24
32
|
"none",
|
|
@@ -43,6 +51,14 @@ export interface AuthConfig {
|
|
|
43
51
|
* `requires` or `optional` (parser-enforced).
|
|
44
52
|
*/
|
|
45
53
|
secretRefs?: Record<string, string>;
|
|
54
|
+
/**
|
|
55
|
+
* static-key only: maps request header name → prefix string prepended to
|
|
56
|
+
* the stored secret value before it is sent. The store holds the raw
|
|
57
|
+
* credential; the guide declares how it is presented (e.g.
|
|
58
|
+
* `Authorization: "Bearer "`). Absent = verbatim value. Every key must
|
|
59
|
+
* also appear in `secretRefs` (parser-enforced).
|
|
60
|
+
*/
|
|
61
|
+
headerPrefixes?: Record<string, string>;
|
|
46
62
|
/**
|
|
47
63
|
* static-key only: maps query param name → secret store name.
|
|
48
64
|
* Values are injected below the agent-supplied params map at fetch time
|
|
@@ -81,6 +97,14 @@ export interface PaginationConfig {
|
|
|
81
97
|
pageSizeParam?: string;
|
|
82
98
|
/** offset-limit / page: requested page size. */
|
|
83
99
|
pageSize?: number;
|
|
100
|
+
/**
|
|
101
|
+
* offset-limit / page: the seed value for the page param — where this
|
|
102
|
+
* API's index starts (e.g. `base: 1` for 1-based offset APIs). Used only
|
|
103
|
+
* as the pagination seed; the seed precedence is caller value → `base` →
|
|
104
|
+
* the param `default` → the style fallback (0 for offset-limit, 1 for
|
|
105
|
+
* page). Accepted but never read by the non-seeding styles.
|
|
106
|
+
*/
|
|
107
|
+
base?: number;
|
|
84
108
|
/** nextLink: JSON path to the next-page URL. */
|
|
85
109
|
nextLinkPath?: string;
|
|
86
110
|
/** cursor: the cursor query param name. */
|
|
@@ -190,6 +214,12 @@ export interface Operation {
|
|
|
190
214
|
*/
|
|
191
215
|
export interface ApiGuide extends Guide {
|
|
192
216
|
kind: "api";
|
|
217
|
+
/**
|
|
218
|
+
* Recipe schema version (attribution, not enforcement — see
|
|
219
|
+
* GUIDE_SCHEMA_VERSION). Parsed from frontmatter `schemaVersion:`; absent
|
|
220
|
+
* stays `undefined` (semantic default 0). Never gates/warns/alters parse.
|
|
221
|
+
*/
|
|
222
|
+
schemaVersion?: number;
|
|
193
223
|
/** Execution root: scheme + host + base path; version prefix lives here. */
|
|
194
224
|
apiHost: string;
|
|
195
225
|
/** Drift signal; defaulted not enforced. */
|
package/core/auth.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import type { AuthConfig, ApiGuide } from "./api-guide-types.js";
|
|
11
|
-
import { readSecret } from "./secrets-store.js";
|
|
11
|
+
import { readSecret, provisionedDomainsSuffix } from "./secrets-store.js";
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* The canonical secret-store key for a guide: its primary browsable domain.
|
|
@@ -24,8 +24,13 @@ export function canonicalStoreDomain(guide: ApiGuide): string {
|
|
|
24
24
|
|
|
25
25
|
/** Result of resolving a guide's `auth.secretRefs` against the store. */
|
|
26
26
|
export interface SecretResolution {
|
|
27
|
-
/** headerName → resolved value, ready to merge into the request. */
|
|
27
|
+
/** headerName → resolved value (with prefix applied), ready to merge into the request. */
|
|
28
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[];
|
|
29
34
|
/** secret names referenced by `requires` that are absent from the store. */
|
|
30
35
|
absentRequired: string[];
|
|
31
36
|
/** secret names referenced by `optional` that are absent from the store. */
|
|
@@ -38,6 +43,7 @@ export function resolveSecretHeaders(
|
|
|
38
43
|
domain: string,
|
|
39
44
|
): SecretResolution {
|
|
40
45
|
const headers: Record<string, string> = {};
|
|
46
|
+
const rawHeaderValues: string[] = [];
|
|
41
47
|
const absentRequired: string[] = [];
|
|
42
48
|
const absentOptional: string[] = [];
|
|
43
49
|
const requires = auth.requires ?? [];
|
|
@@ -47,10 +53,11 @@ export function resolveSecretHeaders(
|
|
|
47
53
|
if (requires.includes(secretName)) absentRequired.push(secretName);
|
|
48
54
|
else absentOptional.push(secretName);
|
|
49
55
|
} else {
|
|
50
|
-
headers[headerName] = value;
|
|
56
|
+
headers[headerName] = (auth.headerPrefixes?.[headerName] ?? "") + value;
|
|
57
|
+
rawHeaderValues.push(value);
|
|
51
58
|
}
|
|
52
59
|
}
|
|
53
|
-
return { headers, absentRequired, absentOptional };
|
|
60
|
+
return { headers, rawHeaderValues, absentRequired, absentOptional };
|
|
54
61
|
}
|
|
55
62
|
|
|
56
63
|
/** Result of resolving a guide's `auth.secretQueryRefs` against the store. */
|
|
@@ -121,7 +128,8 @@ export function authStatusLine(
|
|
|
121
128
|
if (absentRequired.length > 0) {
|
|
122
129
|
return (
|
|
123
130
|
`🔑 auth: requires ${absentRequired.join(", ")} — not provisioned. ` +
|
|
124
|
-
`Run /api secrets ${domain}.`
|
|
131
|
+
`Run /api secrets ${domain}.` +
|
|
132
|
+
provisionedDomainsSuffix(domain)
|
|
125
133
|
);
|
|
126
134
|
}
|
|
127
135
|
// The optional dimension only exists for optional names actually referenced
|
|
@@ -147,3 +155,32 @@ export function authStatusLine(
|
|
|
147
155
|
}
|
|
148
156
|
return "🔑 auth: ok";
|
|
149
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
|
+
}
|
package/core/guide-store.ts
CHANGED
|
@@ -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,15 +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 { scrubSecretValues } from "./auth.js";
|
|
24
25
|
import {
|
|
25
26
|
fetchUrl,
|
|
26
27
|
redactSecretParams,
|
|
27
28
|
type FetchOptions,
|
|
28
29
|
} 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 };
|
|
33
30
|
import { fillPathTemplate, joinUrl } from "./path-template.js";
|
|
34
31
|
import type { TransformFn } from "./local-helpers.js"; // type-only — no runtime import (flat dependency direction)
|
|
35
32
|
import type {
|
|
@@ -324,8 +321,7 @@ function buildUrl(
|
|
|
324
321
|
* This dispatch is a deliberate seam, not dead code: keeping the field +
|
|
325
322
|
* dispatch now makes the future keyed-auth build additive (a new `kind`
|
|
326
323
|
* behind this same `if`/`throw`) rather than a retrofit of every `restGet`/
|
|
327
|
-
* `paginate` call site and the guide schema.
|
|
328
|
-
* `docs/design/api-secrets-roadmap.md` for the build-out plan.
|
|
324
|
+
* `paginate` call site and the guide schema.
|
|
329
325
|
*/
|
|
330
326
|
function checkAuth(auth: ApiGuide["auth"]): void {
|
|
331
327
|
const kind = auth.kind;
|
|
@@ -354,7 +350,6 @@ function fetchWithOpts(
|
|
|
354
350
|
fallbackCharset?: string,
|
|
355
351
|
secretHeaderNames?: Set<string>,
|
|
356
352
|
hasQuerySecret?: boolean,
|
|
357
|
-
secretQueryParamNames?: Set<string>,
|
|
358
353
|
): ReturnType<typeof fetchUrl> {
|
|
359
354
|
const opts: FetchOptions = { headers: { accept, ...extraHeaders } };
|
|
360
355
|
if (fresh !== undefined) opts.fresh = fresh;
|
|
@@ -362,7 +357,6 @@ function fetchWithOpts(
|
|
|
362
357
|
if (fallbackCharset) opts.fallbackCharset = fallbackCharset;
|
|
363
358
|
if (secretHeaderNames) opts.secretHeaderNames = secretHeaderNames;
|
|
364
359
|
if (hasQuerySecret) opts.hasQuerySecret = true;
|
|
365
|
-
if (secretQueryParamNames) opts.secretQueryParamNames = secretQueryParamNames;
|
|
366
360
|
return fetchUrl(url, opts);
|
|
367
361
|
}
|
|
368
362
|
|
|
@@ -397,11 +391,7 @@ function checkResponseStatus(
|
|
|
397
391
|
// Output-channel audit: scrub known store-injected secret values from the
|
|
398
392
|
// error excerpt so a 401 body echoing an auth header can't leak the key
|
|
399
393
|
// into agent context.
|
|
400
|
-
|
|
401
|
-
for (const v of secretValues) {
|
|
402
|
-
if (v && v.length > 0) message = message.split(v).join("***");
|
|
403
|
-
}
|
|
404
|
-
}
|
|
394
|
+
message = scrubSecretValues(message, secretValues);
|
|
405
395
|
|
|
406
396
|
throw new HelperError(
|
|
407
397
|
"response",
|
|
@@ -498,7 +488,6 @@ export async function restGet(
|
|
|
498
488
|
shape.charset,
|
|
499
489
|
opts?.secretHeaderNames,
|
|
500
490
|
hasQuerySecret,
|
|
501
|
-
opts?.secretQueryParamNames,
|
|
502
491
|
);
|
|
503
492
|
|
|
504
493
|
// 7. Check HTTP status before attempting to parse the body.
|
|
@@ -627,14 +616,16 @@ export async function paginate(
|
|
|
627
616
|
|
|
628
617
|
// Seed offset/page params.
|
|
629
618
|
if (style === "offset-limit" || style === "page") {
|
|
630
|
-
// Caller value, else
|
|
631
|
-
//
|
|
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
|
|
632
622
|
// offsets start at 0) and 1 for page (nearly all page-indexed APIs are
|
|
633
623
|
// 1-based; a rare 0-based page API overrides with
|
|
634
|
-
// `params: { page: { default: 0 } }`).
|
|
624
|
+
// `base: 0` or `params: { page: { default: 0 } }`).
|
|
635
625
|
const fallback = style === "page" ? 1 : 0;
|
|
636
626
|
const rawPage =
|
|
637
627
|
params[pagCfg.pageParam!] ??
|
|
628
|
+
pagCfg.base ??
|
|
638
629
|
operation.params[pagCfg.pageParam!]?.default ??
|
|
639
630
|
fallback;
|
|
640
631
|
page = typeof rawPage === "number" ? rawPage : parseInt(String(rawPage), 10);
|
|
@@ -645,6 +636,23 @@ export async function paginate(
|
|
|
645
636
|
// Agent-supplied only (secret param names excluded, incl. passthrough).
|
|
646
637
|
const secretParamNames = opts?.secretQueryParamNames ?? new Set<string>();
|
|
647
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
|
+
}
|
|
648
656
|
// Secret query params injected below the agent map on every page's fetch URL.
|
|
649
657
|
const secretParams = opts?.secretQueryParams ?? {};
|
|
650
658
|
const hasQuerySecret = Object.keys(secretParams).length > 0;
|
|
@@ -659,8 +667,9 @@ export async function paginate(
|
|
|
659
667
|
|
|
660
668
|
if (style === "offset-limit" || style === "page") {
|
|
661
669
|
pageParams[pagCfg.pageParam!] = String(page ?? 0);
|
|
670
|
+
// effectivePageSize is always resolved (a number) in this branch.
|
|
662
671
|
if (pagCfg.pageSizeParam) {
|
|
663
|
-
pageParams[pagCfg.pageSizeParam] = String(
|
|
672
|
+
pageParams[pagCfg.pageSizeParam] = String(effectivePageSize);
|
|
664
673
|
}
|
|
665
674
|
} else if (style === "cursor" && cursor !== undefined) {
|
|
666
675
|
pageParams[pagCfg.cursorParam!] = cursor;
|
|
@@ -724,7 +733,6 @@ export async function paginate(
|
|
|
724
733
|
shape.charset,
|
|
725
734
|
opts?.secretHeaderNames,
|
|
726
735
|
hasQuerySecret,
|
|
727
|
-
opts?.secretQueryParamNames,
|
|
728
736
|
);
|
|
729
737
|
|
|
730
738
|
// Check HTTP status before attempting to parse. Secret values scrubbed
|
|
@@ -806,7 +814,13 @@ export async function paginate(
|
|
|
806
814
|
}
|
|
807
815
|
|
|
808
816
|
// Determine next page.
|
|
809
|
-
const advanced = advancePagination(
|
|
817
|
+
const advanced = advancePagination(
|
|
818
|
+
style,
|
|
819
|
+
pagCfg,
|
|
820
|
+
data,
|
|
821
|
+
page,
|
|
822
|
+
effectivePageSize,
|
|
823
|
+
);
|
|
810
824
|
|
|
811
825
|
if (!advanced) break;
|
|
812
826
|
|
|
@@ -846,13 +860,19 @@ function advancePagination(
|
|
|
846
860
|
cfg: NonNullable<Operation["pagination"]>,
|
|
847
861
|
data: unknown,
|
|
848
862
|
prevPage?: number,
|
|
863
|
+
effectivePageSize?: number,
|
|
849
864
|
): PaginationState | null {
|
|
850
865
|
if (style === "offset-limit") {
|
|
851
866
|
// Row-offset semantics: the API skips `offset` items, so the next page
|
|
852
|
-
// must advance by the page size
|
|
853
|
-
//
|
|
854
|
-
//
|
|
855
|
-
|
|
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
|
+
};
|
|
856
876
|
}
|
|
857
877
|
|
|
858
878
|
if (style === "page") {
|
package/core/local-helpers.ts
CHANGED
|
@@ -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
|
|
31
|
+
import { getUserGuidesDir } from "./guide-store.js";
|
|
32
|
+
import { assertSafeDomain } from "./path-template.js";
|
|
32
33
|
|
|
33
34
|
// ═══════════════════════════════════════════════════════════════════
|
|
34
35
|
// Session-level state
|