pi-lean-host 0.2.0 → 0.3.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 +113 -117
- package/core/api-guide-types.ts +39 -0
- package/core/api-toggle.ts +23 -1
- package/core/auth.ts +42 -5
- package/core/delete-command.ts +190 -0
- package/core/guide-picker.ts +104 -0
- package/core/guide-store.ts +0 -26
- package/core/helpers-command.ts +2 -4
- package/core/helpers.ts +72 -24
- package/core/local-helpers.ts +2 -1
- package/core/parse-api-guide.ts +491 -57
- package/core/path-template.ts +30 -1
- package/core/resolve-op.ts +222 -0
- 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/core/verify-command.ts +399 -0
- package/package.json +15 -1
- package/tools/api-fetch.ts +147 -233
- package/tools/api-guide.ts +35 -46
- package/tools/api-learn.ts +438 -125
- package/tools/api-probe.ts +501 -88
- package/tools/utils.ts +21 -0
package/core/path-template.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* - `extractPathTokens` — pull `{token}` names out of a templated path.
|
|
9
9
|
* - `fillPathTemplate` — substitute `{token}` placeholders from params.
|
|
10
10
|
* - `joinUrl` — join a base host + path + query string into a full URL.
|
|
11
|
+
* - `assertSafeDomain` — reject a domain that could escape the guides dir.
|
|
11
12
|
*/
|
|
12
13
|
|
|
13
14
|
/** Extract `{token}` names from a templated path, in order, deduplicated. */
|
|
@@ -46,5 +47,33 @@ export function joinUrl(baseHost: string, path: string, query: string): string {
|
|
|
46
47
|
const base = baseHost.endsWith("/") ? baseHost : `${baseHost}/`;
|
|
47
48
|
const rel = path.startsWith("/") ? path.slice(1) : path;
|
|
48
49
|
const url = new URL(rel, base).toString();
|
|
49
|
-
|
|
50
|
+
if (!query) return url;
|
|
51
|
+
const sep = url.includes("?") ? "&" : "?";
|
|
52
|
+
return `${url}${sep}${query}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Reject a `domain` that could escape the guides dir via path traversal.
|
|
57
|
+
*
|
|
58
|
+
* Domains are used in `join(guidesDir, domain, ...)` for helper lookups
|
|
59
|
+
* and guide writes. A user-typed `/api helpers ../../foo` or an agent
|
|
60
|
+
* `api-learn({domain: "../x"})` must not read or write outside the
|
|
61
|
+
* guides dir. Returns the domain if safe, throws otherwise.
|
|
62
|
+
*/
|
|
63
|
+
export function assertSafeDomain(domain: string): string {
|
|
64
|
+
// A safe domain is a single path segment: no separators, no NUL,
|
|
65
|
+
// and not "."/".." (self/parent). Anything else is a literal dir name.
|
|
66
|
+
if (
|
|
67
|
+
domain.length === 0 ||
|
|
68
|
+
domain.includes("/") ||
|
|
69
|
+
domain.includes("\\") ||
|
|
70
|
+
domain.includes("\0") ||
|
|
71
|
+
domain === "." ||
|
|
72
|
+
domain === ".."
|
|
73
|
+
) {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`Invalid domain '${domain}': must be a single path segment with no '/', '\\', or '..'.`,
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
return domain;
|
|
50
79
|
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* resolveOpForExecution — the shared guide-resolution → helper-call →
|
|
3
|
+
* transform-load → auth-resolution → executor-dispatch sequence used by both
|
|
4
|
+
* `api-fetch` (single op) and `/api verify` (a loop over every op). One
|
|
5
|
+
* implementation, two real call sites — a duplicated copy would drift and
|
|
6
|
+
* ship a known second bug, so the sequence lives here.
|
|
7
|
+
*
|
|
8
|
+
* The caller owns everything around it: guide/op resolution (api-fetch by
|
|
9
|
+
* op name across guides, verify by declared order), result formatting, and
|
|
10
|
+
* error/skip rendering. This module only turns a (guide, op) into a
|
|
11
|
+
* successful executor result or a structured non-run outcome.
|
|
12
|
+
*
|
|
13
|
+
* Throws `HelperError` / transport errors up to the caller (both call sites
|
|
14
|
+
* catch); returns a non-`ok` result only for the two conditions that are
|
|
15
|
+
* *not* run failures: a session-disabled local helper (skip, not fail) and
|
|
16
|
+
* a fail-closed missing `requires` secret (short-circuit before dispatch).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
restGet,
|
|
21
|
+
paginate,
|
|
22
|
+
type RestGetResult,
|
|
23
|
+
type PaginateResult,
|
|
24
|
+
} from "./helpers.js";
|
|
25
|
+
import { callHelper, loadTransform } from "./local-helpers.js";
|
|
26
|
+
import {
|
|
27
|
+
resolveSecretHeaders,
|
|
28
|
+
resolveSecretQueryParams,
|
|
29
|
+
authStatusLine,
|
|
30
|
+
canonicalStoreDomain,
|
|
31
|
+
type SecretResolution,
|
|
32
|
+
type QuerySecretResolution,
|
|
33
|
+
} from "./auth.js";
|
|
34
|
+
import type { ApiGuide, ExecutorVia, Operation } from "./api-guide-types.js";
|
|
35
|
+
|
|
36
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
37
|
+
// Types
|
|
38
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
39
|
+
|
|
40
|
+
export interface ResolveOpOptions {
|
|
41
|
+
/** User-supplied params (pre-helper) — the role `userParams` plays in api-fetch. */
|
|
42
|
+
userParams?: Record<string, unknown>;
|
|
43
|
+
/** paginate: gather all items up to the guide's ceiling. */
|
|
44
|
+
gatherAll?: boolean;
|
|
45
|
+
/** paginate: bypass the nextLink SSRF guard (test hook only). */
|
|
46
|
+
skipSsrfGuard?: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Store-injected auth opts, forwarded to the executor and reused by the
|
|
50
|
+
* caller for the output-channel audit (secret scrub). */
|
|
51
|
+
interface AuthOpts {
|
|
52
|
+
authHeaders?: Record<string, string>;
|
|
53
|
+
secretHeaderNames?: Set<string>;
|
|
54
|
+
secretValues?: string[];
|
|
55
|
+
secretQueryParams?: Record<string, string>;
|
|
56
|
+
secretQueryParamNames?: Set<string>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type ResolveOpResult =
|
|
60
|
+
| {
|
|
61
|
+
ok: true;
|
|
62
|
+
via: ExecutorVia;
|
|
63
|
+
result: RestGetResult | PaginateResult;
|
|
64
|
+
/** Metadata-only auth footer (names only) — undefined for no-auth guides. */
|
|
65
|
+
authFooter?: string;
|
|
66
|
+
/** Resolved auth opts — for the caller's output-channel audit. */
|
|
67
|
+
authOpts: AuthOpts;
|
|
68
|
+
}
|
|
69
|
+
| {
|
|
70
|
+
ok: false;
|
|
71
|
+
reason: "helper_disabled";
|
|
72
|
+
/** Human-readable reason (the callHelper error message). */
|
|
73
|
+
message: string;
|
|
74
|
+
}
|
|
75
|
+
| {
|
|
76
|
+
ok: false;
|
|
77
|
+
reason: "auth_required_not_provisioned";
|
|
78
|
+
/** The secret names a `requires` block wants but the store lacks. */
|
|
79
|
+
missing: string[];
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
83
|
+
// resolveOpForExecution
|
|
84
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Resolve and execute one operation against its guide.
|
|
88
|
+
*
|
|
89
|
+
* @param guide The matched ApiGuide.
|
|
90
|
+
* @param op The operation to execute.
|
|
91
|
+
* @param helperDirName The guide's directory name — the helper-routing key
|
|
92
|
+
* for `callHelper` / `loadTransform` (diverges from the
|
|
93
|
+
* routing `domain` in the multi-recipe case).
|
|
94
|
+
* @param opts Execution options (user params, gatherAll, …).
|
|
95
|
+
*/
|
|
96
|
+
export async function resolveOpForExecution(
|
|
97
|
+
guide: ApiGuide,
|
|
98
|
+
op: Operation,
|
|
99
|
+
helperDirName: string,
|
|
100
|
+
opts?: ResolveOpOptions,
|
|
101
|
+
): Promise<ResolveOpResult> {
|
|
102
|
+
// The canonical secret-store key: `guide.domains[0]` (the plain browsable
|
|
103
|
+
// domain), independent of the routing `domain` the caller was given.
|
|
104
|
+
const storeDomain = canonicalStoreDomain(guide);
|
|
105
|
+
const userParams = opts?.userParams ?? {};
|
|
106
|
+
|
|
107
|
+
// 1. Pre-call helper (op.helper === true). A session-disabled helper is a
|
|
108
|
+
// skip, not a failure — the op is unverifiable this session, not broken.
|
|
109
|
+
let executeParams = userParams;
|
|
110
|
+
if (op.helper === true) {
|
|
111
|
+
const helperResult = await callHelper(helperDirName, op.name, executeParams);
|
|
112
|
+
if (!helperResult.ok) {
|
|
113
|
+
return { ok: false, reason: "helper_disabled", message: helperResult.error };
|
|
114
|
+
}
|
|
115
|
+
executeParams = helperResult.params;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// 2. Post-response transform (op.transform === true). Loaded once before
|
|
119
|
+
// dispatch; the executor owns the invocation + its try/catch (a throw
|
|
120
|
+
// never escapes — it surfaces as a non-blocking transformWarning).
|
|
121
|
+
const transformFn =
|
|
122
|
+
op.transform === true ? await loadTransform(helperDirName) : null;
|
|
123
|
+
if (op.transform === true && transformFn === null) {
|
|
124
|
+
console.warn(
|
|
125
|
+
`⚠ Transform declared but no helper.ts found for ${helperDirName}.`,
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// 3. Auth resolution (kind: static-key) — resolve store-injected headers
|
|
130
|
+
// AND query params up front so a missing required secret fails closed
|
|
131
|
+
// BEFORE any request. Values never leave this scope — only header/param
|
|
132
|
+
// and secret NAMES ever surface to the caller.
|
|
133
|
+
let headerRes: SecretResolution | undefined;
|
|
134
|
+
let queryRes: QuerySecretResolution | undefined;
|
|
135
|
+
if (guide.auth.kind === "static-key") {
|
|
136
|
+
headerRes = resolveSecretHeaders(guide.auth, storeDomain);
|
|
137
|
+
queryRes = resolveSecretQueryParams(guide.auth, storeDomain);
|
|
138
|
+
const missingRequired = [
|
|
139
|
+
...(headerRes.absentRequired ?? []),
|
|
140
|
+
...(queryRes.absentRequired ?? []),
|
|
141
|
+
];
|
|
142
|
+
if (missingRequired.length > 0) {
|
|
143
|
+
return {
|
|
144
|
+
ok: false,
|
|
145
|
+
reason: "auth_required_not_provisioned",
|
|
146
|
+
missing: missingRequired,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const headerValues = headerRes
|
|
151
|
+
? [...Object.values(headerRes.headers), ...headerRes.rawHeaderValues]
|
|
152
|
+
: [];
|
|
153
|
+
const queryValues = queryRes ? Object.values(queryRes.queryParams) : [];
|
|
154
|
+
const authOpts: AuthOpts =
|
|
155
|
+
headerRes || queryRes
|
|
156
|
+
? {
|
|
157
|
+
...(headerRes
|
|
158
|
+
? {
|
|
159
|
+
authHeaders: headerRes.headers,
|
|
160
|
+
secretHeaderNames: new Set(
|
|
161
|
+
Object.keys(headerRes.headers).map((h) => h.toLowerCase()),
|
|
162
|
+
),
|
|
163
|
+
}
|
|
164
|
+
: {}),
|
|
165
|
+
...(queryRes
|
|
166
|
+
? {
|
|
167
|
+
secretQueryParams: queryRes.queryParams,
|
|
168
|
+
secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
|
|
169
|
+
}
|
|
170
|
+
: {}),
|
|
171
|
+
secretValues: [...headerValues, ...queryValues],
|
|
172
|
+
}
|
|
173
|
+
: {};
|
|
174
|
+
const authFooter = authStatusLine(guide.auth, storeDomain);
|
|
175
|
+
|
|
176
|
+
// 4. Execute via the declared executor.
|
|
177
|
+
if (op.via === "restGet") {
|
|
178
|
+
const result = await restGet(
|
|
179
|
+
guide.apiHost,
|
|
180
|
+
op,
|
|
181
|
+
executeParams,
|
|
182
|
+
guide,
|
|
183
|
+
authOpts,
|
|
184
|
+
transformFn ?? undefined,
|
|
185
|
+
helperDirName,
|
|
186
|
+
);
|
|
187
|
+
return {
|
|
188
|
+
ok: true,
|
|
189
|
+
via: "restGet",
|
|
190
|
+
result,
|
|
191
|
+
...(authFooter ? { authFooter } : {}),
|
|
192
|
+
authOpts,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (op.via === "paginate") {
|
|
197
|
+
const paginateOpts: Parameters<typeof paginate>[4] = {
|
|
198
|
+
...authOpts,
|
|
199
|
+
...(opts?.skipSsrfGuard ? { skipSsrfGuard: true } : {}),
|
|
200
|
+
...(opts?.gatherAll === undefined ? {} : { gatherAll: opts.gatherAll }),
|
|
201
|
+
};
|
|
202
|
+
const result = await paginate(
|
|
203
|
+
guide.apiHost,
|
|
204
|
+
op,
|
|
205
|
+
executeParams,
|
|
206
|
+
guide,
|
|
207
|
+
paginateOpts,
|
|
208
|
+
transformFn ?? undefined,
|
|
209
|
+
helperDirName,
|
|
210
|
+
);
|
|
211
|
+
return {
|
|
212
|
+
ok: true,
|
|
213
|
+
via: "paginate",
|
|
214
|
+
result,
|
|
215
|
+
...(authFooter ? { authFooter } : {}),
|
|
216
|
+
authOpts,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// TypeScript guard — all ExecutorVia values handled above.
|
|
221
|
+
throw new Error(`Unhandled executor '${op.via as string}'.`);
|
|
222
|
+
}
|
package/core/secrets-command.ts
CHANGED
|
@@ -147,6 +147,26 @@ function declaredSecretNames(domain: string): string[] {
|
|
|
147
147
|
return [...names].sort((a, b) => a.localeCompare(b));
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
+
/**
|
|
151
|
+
* The guide-declared header prefix for a secret name, or undefined. When a
|
|
152
|
+
* guide maps a secret to a prefixed header, the store must hold the raw
|
|
153
|
+
* credential (the guide adds the prefix at fetch time) — surface that in the
|
|
154
|
+
* provisioning prompt so the user pastes the raw token, not the prefixed form.
|
|
155
|
+
*/
|
|
156
|
+
function declaredPrefixHint(domain: string, name: string): string | undefined {
|
|
157
|
+
for (const { guide } of findGuidesByDomain(domain)) {
|
|
158
|
+
if (guide.auth.kind !== "static-key") continue;
|
|
159
|
+
for (const [headerName, secretName] of Object.entries(
|
|
160
|
+
guide.auth.secretRefs ?? {},
|
|
161
|
+
)) {
|
|
162
|
+
if (secretName === name && guide.auth.headerPrefixes?.[headerName]) {
|
|
163
|
+
return guide.auth.headerPrefixes[headerName];
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
|
|
150
170
|
// ── Assisted entry: /api secrets <domain> ──────────────────────────
|
|
151
171
|
|
|
152
172
|
async function assistedEntry(
|
|
@@ -213,9 +233,12 @@ async function promptAndStore(
|
|
|
213
233
|
domain: string,
|
|
214
234
|
name: string,
|
|
215
235
|
): Promise<void> {
|
|
236
|
+
const prefix = declaredPrefixHint(domain, name);
|
|
216
237
|
const value = await ctx.ui.input(
|
|
217
|
-
|
|
218
|
-
|
|
238
|
+
prefix
|
|
239
|
+
? `Value for '${domain}'.${name} (raw token — the guide adds \`${prefix}\`)`
|
|
240
|
+
: `Value for '${domain}'.${name}`,
|
|
241
|
+
prefix ? "paste the raw token" : "paste the secret value",
|
|
219
242
|
);
|
|
220
243
|
if (value === undefined) return; // cancelled
|
|
221
244
|
const trimmed = value.trim();
|
package/core/secrets-store.ts
CHANGED
|
@@ -26,7 +26,7 @@ import {
|
|
|
26
26
|
rmSync,
|
|
27
27
|
writeFileSync,
|
|
28
28
|
} from "node:fs";
|
|
29
|
-
import { assertSafeDomain } from "./
|
|
29
|
+
import { assertSafeDomain } from "./path-template.js";
|
|
30
30
|
|
|
31
31
|
/** A secret store: read/write/delete one name, list domain/name indexes. */
|
|
32
32
|
export interface SecretStore {
|
|
@@ -168,3 +168,13 @@ export function listDomains(): string[] {
|
|
|
168
168
|
export function listNames(domain: string): string[] {
|
|
169
169
|
return _store.listNames(domain);
|
|
170
170
|
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Suffix naming the *other* provisioned domains (names only) for a store-miss
|
|
174
|
+
* note — " — provisioned domains: a, b" — or "" when none. Lets a miss tell
|
|
175
|
+
* the authoring agent where the key actually lives without an `ls`.
|
|
176
|
+
*/
|
|
177
|
+
export function provisionedDomainsSuffix(domain: string): string {
|
|
178
|
+
const others = listDomains().filter((d) => d !== domain);
|
|
179
|
+
return others.length > 0 ? ` — provisioned domains: ${others.join(", ")}` : "";
|
|
180
|
+
}
|
package/core/ssrf-guard.ts
CHANGED
|
@@ -29,6 +29,11 @@ const INTERNAL_IP_REGEX =
|
|
|
29
29
|
|
|
30
30
|
// ─── Guard ───────────────────────────────────────────────────────────
|
|
31
31
|
|
|
32
|
+
/**
|
|
33
|
+
* `reason` is hostname-only by design — never embed the full URL here:
|
|
34
|
+
* query secrets live in URLs, and transport surfaces `reason` verbatim
|
|
35
|
+
* (SsrfBlockedError, transport.ts).
|
|
36
|
+
*/
|
|
32
37
|
export function ssrfGuard(
|
|
33
38
|
rawUrl: string,
|
|
34
39
|
): { ok: true } | { ok: false; reason: string } {
|
package/core/transport.ts
CHANGED
|
@@ -65,13 +65,6 @@ export interface FetchOptions {
|
|
|
65
65
|
* private (never cached / served from cache) and redirects are guarded.
|
|
66
66
|
*/
|
|
67
67
|
hasQuerySecret?: boolean;
|
|
68
|
-
/**
|
|
69
|
-
* Names of store-injected query-param secrets in the request URL. Used by
|
|
70
|
-
* `fetchUrl` to redact the URL in any error message it surfaces, so a raw
|
|
71
|
-
* query secret can never leak into agent context via a transport error
|
|
72
|
-
* (output-channel audit).
|
|
73
|
-
*/
|
|
74
|
-
secretQueryParamNames?: Set<string>;
|
|
75
68
|
/** Charset to decode the body with when the response's Content-Type
|
|
76
69
|
* header omits one. Honors a guide's `responseShape.charset` for APIs
|
|
77
70
|
* that serve e.g. ISO-8859-1 bytes without a charset parameter. An
|
|
@@ -440,7 +433,7 @@ export async function fetchUrl(
|
|
|
440
433
|
const reqHeaders: Record<string, string> = { ...opts?.headers };
|
|
441
434
|
if (!reqHeaders["user-agent"]) {
|
|
442
435
|
reqHeaders["user-agent"] =
|
|
443
|
-
"pi-lean-host/0.
|
|
436
|
+
"pi-lean-host/0.3.0 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
|
|
444
437
|
}
|
|
445
438
|
|
|
446
439
|
if (!opts?.fresh && !hasAuth) {
|
|
@@ -452,7 +445,7 @@ export async function fetchUrl(
|
|
|
452
445
|
|
|
453
446
|
const startTime = Date.now();
|
|
454
447
|
|
|
455
|
-
for (let attempt = 0;
|
|
448
|
+
for (let attempt = 0; ; attempt++) {
|
|
456
449
|
const remaining = timeout - (Date.now() - startTime);
|
|
457
450
|
if (remaining <= 0) throw new Error("Request timeout");
|
|
458
451
|
|
|
@@ -543,11 +536,4 @@ export async function fetchUrl(
|
|
|
543
536
|
throw e;
|
|
544
537
|
}
|
|
545
538
|
}
|
|
546
|
-
|
|
547
|
-
// Output-channel audit: never embed the raw request URL in a surfaced
|
|
548
|
-
// message. If a query secret is in play, redact it so the fallthrough
|
|
549
|
-
// (or any future reachable variant) can't leak the key.
|
|
550
|
-
throw new Error(
|
|
551
|
-
`Failed to fetch ${redactSecretParams(url, opts?.secretQueryParamNames)} after ${maxRetries + 1} attempts`,
|
|
552
|
-
);
|
|
553
539
|
}
|