pi-lean-host 0.0.1 → 0.1.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 +777 -30
- package/core/api-guide-types.ts +244 -0
- package/core/api-toggle.ts +313 -0
- package/core/guide-loader.ts +80 -0
- package/core/guide-store.ts +125 -0
- package/core/helpers-command.ts +110 -0
- package/core/helpers.ts +801 -0
- package/core/local-helpers.ts +246 -0
- package/core/parse-api-guide.ts +1218 -0
- package/core/path-template.ts +50 -0
- package/core/portal-projection.ts +69 -0
- package/core/response-spill.ts +185 -0
- package/core/ssrf-guard.ts +99 -0
- package/core/transport.ts +451 -0
- package/core/verify-ship-manifest.ts +118 -0
- package/index.ts +46 -0
- package/package.json +42 -13
- package/tools/api-fetch.ts +578 -0
- package/tools/api-guide.ts +320 -0
- package/tools/api-learn.ts +348 -0
- package/tools/api-probe.ts +500 -0
- package/tools/index.ts +7 -0
- package/tools/utils.ts +34 -0
- package/AGENTS.md +0 -22
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP transport layer — undici Agent with caching and retry.
|
|
3
|
+
*
|
|
4
|
+
* Provides `fetchUrl()` with:
|
|
5
|
+
* - ETag-based conditional requests (304 → cached body)
|
|
6
|
+
* - Cache-Control `max-age` TTL
|
|
7
|
+
* - Retry-on-429 with exponential backoff + `Retry-After` support
|
|
8
|
+
* - Configurable timeout
|
|
9
|
+
* - Automatic charset decoding from Content-Type
|
|
10
|
+
*
|
|
11
|
+
* Caching is per-URL, module-level (in-memory map). The cache is
|
|
12
|
+
* transparent to callers; each URL is cached independently.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { request, Agent, interceptors, type Dispatcher } from "undici";
|
|
16
|
+
import { ssrfGuard } from "./ssrf-guard.js";
|
|
17
|
+
|
|
18
|
+
// ponytail: module-level composed agents; closed only on process exit.
|
|
19
|
+
// Add a close() in session_shutdown if leak-detection ever flags it.
|
|
20
|
+
|
|
21
|
+
/** Auto-follows up to 5 redirects. Used when redirect targets are trusted
|
|
22
|
+
* (agent-supplied URLs — the agent has bash, so guarding them is theater). */
|
|
23
|
+
const redirectAgent = new Agent().compose(
|
|
24
|
+
interceptors.redirect({ maxRedirections: 5 }),
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
/** No auto-redirect. Used with `guardRedirects` so each redirect target is
|
|
28
|
+
* SSRF-checked before it is followed. See fetchUrl for the manual loop. */
|
|
29
|
+
const noRedirectAgent = new Agent();
|
|
30
|
+
|
|
31
|
+
const MAX_REDIRECTS = 5;
|
|
32
|
+
|
|
33
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
34
|
+
// Types
|
|
35
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
36
|
+
|
|
37
|
+
export interface FetchOptions {
|
|
38
|
+
/** Request timeout in ms (default: 30_000). */
|
|
39
|
+
timeout?: number;
|
|
40
|
+
/** Additional request headers. */
|
|
41
|
+
headers?: Record<string, string>;
|
|
42
|
+
/** Max retries on 429 (default: 2). */
|
|
43
|
+
maxRetries?: number;
|
|
44
|
+
/** Skip cache (force fresh fetch). */
|
|
45
|
+
fresh?: boolean;
|
|
46
|
+
/** SSRF-check each redirect target before following it. Use only for
|
|
47
|
+
* server-supplied URLs (paginate nextLink) — a malicious API can 302
|
|
48
|
+
* to an internal host, and when auth headers ship the Authorization
|
|
49
|
+
* header would attach to the redirect. Agent-supplied URLs don't need
|
|
50
|
+
* this (the agent already has bash). */
|
|
51
|
+
guardRedirects?: boolean;
|
|
52
|
+
/** Charset to decode the body with when the response's Content-Type
|
|
53
|
+
* header omits one. Honors a guide's `responseShape.charset` for APIs
|
|
54
|
+
* that serve e.g. ISO-8859-1 bytes without a charset parameter. An
|
|
55
|
+
* explicit header charset always takes precedence. */
|
|
56
|
+
fallbackCharset?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface FetchResult {
|
|
60
|
+
status: number;
|
|
61
|
+
headers: Record<string, string>;
|
|
62
|
+
body: string;
|
|
63
|
+
/** True when the result came from cache (no network request). */
|
|
64
|
+
cached: boolean;
|
|
65
|
+
/** Final URL after redirects — present only when at least one hop occurred. */
|
|
66
|
+
finalUrl?: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
70
|
+
// Cache
|
|
71
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
72
|
+
|
|
73
|
+
interface CacheEntry {
|
|
74
|
+
body: string;
|
|
75
|
+
/** ETag for conditional requests; absent when the upstream didn't send one. */
|
|
76
|
+
etag?: string;
|
|
77
|
+
expiresAt: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const DEFAULT_TIMEOUT = 30_000;
|
|
81
|
+
const DEFAULT_MAX_RETRIES = 2;
|
|
82
|
+
const DEFAULT_TTL_MS = 60_000; // 60s fallback when no Cache-Control
|
|
83
|
+
const MAX_CACHE_ENTRIES = 100; // ponytail: hard cap; evict soonest-expiring when exceeded
|
|
84
|
+
const MAX_BODY_BYTES = 10 * 1024 * 1024; // 10 MB ceiling on a single response body
|
|
85
|
+
|
|
86
|
+
/** Module-level cache: cache-key → CacheEntry. */
|
|
87
|
+
const cache = new Map<string, CacheEntry>();
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Drop expired entries, then — if still over the cap — evict the
|
|
91
|
+
* soonest-expiring entries. Called before every `cache.set`.
|
|
92
|
+
*/
|
|
93
|
+
function evictCacheIfNeeded(): void {
|
|
94
|
+
if (cache.size < MAX_CACHE_ENTRIES) return;
|
|
95
|
+
const now = Date.now();
|
|
96
|
+
for (const [k, e] of cache) {
|
|
97
|
+
if (e.expiresAt <= now) cache.delete(k);
|
|
98
|
+
}
|
|
99
|
+
if (cache.size >= MAX_CACHE_ENTRIES) {
|
|
100
|
+
const sorted = [...cache.entries()].sort(
|
|
101
|
+
(a, b) => a[1].expiresAt - b[1].expiresAt,
|
|
102
|
+
);
|
|
103
|
+
while (cache.size >= MAX_CACHE_ENTRIES && sorted.length > 0) {
|
|
104
|
+
const next = sorted.shift();
|
|
105
|
+
if (next) cache.delete(next[0]);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
111
|
+
// Internal helpers
|
|
112
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Produce a cache key from URL and optional Accept header.
|
|
116
|
+
*
|
|
117
|
+
* Two requests for the same URL with different Accept values are cached
|
|
118
|
+
* separately so that content-negotiated responses don't collide.
|
|
119
|
+
* When no Accept header is present the plain URL is used as the key.
|
|
120
|
+
*/
|
|
121
|
+
function cacheKey(url: string, opts?: FetchOptions): string {
|
|
122
|
+
const accept = opts?.headers?.accept;
|
|
123
|
+
const cs = opts?.fallbackCharset ?? "";
|
|
124
|
+
const suffix =
|
|
125
|
+
(accept ? `\x00accept=${accept}` : "") + (cs ? `\x00cs=${cs}` : "");
|
|
126
|
+
return suffix ? `${url}${suffix}` : url;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function parseHeaders(
|
|
130
|
+
hdrs: Dispatcher.ResponseData["headers"],
|
|
131
|
+
): Record<string, string> {
|
|
132
|
+
const out: Record<string, string> = {};
|
|
133
|
+
if (hdrs && typeof hdrs === "object") {
|
|
134
|
+
// undici returns headers as an object with lowercased keys.
|
|
135
|
+
for (const [key, val] of Object.entries(hdrs)) {
|
|
136
|
+
if (typeof val === "string") {
|
|
137
|
+
out[key.toLowerCase()] = val;
|
|
138
|
+
} else if (Array.isArray(val)) {
|
|
139
|
+
// Repeated headers arrive as string[] — join like raw form.
|
|
140
|
+
out[key.toLowerCase()] = val.join(", ");
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function collectBody(
|
|
148
|
+
body: Dispatcher.ResponseData["body"],
|
|
149
|
+
): Promise<Buffer> {
|
|
150
|
+
const chunks: Buffer[] = [];
|
|
151
|
+
let total = 0;
|
|
152
|
+
for await (const chunk of body) {
|
|
153
|
+
total += chunk.length;
|
|
154
|
+
if (total > MAX_BODY_BYTES) {
|
|
155
|
+
const err = new Error(`Response body exceeded ${MAX_BODY_BYTES} bytes`);
|
|
156
|
+
err.name = "BodyTooLargeError"; // checked by fetchUrl retry logic
|
|
157
|
+
throw err;
|
|
158
|
+
}
|
|
159
|
+
chunks.push(Buffer.from(chunk));
|
|
160
|
+
}
|
|
161
|
+
return Buffer.concat(chunks);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function decodeBuffer(buf: Buffer, charset: string): string {
|
|
165
|
+
const cs = charset.toLowerCase().replace(/[^a-z0-9_-]/g, "");
|
|
166
|
+
if (cs === "utf-8" || cs === "utf8" || cs === "") {
|
|
167
|
+
return buf.toString("utf-8");
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
const decoder = new TextDecoder(cs);
|
|
171
|
+
return decoder.decode(buf);
|
|
172
|
+
} catch {
|
|
173
|
+
// Fallback to utf-8 if TextDecoder doesn't recognise the charset.
|
|
174
|
+
return buf.toString("utf-8");
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function parseMaxAge(headers: Record<string, string>): number | null {
|
|
179
|
+
const cc = headers["cache-control"];
|
|
180
|
+
if (!cc) return null;
|
|
181
|
+
const m = cc.match(/max-age=(\d+)/i);
|
|
182
|
+
return m ? parseInt(m[1]!, 10) * 1000 : null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Compute the delay before a retry. Prefers Retry-After: delay-seconds;
|
|
187
|
+
* falls back to parsing an HTTP-date form. If the date is in the past
|
|
188
|
+
* (clock skew / already-expired) or absent, uses exponential backoff —
|
|
189
|
+
* never a negative or zero delay.
|
|
190
|
+
*/
|
|
191
|
+
export function waitForRetry(
|
|
192
|
+
headers: Record<string, string>,
|
|
193
|
+
attempt: number,
|
|
194
|
+
): number {
|
|
195
|
+
const raw = headers["retry-after"];
|
|
196
|
+
if (raw) {
|
|
197
|
+
const secs = parseInt(raw, 10);
|
|
198
|
+
if (!Number.isNaN(secs) && secs > 0) return secs * 1000;
|
|
199
|
+
const dateMs = Date.parse(raw);
|
|
200
|
+
if (!Number.isNaN(dateMs)) {
|
|
201
|
+
const delta = dateMs - Date.now();
|
|
202
|
+
if (delta > 0) return delta;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
// Exponential backoff: 1s, 2s, 4s, …
|
|
206
|
+
return Math.min(1000 * 2 ** attempt, 30_000);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* One GET request with its own abort timer. Returns status, parsed headers,
|
|
211
|
+
* and the raw collected body. Redirects are NOT followed here — the caller
|
|
212
|
+
* decides whether to follow and guard them.
|
|
213
|
+
*/
|
|
214
|
+
async function singleGet(
|
|
215
|
+
url: string,
|
|
216
|
+
reqHeaders: Record<string, string>,
|
|
217
|
+
timeoutMs: number,
|
|
218
|
+
dispatcher: Dispatcher,
|
|
219
|
+
): Promise<{
|
|
220
|
+
status: number;
|
|
221
|
+
headers: Record<string, string>;
|
|
222
|
+
rawBody: Buffer;
|
|
223
|
+
finalUrl: string;
|
|
224
|
+
}> {
|
|
225
|
+
if (timeoutMs <= 0) throw new Error("Request timeout");
|
|
226
|
+
const ac = new AbortController();
|
|
227
|
+
const timer = setTimeout(
|
|
228
|
+
() => ac.abort(new Error("Request timeout")),
|
|
229
|
+
timeoutMs,
|
|
230
|
+
);
|
|
231
|
+
try {
|
|
232
|
+
const resp = await request(url, {
|
|
233
|
+
method: "GET",
|
|
234
|
+
headers: reqHeaders,
|
|
235
|
+
signal: ac.signal,
|
|
236
|
+
dispatcher,
|
|
237
|
+
});
|
|
238
|
+
// The redirect interceptor records the hop chain in context.history;
|
|
239
|
+
// its last entry is where the response actually came from. No history
|
|
240
|
+
// (no interceptor / no redirect) means the URL is unchanged.
|
|
241
|
+
const history = (resp.context as { history?: URL[] } | null)?.history;
|
|
242
|
+
return {
|
|
243
|
+
status: resp.statusCode,
|
|
244
|
+
headers: parseHeaders(resp.headers),
|
|
245
|
+
rawBody: await collectBody(resp.body),
|
|
246
|
+
finalUrl: history?.at(-1) ? String(history.at(-1)) : url,
|
|
247
|
+
};
|
|
248
|
+
} finally {
|
|
249
|
+
clearTimeout(timer);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Follow redirects manually, SSRF-checking each target. Used only for
|
|
255
|
+
* server-supplied URLs (paginate nextLink). GET-only, so method is
|
|
256
|
+
* preserved across 301/302/303/307/308 trivially. Returns the final
|
|
257
|
+
* response; a redirect to a blocked host throws before it is fetched.
|
|
258
|
+
*/
|
|
259
|
+
async function getWithGuardedRedirects(
|
|
260
|
+
url: string,
|
|
261
|
+
reqHeaders: Record<string, string>,
|
|
262
|
+
startTime: number,
|
|
263
|
+
timeoutMs: number,
|
|
264
|
+
): Promise<{
|
|
265
|
+
status: number;
|
|
266
|
+
headers: Record<string, string>;
|
|
267
|
+
rawBody: Buffer;
|
|
268
|
+
finalUrl: string;
|
|
269
|
+
}> {
|
|
270
|
+
let current = url;
|
|
271
|
+
for (let hops = 0; hops <= MAX_REDIRECTS; hops++) {
|
|
272
|
+
const remaining = timeoutMs - (Date.now() - startTime);
|
|
273
|
+
const res = await singleGet(
|
|
274
|
+
current,
|
|
275
|
+
reqHeaders,
|
|
276
|
+
remaining,
|
|
277
|
+
noRedirectAgent,
|
|
278
|
+
);
|
|
279
|
+
const isRedirect =
|
|
280
|
+
res.status >= 300 && res.status < 400 && res.status !== 304;
|
|
281
|
+
if (!isRedirect || hops === MAX_REDIRECTS) return res;
|
|
282
|
+
const loc = res.headers["location"];
|
|
283
|
+
if (!loc) return res; // redirect with no Location — return as-is
|
|
284
|
+
const next = new URL(loc, current).toString();
|
|
285
|
+
const guard = ssrfGuard(next);
|
|
286
|
+
if (!guard.ok) {
|
|
287
|
+
// Security-control failure is not transient — don't retry.
|
|
288
|
+
const err = new Error(`Redirect to blocked host: ${guard.reason}`);
|
|
289
|
+
err.name = "SsrfBlockedError";
|
|
290
|
+
throw err;
|
|
291
|
+
}
|
|
292
|
+
current = next;
|
|
293
|
+
}
|
|
294
|
+
// Unreachable: the loop returns on the MAX_REDIRECTS hop.
|
|
295
|
+
throw new Error("Too many redirects");
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
299
|
+
// Public API
|
|
300
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Fetch a URL with caching and retry-on-429.
|
|
304
|
+
*
|
|
305
|
+
* Cache behaviour:
|
|
306
|
+
* - URLs are cached in a module-level `Map<string, CacheEntry>`.
|
|
307
|
+
* - TTL from `Cache-Control: max-age=N` or the `DEFAULT_TTL_MS` fallback.
|
|
308
|
+
* - When a cached entry has an `etag`, the conditional `If-None-Match`
|
|
309
|
+
* header is sent and a 304 refreshes the cached body's expiry.
|
|
310
|
+
* - `opts.fresh = true` skips the cache read and bypasses sending
|
|
311
|
+
* `If-None-Match` (server returns full response).
|
|
312
|
+
* - Requests carrying caller-specific headers (anything besides Accept,
|
|
313
|
+
* e.g. API keys) are never cached or served from cache — the response
|
|
314
|
+
* is private to that caller.
|
|
315
|
+
*
|
|
316
|
+
* Retry behaviour:
|
|
317
|
+
* - 429 responses are retried up to `opts.maxRetries` times.
|
|
318
|
+
* - Backoff: if `Retry-After` is present, wait that many seconds;
|
|
319
|
+
* otherwise exponential backoff (1s, 2s, 4s, capped at 30s).
|
|
320
|
+
* - Other 4xx/5xx status codes are returned as-is without retry.
|
|
321
|
+
*
|
|
322
|
+
* Network errors (DNS, connection refused, timeout) are thrown.
|
|
323
|
+
*/
|
|
324
|
+
export async function fetchUrl(
|
|
325
|
+
url: string,
|
|
326
|
+
opts?: FetchOptions,
|
|
327
|
+
): Promise<FetchResult> {
|
|
328
|
+
const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;
|
|
329
|
+
const maxRetries = opts?.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
330
|
+
|
|
331
|
+
// Responses to requests carrying caller-specific headers (auth keys,
|
|
332
|
+
// tokens, …) are private to that caller — never cache or reuse them.
|
|
333
|
+
// Only the Accept header (content negotiation) is cache-shareable, and
|
|
334
|
+
// it's already part of the cache key. Without this gate, the same URL
|
|
335
|
+
// fetched with two different auth headers would collide on one cache
|
|
336
|
+
// entry and the second caller would get the first caller's response.
|
|
337
|
+
const hasAuthHeaders =
|
|
338
|
+
!!opts?.headers &&
|
|
339
|
+
Object.keys(opts.headers).some((h) => h.toLowerCase() !== "accept");
|
|
340
|
+
|
|
341
|
+
// ── cache hit ───────────────────────────────────────────────
|
|
342
|
+
const key = cacheKey(url, opts);
|
|
343
|
+
if (!opts?.fresh && !hasAuthHeaders) {
|
|
344
|
+
const entry = cache.get(key);
|
|
345
|
+
if (entry && Date.now() < entry.expiresAt) {
|
|
346
|
+
return { status: 200, headers: {}, body: entry.body, cached: true };
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// ── request headers ─────────────────────────────────────────
|
|
351
|
+
const reqHeaders: Record<string, string> = { ...opts?.headers };
|
|
352
|
+
if (!reqHeaders["user-agent"]) {
|
|
353
|
+
reqHeaders["user-agent"] =
|
|
354
|
+
"pi-lean-host/0.1.0 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
if (!opts?.fresh && !hasAuthHeaders) {
|
|
358
|
+
const entry = cache.get(key);
|
|
359
|
+
if (entry?.etag) {
|
|
360
|
+
reqHeaders["If-None-Match"] = entry.etag;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const startTime = Date.now();
|
|
365
|
+
|
|
366
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
367
|
+
const remaining = timeout - (Date.now() - startTime);
|
|
368
|
+
if (remaining <= 0) throw new Error("Request timeout");
|
|
369
|
+
|
|
370
|
+
try {
|
|
371
|
+
// When guardRedirects is set, follow redirects manually and SSRF-
|
|
372
|
+
// check each target (server-supplied URLs only). Otherwise let
|
|
373
|
+
// undici auto-follow up to 5 redirects.
|
|
374
|
+
const {
|
|
375
|
+
status,
|
|
376
|
+
headers: respHeaders,
|
|
377
|
+
rawBody,
|
|
378
|
+
finalUrl,
|
|
379
|
+
} = opts?.guardRedirects
|
|
380
|
+
? await getWithGuardedRedirects(url, reqHeaders, startTime, timeout)
|
|
381
|
+
: await singleGet(url, reqHeaders, remaining, redirectAgent);
|
|
382
|
+
|
|
383
|
+
// ── 304 Not Modified ────────────────────────────────
|
|
384
|
+
if (status === 304) {
|
|
385
|
+
const entry = cache.get(key);
|
|
386
|
+
if (entry) {
|
|
387
|
+
const maxAge = parseMaxAge(respHeaders) ?? DEFAULT_TTL_MS;
|
|
388
|
+
entry.expiresAt = Date.now() + maxAge;
|
|
389
|
+
// 304 refreshes an existing key — no growth, but cap-check is cheap.
|
|
390
|
+
cache.set(key, entry);
|
|
391
|
+
return {
|
|
392
|
+
status: 200,
|
|
393
|
+
headers: respHeaders,
|
|
394
|
+
body: entry.body,
|
|
395
|
+
cached: true,
|
|
396
|
+
...(finalUrl !== url ? { finalUrl } : {}),
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
// No cached entry → fall through to process body.
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// ── 429 Too Many Requests ───────────────────────────
|
|
403
|
+
if (status === 429 && attempt < maxRetries) {
|
|
404
|
+
const delay = waitForRetry(respHeaders, attempt);
|
|
405
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
406
|
+
continue; // retry
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// ── decode & cache (2xx only) ───────────────────────
|
|
410
|
+
const contentType = respHeaders["content-type"] ?? "";
|
|
411
|
+
const charsetMatch = contentType.match(/charset\s*=\s*([^\s;]+)/i);
|
|
412
|
+
const charset = charsetMatch?.[1] ?? opts?.fallbackCharset ?? "utf-8";
|
|
413
|
+
const body = decodeBuffer(rawBody, charset);
|
|
414
|
+
|
|
415
|
+
if (status >= 200 && status < 300 && !hasAuthHeaders) {
|
|
416
|
+
const maxAge = parseMaxAge(respHeaders) ?? DEFAULT_TTL_MS;
|
|
417
|
+
const etag = respHeaders["etag"];
|
|
418
|
+
|
|
419
|
+
const entry: CacheEntry = { body, expiresAt: Date.now() + maxAge };
|
|
420
|
+
if (etag) entry.etag = etag;
|
|
421
|
+
evictCacheIfNeeded();
|
|
422
|
+
cache.set(key, entry);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
return {
|
|
426
|
+
status,
|
|
427
|
+
headers: respHeaders,
|
|
428
|
+
body,
|
|
429
|
+
cached: false,
|
|
430
|
+
...(finalUrl !== url ? { finalUrl } : {}),
|
|
431
|
+
};
|
|
432
|
+
} catch (err) {
|
|
433
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
434
|
+
// Don't retry on timeout/abort, oversized bodies, or SSRF
|
|
435
|
+
// blocks — none are transient.
|
|
436
|
+
const transient =
|
|
437
|
+
e.name !== "AbortError" &&
|
|
438
|
+
e.name !== "BodyTooLargeError" &&
|
|
439
|
+
e.name !== "SsrfBlockedError" &&
|
|
440
|
+
(e as NodeJS.ErrnoException).code !== "UND_ERR_ABORTED";
|
|
441
|
+
if (attempt < maxRetries && transient) {
|
|
442
|
+
const delay = Math.min(1000 * 2 ** attempt, 30_000);
|
|
443
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
throw e;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
throw new Error(`Failed to fetch ${url} after ${maxRetries + 1} attempts`);
|
|
451
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ship-manifest verification helper (vendored from pi-lean-portal).
|
|
3
|
+
*
|
|
4
|
+
* Walks a package directory for production `.ts` files and compares them to
|
|
5
|
+
* the `files` array in `package.json`. Used by `ship-manifest.test.ts` to
|
|
6
|
+
* prove the published npm tarball contains every module the package imports
|
|
7
|
+
* at runtime — with a negative assertion that `api-guides/` and helper .ts
|
|
8
|
+
* files are absent (GitHub-only recipes).
|
|
9
|
+
*
|
|
10
|
+
* Vendored (not imported from portal) so the host-only boundary stays intact.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
14
|
+
import { dirname, relative, resolve } from "node:path";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
|
|
17
|
+
const DEFAULT_SKIP_DIRS = ["node_modules", "docs", "__tests__"];
|
|
18
|
+
const SKIP_FILES = new Set<string>(["test-fixtures.ts"]);
|
|
19
|
+
/** Entries that won't exist on disk at rest but are valid (generated at pack time). */
|
|
20
|
+
const SKIP_STALE = new Set(["LICENSE"]);
|
|
21
|
+
|
|
22
|
+
export interface ShipManifestResult {
|
|
23
|
+
declared: readonly string[];
|
|
24
|
+
onDisk: readonly string[];
|
|
25
|
+
missing: readonly string[];
|
|
26
|
+
stale: readonly string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function verifyShipManifest(
|
|
30
|
+
packageDirOrUrl: string,
|
|
31
|
+
opts?: { skipDirs?: readonly string[] },
|
|
32
|
+
): ShipManifestResult {
|
|
33
|
+
const packageDir = packageDirOrUrl.startsWith("file:")
|
|
34
|
+
? dirname(fileURLToPath(packageDirOrUrl))
|
|
35
|
+
: packageDirOrUrl;
|
|
36
|
+
const skipDirs = new Set([...DEFAULT_SKIP_DIRS, ...(opts?.skipDirs ?? [])]);
|
|
37
|
+
let pkgRaw: string;
|
|
38
|
+
try {
|
|
39
|
+
pkgRaw = readFileSync(resolve(packageDir, "package.json"), "utf8");
|
|
40
|
+
} catch (err) {
|
|
41
|
+
throw new Error(
|
|
42
|
+
`verifyShipManifest: could not read package.json under "${packageDir}": ${
|
|
43
|
+
err instanceof Error ? err.message : String(err)
|
|
44
|
+
}`,
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
let pkg: { files?: string[] };
|
|
48
|
+
try {
|
|
49
|
+
pkg = JSON.parse(pkgRaw) as { files?: string[] };
|
|
50
|
+
} catch (err) {
|
|
51
|
+
throw new Error(
|
|
52
|
+
`verifyShipManifest: invalid package.json under "${packageDir}": ${
|
|
53
|
+
err instanceof Error ? err.message : String(err)
|
|
54
|
+
}`,
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
const declared = pkg.files ?? [];
|
|
58
|
+
const exactFiles = new Set<string>();
|
|
59
|
+
const dirPrefixes: string[] = [];
|
|
60
|
+
for (const entry of declared) {
|
|
61
|
+
if (entry.startsWith("!")) continue;
|
|
62
|
+
if (entry.endsWith("/")) dirPrefixes.push(entry);
|
|
63
|
+
else if (isDirOnDisk(packageDir, entry)) dirPrefixes.push(`${entry}/`);
|
|
64
|
+
else exactFiles.add(entry);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const onDisk = walkProductionTs(packageDir, packageDir, skipDirs);
|
|
68
|
+
const missing = onDisk.filter((f) => !isCovered(f, exactFiles, dirPrefixes));
|
|
69
|
+
const stale = declared.filter(
|
|
70
|
+
(entry) =>
|
|
71
|
+
!entry.startsWith("!") &&
|
|
72
|
+
!SKIP_STALE.has(entry) &&
|
|
73
|
+
!existsSync(resolve(packageDir, entry)),
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
return { declared, onDisk, missing, stale };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function isDirOnDisk(packageDir: string, entry: string): boolean {
|
|
80
|
+
try {
|
|
81
|
+
return statSync(resolve(packageDir, entry)).isDirectory();
|
|
82
|
+
} catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function isCovered(
|
|
88
|
+
file: string,
|
|
89
|
+
exactFiles: Set<string>,
|
|
90
|
+
dirPrefixes: readonly string[],
|
|
91
|
+
): boolean {
|
|
92
|
+
if (exactFiles.has(file)) return true;
|
|
93
|
+
for (const prefix of dirPrefixes) {
|
|
94
|
+
if (file.startsWith(prefix)) return true;
|
|
95
|
+
}
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function walkProductionTs(
|
|
100
|
+
root: string,
|
|
101
|
+
dir: string,
|
|
102
|
+
skipDirs: Set<string>,
|
|
103
|
+
): string[] {
|
|
104
|
+
const out: string[] = [];
|
|
105
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
106
|
+
if (entry.name.startsWith(".")) continue;
|
|
107
|
+
if (entry.isDirectory() && skipDirs.has(entry.name)) continue;
|
|
108
|
+
const abs = resolve(dir, entry.name);
|
|
109
|
+
if (entry.isDirectory()) {
|
|
110
|
+
out.push(...walkProductionTs(root, abs, skipDirs));
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (!entry.isFile() || !entry.name.endsWith(".ts")) continue;
|
|
114
|
+
if (entry.name.endsWith(".test.ts") || SKIP_FILES.has(entry.name)) continue;
|
|
115
|
+
out.push(relative(root, abs));
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
package/index.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
apiGuideTool,
|
|
5
|
+
apiFetchTool,
|
|
6
|
+
apiLearnTool,
|
|
7
|
+
apiProbeTool,
|
|
8
|
+
} from "./tools/index.js";
|
|
9
|
+
import initApiToggle from "./core/api-toggle.js";
|
|
10
|
+
import { registerPortalProjection } from "./core/portal-projection.js";
|
|
11
|
+
import { cleanupAllSpill } from "./core/response-spill.js";
|
|
12
|
+
import { resetToggleModuleState } from "./core/api-toggle.js";
|
|
13
|
+
import { resetDisabledHelpers } from "./core/local-helpers.js";
|
|
14
|
+
|
|
15
|
+
export default function (pi: ExtensionAPI): void {
|
|
16
|
+
// --- Ensure idempotent re-invocation ----------------------------
|
|
17
|
+
// pi reuses the cached extension factory on /resume (same cwd),
|
|
18
|
+
// which re-invokes this function with the same module-level
|
|
19
|
+
// singletons. Reset them here so the second load is safe.
|
|
20
|
+
resetToggleModuleState();
|
|
21
|
+
resetDisabledHelpers();
|
|
22
|
+
// ── Register tools ───────────────────────────────────────────
|
|
23
|
+
pi.registerTool(apiGuideTool);
|
|
24
|
+
pi.registerTool(apiFetchTool);
|
|
25
|
+
pi.registerTool(apiLearnTool);
|
|
26
|
+
pi.registerTool(apiProbeTool);
|
|
27
|
+
|
|
28
|
+
// ── Register /api command and session hooks ─────────────────
|
|
29
|
+
initApiToggle(pi);
|
|
30
|
+
|
|
31
|
+
// ── Portal co-install integration ────────────────────────────
|
|
32
|
+
// Register host's guide projection with portal if co-installed.
|
|
33
|
+
// Runtime feature-detect — no static portal import.
|
|
34
|
+
registerPortalProjection();
|
|
35
|
+
// session_start ensures registration even if host loads before portal.
|
|
36
|
+
pi.on("session_start", async () => {
|
|
37
|
+
registerPortalProjection();
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// ── Response spill cleanup ─────────────────────────────────
|
|
41
|
+
pi.on("session_shutdown", async () => {
|
|
42
|
+
cleanupAllSpill();
|
|
43
|
+
});
|
|
44
|
+
// cleanupAllSpill() on shutdown + eviction cap bounds disk use.
|
|
45
|
+
// Add per-session cleanup if cross-conversation leaks are observed.
|
|
46
|
+
}
|
package/package.json
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-lean-host",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "REST API client for Pi. A YAML file per API covers endpoints and pagination; the agent calls through a fixed executor so an API encoded once is reusable forever, not re-derived each session. It can probe a live endpoint and write the YAML for you, and a TypeScript file alongside can add custom auth or reshape the request and response freely.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
7
7
|
"pi-extension",
|
|
8
|
-
"
|
|
9
|
-
"
|
|
10
|
-
"
|
|
11
|
-
"
|
|
8
|
+
"api",
|
|
9
|
+
"rest",
|
|
10
|
+
"http",
|
|
11
|
+
"data",
|
|
12
|
+
"scraping"
|
|
12
13
|
],
|
|
13
14
|
"license": "AGPL-3.0-only",
|
|
14
15
|
"repository": {
|
|
@@ -21,16 +22,44 @@
|
|
|
21
22
|
"access": "public"
|
|
22
23
|
},
|
|
23
24
|
"files": [
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
"
|
|
25
|
+
"index.ts",
|
|
26
|
+
"LICENSE",
|
|
27
|
+
"core/ssrf-guard.ts",
|
|
28
|
+
"core/guide-loader.ts",
|
|
29
|
+
"core/api-guide-types.ts",
|
|
30
|
+
"core/parse-api-guide.ts",
|
|
31
|
+
"core/guide-store.ts",
|
|
32
|
+
"core/transport.ts",
|
|
33
|
+
"core/helpers.ts",
|
|
34
|
+
"core/path-template.ts",
|
|
35
|
+
"core/local-helpers.ts",
|
|
36
|
+
"core/helpers-command.ts",
|
|
37
|
+
"core/api-toggle.ts",
|
|
38
|
+
"core/portal-projection.ts",
|
|
39
|
+
"core/response-spill.ts",
|
|
40
|
+
"core/verify-ship-manifest.ts",
|
|
41
|
+
"tools/index.ts",
|
|
42
|
+
"tools/api-guide.ts",
|
|
43
|
+
"tools/api-fetch.ts",
|
|
44
|
+
"tools/api-learn.ts",
|
|
45
|
+
"tools/api-probe.ts",
|
|
46
|
+
"tools/utils.ts",
|
|
47
|
+
"README.md"
|
|
27
48
|
],
|
|
49
|
+
"pi": {
|
|
50
|
+
"extensions": [
|
|
51
|
+
"./index.ts"
|
|
52
|
+
]
|
|
53
|
+
},
|
|
28
54
|
"scripts": {
|
|
29
55
|
"prepack": "cp ../../LICENSE ./LICENSE",
|
|
30
|
-
"test": "vitest run"
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
"
|
|
56
|
+
"test": "vitest run"
|
|
57
|
+
},
|
|
58
|
+
"dependencies": {
|
|
59
|
+
"fast-xml-parser": "^5.7.0",
|
|
60
|
+
"pi-tool-masking": "^1.2.3",
|
|
61
|
+
"undici": "^8.0.0",
|
|
62
|
+
"yaml": "^2.7.0"
|
|
34
63
|
},
|
|
35
64
|
"peerDependencies": {
|
|
36
65
|
"@earendil-works/pi-ai": "*",
|