pi-lean-host 0.4.0 → 0.6.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 +194 -557
- package/core/api-guide-types.ts +250 -47
- package/core/api-toggle.ts +244 -39
- package/core/auth.ts +997 -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 +2 -2
- package/core/helpers.ts +532 -151
- package/core/local-helpers.ts +7 -0
- package/core/oauth-command.ts +913 -0
- package/core/oauth-flow.ts +392 -0
- package/core/oauth-store.ts +306 -0
- package/core/parse-api-guide.ts +1125 -596
- package/core/path-template.ts +101 -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/transport.ts +322 -35
- package/core/verify-command.ts +93 -65
- package/docs/migration-v1.md +56 -0
- package/index.ts +12 -10
- package/package.json +16 -6
- package/tools/api-fetch.ts +45 -18
- package/tools/api-guide.ts +37 -67
- package/tools/api-learn.ts +148 -103
- package/tools/api-probe.ts +458 -294
- package/tools/api-scaffold.ts +34 -63
- package/tools/api-store.ts +381 -0
- package/tools/oauth-mint.ts +338 -0
- package/tools/utils.ts +70 -1
- package/core/verify-ship-manifest.ts +0 -118
- package/tools/index.ts +0 -8
package/core/transport.ts
CHANGED
|
@@ -3,21 +3,57 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Provides `fetchUrl()` with:
|
|
5
5
|
* - ETag-based conditional requests (304 → cached body)
|
|
6
|
-
* -
|
|
6
|
+
* - Grant-based caching: a response is stored only when the server granted
|
|
7
|
+
* freshness — a time grant (`Cache-Control: max-age`) or a validator grant
|
|
8
|
+
* (an ETag → revalidate-only; the body is stored and every repeat is a
|
|
9
|
+
* conditional GET, usually answered by a 304 with no body). No TTL is
|
|
10
|
+
* ever fabricated for header-less responses.
|
|
7
11
|
* - Retry-on-429 with exponential backoff + `Retry-After` support
|
|
8
12
|
* - Configurable timeout
|
|
9
13
|
* - Automatic charset decoding from Content-Type
|
|
10
14
|
*
|
|
11
15
|
* Caching is per-URL, module-level (in-memory map). The cache is
|
|
12
16
|
* transparent to callers; each URL is cached independently.
|
|
17
|
+
*
|
|
18
|
+
* Deliberately ignored cache directives (recorded so they aren't
|
|
19
|
+
* re-investigated):
|
|
20
|
+
* - `Vary` — known limitation: the cache keys on URL + Accept + charset
|
|
21
|
+
* only; pre-existing, not widened into a fix here.
|
|
22
|
+
* - `s-maxage` — correctly ignored (private cache, RFC 7234 §1.3).
|
|
23
|
+
* - `must-revalidate` / `stale-while-revalidate` / `stale-if-error` —
|
|
24
|
+
* trivially satisfied: nothing is ever served stale.
|
|
25
|
+
* - `Age` / `Date` skew — a granted entry is served for its full `max-age`
|
|
26
|
+
* from store time even if `Age` says it arrived stale; pre-existing,
|
|
27
|
+
* unchanged in severity.
|
|
28
|
+
* - `Expires` — parsing deliberately not implemented (HTTP/1.0 legacy);
|
|
29
|
+
* under grant-based caching an Expires-only server is either
|
|
30
|
+
* revalidate-only (ETag present) or refetched every time (none).
|
|
13
31
|
*/
|
|
14
32
|
|
|
33
|
+
import { readFileSync } from "node:fs";
|
|
15
34
|
import { request, Agent, interceptors, type Dispatcher } from "undici";
|
|
35
|
+
import { gunzipSync, inflateRawSync, inflateSync } from "node:zlib";
|
|
16
36
|
import { ssrfGuard } from "./ssrf-guard.js";
|
|
17
37
|
|
|
38
|
+
// User-Agent version tracks the package version (no release-script edit needed).
|
|
39
|
+
// Falls back to "unknown" if package.json is unreadable — never fail transport init.
|
|
40
|
+
let HOST_UA_VERSION = "unknown";
|
|
41
|
+
try {
|
|
42
|
+
HOST_UA_VERSION = (
|
|
43
|
+
JSON.parse(
|
|
44
|
+
readFileSync(new URL("../package.json", import.meta.url), "utf-8"),
|
|
45
|
+
) as { version: string }
|
|
46
|
+
).version;
|
|
47
|
+
} catch {
|
|
48
|
+
// keep fallback
|
|
49
|
+
}
|
|
50
|
+
|
|
18
51
|
// ponytail: module-level composed agents; closed only on process exit.
|
|
19
52
|
// Add a close() in session_shutdown if leak-detection ever flags it.
|
|
20
53
|
|
|
54
|
+
/** One-shot flag so a 1-char path secret warns once, not per redacted URL. */
|
|
55
|
+
let warnedOneCharPathSecret = false;
|
|
56
|
+
|
|
21
57
|
/** Auto-follows up to 5 redirects. Used when redirect targets are trusted
|
|
22
58
|
* (agent-supplied URLs — the agent has bash, so guarding them is theater). */
|
|
23
59
|
const redirectAgent = new Agent().compose(
|
|
@@ -58,6 +94,15 @@ export interface FetchOptions {
|
|
|
58
94
|
* auth-bearing request, so this always applies to keyed calls).
|
|
59
95
|
*/
|
|
60
96
|
secretHeaderNames?: Set<string>;
|
|
97
|
+
/**
|
|
98
|
+
* Query-param names whose values are secrets injected from the secrets
|
|
99
|
+
* store (static-key `secretQueryRefs` or oauth2 `paramStyle: query`).
|
|
100
|
+
* Stripped from the URL on cross-domain redirect hops — a relative
|
|
101
|
+
* redirect preserves the original query, so a secret param would
|
|
102
|
+
* otherwise ride the hop to another host. Only honored while the
|
|
103
|
+
* guarded-redirect path is active (same condition as secretHeaderNames).
|
|
104
|
+
*/
|
|
105
|
+
secretQueryParamNames?: Set<string>;
|
|
61
106
|
/**
|
|
62
107
|
* True when this request carries a store-injected query-param secret
|
|
63
108
|
* (kind: static-key). Broadens `hasAuth` to cover query-secret-only
|
|
@@ -65,6 +110,26 @@ export interface FetchOptions {
|
|
|
65
110
|
* private (never cached / served from cache) and redirects are guarded.
|
|
66
111
|
*/
|
|
67
112
|
hasQuerySecret?: boolean;
|
|
113
|
+
/**
|
|
114
|
+
* True when this request carries store-injected path-token secrets
|
|
115
|
+
* (kind: static-key `secretPathRefs`). Broadens `hasAuth` exactly like
|
|
116
|
+
* `hasQuerySecret` — a path-secret-only guide (Telegram-class: no secret
|
|
117
|
+
* header, no secret query param) must skip the cache and get guarded
|
|
118
|
+
* redirects.
|
|
119
|
+
*/
|
|
120
|
+
hasPathSecret?: boolean;
|
|
121
|
+
/**
|
|
122
|
+
* Redaction closure applied to every cross-domain redirect hop URL before
|
|
123
|
+
* the next fetch: replaces store-injected path-token values (raw + both
|
|
124
|
+
* hex-encoded forms) with `***`. A path token rides mid-segment
|
|
125
|
+
* (`/bot<token>/getUpdates`), so a relative redirect would carry it to the
|
|
126
|
+
* other host — this is a value replacement, not a segment deletion (that
|
|
127
|
+
* would change the route). Built by the caller where the values are in
|
|
128
|
+
* scope; the transport stays value-agnostic (no raw secrets in its
|
|
129
|
+
* signature vocabulary). Only consulted on cross-domain hops — same-host
|
|
130
|
+
* Location echoes keep the token (resolve-against-hopUrl semantics).
|
|
131
|
+
*/
|
|
132
|
+
redactPathSecret?: (url: string) => string;
|
|
68
133
|
/** Charset to decode the body with when the response's Content-Type
|
|
69
134
|
* header omits one. Honors a guide's `responseShape.charset` for APIs
|
|
70
135
|
* that serve e.g. ISO-8859-1 bytes without a charset parameter. An
|
|
@@ -91,24 +156,41 @@ interface CacheEntry {
|
|
|
91
156
|
/** ETag for conditional requests; absent when the upstream didn't send one. */
|
|
92
157
|
etag?: string;
|
|
93
158
|
expiresAt: number;
|
|
159
|
+
/** The freshness grant (ms) currently in effect — stamped at store time
|
|
160
|
+
* and re-stamped on every 304 refresh. A bare 304 (no grant of its own)
|
|
161
|
+
* falls back to this value so a granted entry doesn't degrade to
|
|
162
|
+
* revalidate-only when the 304 carries no max-age; because it is
|
|
163
|
+
* re-stamped, a `no-cache` 304's 0 grant survives later bare 304s. */
|
|
164
|
+
grantMs: number;
|
|
94
165
|
}
|
|
95
166
|
|
|
96
167
|
const DEFAULT_TIMEOUT = 30_000;
|
|
97
168
|
const DEFAULT_MAX_RETRIES = 2;
|
|
98
|
-
const DEFAULT_TTL_MS = 60_000; // 60s fallback when no Cache-Control
|
|
99
169
|
const MAX_CACHE_ENTRIES = 100; // ponytail: hard cap; evict soonest-expiring when exceeded
|
|
100
170
|
const MAX_BODY_BYTES = 10 * 1024 * 1024; // 10 MB ceiling on a single response body
|
|
101
171
|
|
|
102
172
|
/** Module-level cache: cache-key → CacheEntry. */
|
|
103
173
|
const cache = new Map<string, CacheEntry>();
|
|
104
174
|
|
|
175
|
+
/** Module clock — overridden by tests for sleep-free TTL-expiry scenarios.
|
|
176
|
+
* Only the four cache-path call sites consult this (hit branch,
|
|
177
|
+
* evictCacheIfNeeded, 2xx store, 304 refresh); retry/backoff/timeout paths
|
|
178
|
+
* keep bare Date.now(). */
|
|
179
|
+
let _now: () => number = Date.now;
|
|
180
|
+
|
|
181
|
+
/** Test seam — swap the module clock used by the cache paths.
|
|
182
|
+
* Same `_…ForTest` convention as guide-store.ts's `_resetLoadWarningsForTest`. */
|
|
183
|
+
export function _setClockForTest(fn: () => number): void {
|
|
184
|
+
_now = fn;
|
|
185
|
+
}
|
|
186
|
+
|
|
105
187
|
/**
|
|
106
188
|
* Drop expired entries, then — if still over the cap — evict the
|
|
107
189
|
* soonest-expiring entries. Called before every `cache.set`.
|
|
108
190
|
*/
|
|
109
191
|
function evictCacheIfNeeded(): void {
|
|
110
192
|
if (cache.size < MAX_CACHE_ENTRIES) return;
|
|
111
|
-
const now =
|
|
193
|
+
const now = _now();
|
|
112
194
|
for (const [k, e] of cache) {
|
|
113
195
|
if (e.expiresAt <= now) cache.delete(k);
|
|
114
196
|
}
|
|
@@ -149,7 +231,7 @@ function cacheKey(url: string, opts?: FetchOptions): string {
|
|
|
149
231
|
* normalized by this). Defined here so the transport layer — the one place
|
|
150
232
|
* that holds a raw request URL and may embed it in an error message — can
|
|
151
233
|
* self-redact instead of relying on callers to remember. `helpers.ts`
|
|
152
|
-
*
|
|
234
|
+
* uses it for the capture points it owns (result.url, urls[],
|
|
153
235
|
* HelperError.url).
|
|
154
236
|
*/
|
|
155
237
|
export function redactSecretParams(
|
|
@@ -168,6 +250,50 @@ export function redactSecretParams(
|
|
|
168
250
|
}
|
|
169
251
|
}
|
|
170
252
|
|
|
253
|
+
/**
|
|
254
|
+
* Output-channel audit — path-token channel: redact store-injected path
|
|
255
|
+
* token values from a URL for surfacing. Unlike `redactSecretParams` (query
|
|
256
|
+
* params, name-keyed), a path token is embedded mid-segment
|
|
257
|
+
* (`/bot<token>/getUpdates`), so this is a string replace of each resolved
|
|
258
|
+
* value with `***` — raw, plus its `encodeURIComponent` form in BOTH hex
|
|
259
|
+
* cases (uppercase `%3A` from `fillPathTemplate` and lowercase `%3a` echoes
|
|
260
|
+
* from server-normalized URLs / error bodies). Deliberate asymmetry with
|
|
261
|
+
* `scrubSecretValues` (do not unify): the URL channel skips 1-char values
|
|
262
|
+
* because surfaced URLs are functional — a 1-char replace corrupts unrelated
|
|
263
|
+
* path text (`/things/1234/x` → `/things/***234/x`) with negligible security
|
|
264
|
+
* gain — while the body scrub takes any non-empty value (bodies are
|
|
265
|
+
* informational and tolerate collateral corruption). String needles only,
|
|
266
|
+
* never regex — same `$`-pattern pitfall `scrubSecretValues` avoids.
|
|
267
|
+
*/
|
|
268
|
+
export function redactSecretPathValues(
|
|
269
|
+
url: string,
|
|
270
|
+
secretPathValues?: string[],
|
|
271
|
+
): string {
|
|
272
|
+
if (!secretPathValues || secretPathValues.length === 0) return url;
|
|
273
|
+
let out = url;
|
|
274
|
+
for (const v of secretPathValues) {
|
|
275
|
+
if (v.length === 0) continue;
|
|
276
|
+
if (v.length === 1) {
|
|
277
|
+
// ponytail: once-per-session flag — a long /api verify run would
|
|
278
|
+
// otherwise spam one warn per redacted URL; promote to a per-guide
|
|
279
|
+
// (or surfaced-details) channel if the once-per-session miss matters.
|
|
280
|
+
if (!warnedOneCharPathSecret) {
|
|
281
|
+
warnedOneCharPathSecret = true;
|
|
282
|
+
console.warn(
|
|
283
|
+
"⚠ path secret is 1 character — redact-unfriendly for URL surfaces; skipping URL redaction (the body scrub still applies)",
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
const enc = encodeURIComponent(v);
|
|
289
|
+
const encLower = enc.replace(/%../g, (s) => s.toLowerCase());
|
|
290
|
+
for (const needle of new Set([v, enc, encLower])) {
|
|
291
|
+
out = out.split(needle).join("***");
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return out;
|
|
295
|
+
}
|
|
296
|
+
|
|
171
297
|
function parseHeaders(
|
|
172
298
|
hdrs: Dispatcher.ResponseData["headers"],
|
|
173
299
|
): Record<string, string> {
|
|
@@ -203,6 +329,37 @@ async function collectBody(
|
|
|
203
329
|
return Buffer.concat(chunks);
|
|
204
330
|
}
|
|
205
331
|
|
|
332
|
+
/**
|
|
333
|
+
* Content-Encoding decompression — some servers (Open Food Facts' mod_deflate,
|
|
334
|
+
* various OData stacks) gzip JSON responses even when the client does not
|
|
335
|
+
* advertise `Accept-Encoding: gzip`. undici's raw `request()` does NOT
|
|
336
|
+
* auto-decompress (unlike fetch()), so without this the raw gzip bytes reach
|
|
337
|
+
* JSON.parse and the op fails with a confusing "Invalid JSON response".
|
|
338
|
+
* Handled here — the single choke point every fetch (restGet, paginate,
|
|
339
|
+
* nextLink hops, /api verify) flows through — not per call site.
|
|
340
|
+
* ponytail: gzip + deflate only; br and multi-layer encodings pass through
|
|
341
|
+
* untouched — add when a real guide needs them.
|
|
342
|
+
*/
|
|
343
|
+
function decompressBody(buf: Buffer, encoding: string | undefined): Buffer {
|
|
344
|
+
const enc = encoding?.toLowerCase().trim();
|
|
345
|
+
if (!enc) return buf;
|
|
346
|
+
try {
|
|
347
|
+
if (enc === "gzip" || enc === "x-gzip") return gunzipSync(buf);
|
|
348
|
+
// "deflate" is ambiguous on the wire (zlib-wrapped vs raw) — try both.
|
|
349
|
+
if (enc === "deflate") {
|
|
350
|
+
try {
|
|
351
|
+
return inflateSync(buf);
|
|
352
|
+
} catch {
|
|
353
|
+
return inflateRawSync(buf);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
} catch {
|
|
357
|
+
// Un-decodable body (e.g. server lied about the encoding) — return the
|
|
358
|
+
// raw bytes so the caller surfaces the parse error it would have anyway.
|
|
359
|
+
}
|
|
360
|
+
return buf;
|
|
361
|
+
}
|
|
362
|
+
|
|
206
363
|
function decodeBuffer(buf: Buffer, charset: string): string {
|
|
207
364
|
const cs = charset.toLowerCase().replace(/[^a-z0-9_-]/g, "");
|
|
208
365
|
if (cs === "utf-8" || cs === "utf8" || cs === "") {
|
|
@@ -224,6 +381,47 @@ function parseMaxAge(headers: Record<string, string>): number | null {
|
|
|
224
381
|
return m ? parseInt(m[1]!, 10) * 1000 : null;
|
|
225
382
|
}
|
|
226
383
|
|
|
384
|
+
/**
|
|
385
|
+
* Effective freshness grant for a response, in ms — computed ONCE per
|
|
386
|
+
* response; every cache consumer (store condition, entry expiry, 304
|
|
387
|
+
* refresh) reads this single derivation, nothing re-derives from raw
|
|
388
|
+
* headers.
|
|
389
|
+
*
|
|
390
|
+
* no-cache → 0 (revalidation required before reuse regardless of
|
|
391
|
+
* freshness, RFC 7234 §5.2.2.4 — even with max-age > 0)
|
|
392
|
+
* otherwise → parseMaxAge(headers) ?? 0 (0 = no time grant; a
|
|
393
|
+
* revalidate-only entry is born expired)
|
|
394
|
+
*
|
|
395
|
+
* `no-store` is NOT detected here — the store/refresh sites check it
|
|
396
|
+
* explicitly, because a `no-store` response carrying an ETag (or max-age)
|
|
397
|
+
* would otherwise satisfy the grant formula and get stored.
|
|
398
|
+
*/
|
|
399
|
+
function effectiveGrant(headers: Record<string, string>): number | null {
|
|
400
|
+
const cc = headers["cache-control"];
|
|
401
|
+
if (cc && /no-cache/i.test(cc)) return 0;
|
|
402
|
+
return parseMaxAge(headers);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Cache-store condition for a 2xx response: cache the entry only when the
|
|
407
|
+
* response is not `no-store` AND (the effective grant is > 0 or an ETag
|
|
408
|
+
* exists). Pass the grant already derived by the caller — the same
|
|
409
|
+
* "compute once" rule the store/expiry/304 consumers follow.
|
|
410
|
+
* `grantMs > 0` — not raw `parseMaxAge` — excludes dead entries
|
|
411
|
+
* (`max-age=0` or `no-cache, max-age>0` with no ETag would be stored,
|
|
412
|
+
* never served, never 304-refreshable); `no-cache` is not excluded from
|
|
413
|
+
* storage outright because with an ETag it revalidates every use (RFC
|
|
414
|
+
* 7234), consistent with the `no-cache, max-age=0` + ETag pair
|
|
415
|
+
* (`parseMaxAge` returns 0, not null, for that pair).
|
|
416
|
+
*/
|
|
417
|
+
function shouldStore(
|
|
418
|
+
headers: Record<string, string>,
|
|
419
|
+
grantMs: number,
|
|
420
|
+
): boolean {
|
|
421
|
+
if (/no-store/i.test(headers["cache-control"] ?? "")) return false;
|
|
422
|
+
return grantMs > 0 || !!headers["etag"];
|
|
423
|
+
}
|
|
424
|
+
|
|
227
425
|
/**
|
|
228
426
|
* Compute the delay before a retry. Prefers Retry-After: delay-seconds;
|
|
229
427
|
* falls back to parsing an HTTP-date form. If the date is in the past
|
|
@@ -322,6 +520,34 @@ export function stripSecretHeaders(
|
|
|
322
520
|
return out;
|
|
323
521
|
}
|
|
324
522
|
|
|
523
|
+
/**
|
|
524
|
+
* Remove secret query params from a URL (cross-domain redirect hops only).
|
|
525
|
+
* A relative redirect (new URL("?x", current)) preserves the original query
|
|
526
|
+
* string, so injected secrets would survive onto the next host.
|
|
527
|
+
*/
|
|
528
|
+
export function stripSecretQueryParams(
|
|
529
|
+
url: string,
|
|
530
|
+
secretQueryParamNames?: Set<string>,
|
|
531
|
+
): string {
|
|
532
|
+
if (!secretQueryParamNames || secretQueryParamNames.size === 0) return url;
|
|
533
|
+
// ponytail: URL() throws on malformed input; pass through unmodified —
|
|
534
|
+
// singleGet will surface the real fetch error anyway.
|
|
535
|
+
let u: URL;
|
|
536
|
+
try {
|
|
537
|
+
u = new URL(url);
|
|
538
|
+
} catch {
|
|
539
|
+
return url;
|
|
540
|
+
}
|
|
541
|
+
let changed = false;
|
|
542
|
+
for (const name of secretQueryParamNames) {
|
|
543
|
+
if (u.searchParams.has(name)) {
|
|
544
|
+
u.searchParams.delete(name);
|
|
545
|
+
changed = true;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
return changed ? u.toString() : url;
|
|
549
|
+
}
|
|
550
|
+
|
|
325
551
|
/**
|
|
326
552
|
* Follow redirects manually, SSRF-checking each target. Used for
|
|
327
553
|
* server-supplied URLs (paginate nextLink) and — forced — any auth-bearing
|
|
@@ -336,6 +562,8 @@ async function getWithGuardedRedirects(
|
|
|
336
562
|
startTime: number,
|
|
337
563
|
timeoutMs: number,
|
|
338
564
|
secretHeaderNames?: Set<string>,
|
|
565
|
+
secretQueryParamNames?: Set<string>,
|
|
566
|
+
redactPathSecret?: (url: string) => string,
|
|
339
567
|
): Promise<{
|
|
340
568
|
status: number;
|
|
341
569
|
headers: Record<string, string>;
|
|
@@ -347,18 +575,30 @@ async function getWithGuardedRedirects(
|
|
|
347
575
|
for (let hops = 0; hops <= MAX_REDIRECTS; hops++) {
|
|
348
576
|
// Strip store-injected secrets (and Authorization) once a hop leaves
|
|
349
577
|
// the request's original host — a secret must never cross domains.
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
578
|
+
// Query secrets need the same treatment: a relative redirect preserves
|
|
579
|
+
// the original query string, so secret query params would ride the hop.
|
|
580
|
+
// Path tokens ride mid-segment, so the hop URL additionally gets the
|
|
581
|
+
// caller's redaction closure (value replace, never segment deletion).
|
|
582
|
+
const crossDomain = hostOf(current) !== originalHost;
|
|
583
|
+
const hopHeaders = crossDomain
|
|
584
|
+
? stripSecretHeaders(reqHeaders, secretHeaderNames)
|
|
585
|
+
: reqHeaders;
|
|
586
|
+
let hopUrl = current;
|
|
587
|
+
if (crossDomain) {
|
|
588
|
+
hopUrl = stripSecretQueryParams(current, secretQueryParamNames);
|
|
589
|
+
if (redactPathSecret) hopUrl = redactPathSecret(hopUrl);
|
|
590
|
+
}
|
|
354
591
|
const remaining = timeoutMs - (Date.now() - startTime);
|
|
355
|
-
const res = await singleGet(
|
|
592
|
+
const res = await singleGet(hopUrl, hopHeaders, remaining, noRedirectAgent);
|
|
356
593
|
const isRedirect =
|
|
357
594
|
res.status >= 300 && res.status < 400 && res.status !== 304;
|
|
358
595
|
if (!isRedirect || hops === MAX_REDIRECTS) return res;
|
|
359
596
|
const loc = res.headers["location"];
|
|
360
597
|
if (!loc) return res; // redirect with no Location — return as-is
|
|
361
|
-
|
|
598
|
+
// Resolve against hopUrl, not current — a relative redirect inherits
|
|
599
|
+
// the base's query string, and current still carries the secret params
|
|
600
|
+
// that were just stripped for this hop's fetch.
|
|
601
|
+
const next = new URL(loc, hopUrl).toString();
|
|
362
602
|
const guard = ssrfGuard(next);
|
|
363
603
|
if (!guard.ok) {
|
|
364
604
|
// Security-control failure is not transient — don't retry.
|
|
@@ -379,13 +619,22 @@ async function getWithGuardedRedirects(
|
|
|
379
619
|
/**
|
|
380
620
|
* Fetch a URL with caching and retry-on-429.
|
|
381
621
|
*
|
|
382
|
-
* Cache behaviour:
|
|
622
|
+
* Cache behaviour (grant-based — no TTL is ever fabricated):
|
|
383
623
|
* - URLs are cached in a module-level `Map<string, CacheEntry>`.
|
|
384
|
-
* -
|
|
624
|
+
* - A 2xx is stored only on an explicit server grant: a time grant
|
|
625
|
+
* (`Cache-Control: max-age=N`) or a validator grant (an ETag — stored
|
|
626
|
+
* with no stale window; every repeat sends `If-None-Match` and is
|
|
627
|
+
* revalidate-only). `no-store` is never stored; `no-cache` never
|
|
628
|
+
* serves from the fresh-hit branch (with an ETag it still revalidates).
|
|
385
629
|
* - When a cached entry has an `etag`, the conditional `If-None-Match`
|
|
386
|
-
* header is sent
|
|
630
|
+
* header is sent; a 304 refreshes the entry's expiry from the 304's
|
|
631
|
+
* own grant, falling back to the grant recorded at store time. A 304
|
|
632
|
+
* carrying `no-store` deletes the entry instead of refreshing it.
|
|
633
|
+
* - Header-less responses (no `Cache-Control`, no ETag) are never
|
|
634
|
+
* cached — every call hits the network.
|
|
387
635
|
* - `opts.fresh = true` skips the cache read and bypasses sending
|
|
388
|
-
* `If-None-Match` (server returns full response)
|
|
636
|
+
* `If-None-Match` (server returns full response); a granted response
|
|
637
|
+
* fetched fresh is still stored (seeding the cache).
|
|
389
638
|
* - Requests carrying caller-specific headers (anything besides Accept,
|
|
390
639
|
* e.g. API keys) are never cached or served from cache — the response
|
|
391
640
|
* is private to that caller.
|
|
@@ -414,17 +663,21 @@ export async function fetchUrl(
|
|
|
414
663
|
const hasAuthHeaders =
|
|
415
664
|
!!opts?.headers &&
|
|
416
665
|
Object.keys(opts.headers).some((h) => h.toLowerCase() !== "accept");
|
|
417
|
-
// Broader hasAuth gate: header-secrets ∨ query-secrets. A
|
|
418
|
-
// guide carries no non-accept header, so
|
|
419
|
-
// miss it — hasQuerySecret
|
|
420
|
-
// hasAuth: cache-skip,
|
|
421
|
-
|
|
666
|
+
// Broader hasAuth gate: header-secrets ∨ query-secrets ∨ path-secrets. A
|
|
667
|
+
// query- or path-secret-only guide carries no non-accept header, so
|
|
668
|
+
// hasAuthHeaders alone would miss it — hasQuerySecret/hasPathSecret close
|
|
669
|
+
// those gaps. Every auth gate below keys on hasAuth: cache-skip,
|
|
670
|
+
// If-None-Match, and the guarded-redirect force.
|
|
671
|
+
const hasAuth =
|
|
672
|
+
hasAuthHeaders ||
|
|
673
|
+
(opts?.hasQuerySecret ?? false) ||
|
|
674
|
+
(opts?.hasPathSecret ?? false);
|
|
422
675
|
|
|
423
676
|
// ── cache hit ───────────────────────────────────────────────
|
|
424
677
|
const key = cacheKey(url, opts);
|
|
425
678
|
if (!opts?.fresh && !hasAuth) {
|
|
426
679
|
const entry = cache.get(key);
|
|
427
|
-
if (entry &&
|
|
680
|
+
if (entry && _now() < entry.expiresAt) {
|
|
428
681
|
return { status: 200, headers: {}, body: entry.body, cached: true };
|
|
429
682
|
}
|
|
430
683
|
}
|
|
@@ -433,13 +686,21 @@ export async function fetchUrl(
|
|
|
433
686
|
const reqHeaders: Record<string, string> = { ...opts?.headers };
|
|
434
687
|
if (!reqHeaders["user-agent"]) {
|
|
435
688
|
reqHeaders["user-agent"] =
|
|
436
|
-
|
|
689
|
+
`pi-lean-host/${HOST_UA_VERSION} (+https://github.com/coreyryanhanson/pi-lean-dimension)`;
|
|
437
690
|
}
|
|
438
691
|
|
|
692
|
+
// The entry being revalidated, captured at If-None-Match time. The 304
|
|
693
|
+
// arm reads this instead of re-fetching the map: a concurrent caller's
|
|
694
|
+
// evictCacheIfNeeded can delete the (expired) entry while the conditional
|
|
695
|
+
// GET is awaited, and re-reading would then find nothing and serve the
|
|
696
|
+
// 304's empty body as the response.
|
|
697
|
+
let revalidate: CacheEntry | undefined;
|
|
698
|
+
|
|
439
699
|
if (!opts?.fresh && !hasAuth) {
|
|
440
700
|
const entry = cache.get(key);
|
|
441
701
|
if (entry?.etag) {
|
|
442
702
|
reqHeaders["If-None-Match"] = entry.etag;
|
|
703
|
+
revalidate = entry;
|
|
443
704
|
}
|
|
444
705
|
}
|
|
445
706
|
|
|
@@ -467,17 +728,35 @@ export async function fetchUrl(
|
|
|
467
728
|
startTime,
|
|
468
729
|
timeout,
|
|
469
730
|
opts?.secretHeaderNames,
|
|
731
|
+
opts?.secretQueryParamNames,
|
|
732
|
+
opts?.redactPathSecret,
|
|
470
733
|
)
|
|
471
734
|
: await singleGet(url, reqHeaders, remaining, redirectAgent);
|
|
472
735
|
|
|
473
736
|
// ── 304 Not Modified ────────────────────────────────
|
|
474
|
-
|
|
475
|
-
|
|
737
|
+
// Gated on !hasAuth like every other cache arm: a keyed request must
|
|
738
|
+
// never be served a body cached by an unauthenticated caller, even
|
|
739
|
+
// from a protocol-violating server that sends a spontaneous 304.
|
|
740
|
+
// Also gated on !fresh for the same reason: a fresh request must not
|
|
741
|
+
// receive a cached body, so an unsolicited 304 falls through to the
|
|
742
|
+
// status check instead.
|
|
743
|
+
if (status === 304 && !hasAuth && !opts?.fresh) {
|
|
744
|
+
const entry = revalidate ?? cache.get(key);
|
|
476
745
|
if (entry) {
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
746
|
+
if (/no-store/i.test(respHeaders["cache-control"] ?? "")) {
|
|
747
|
+
// A no-store revalidation result must not be stored.
|
|
748
|
+
cache.delete(key);
|
|
749
|
+
} else {
|
|
750
|
+
// Refresh from the 304's own effective grant; fall back to the
|
|
751
|
+
// grant currently recorded on the entry (a granted entry must
|
|
752
|
+
// not degrade to revalidate-only when the 304 carries no
|
|
753
|
+
// max-age), and re-stamp it so the newest grant sticks.
|
|
754
|
+
const grant304 = effectiveGrant(respHeaders) ?? entry.grantMs;
|
|
755
|
+
entry.grantMs = grant304;
|
|
756
|
+
entry.expiresAt = _now() + grant304;
|
|
757
|
+
// The entry object is mutated in place — cache.get returned the
|
|
758
|
+
// live reference, so no re-set is needed.
|
|
759
|
+
}
|
|
481
760
|
return {
|
|
482
761
|
status: 200,
|
|
483
762
|
headers: respHeaders,
|
|
@@ -500,16 +779,24 @@ export async function fetchUrl(
|
|
|
500
779
|
const contentType = respHeaders["content-type"] ?? "";
|
|
501
780
|
const charsetMatch = contentType.match(/charset\s*=\s*([^\s;]+)/i);
|
|
502
781
|
const charset = charsetMatch?.[1] ?? opts?.fallbackCharset ?? "utf-8";
|
|
503
|
-
const body = decodeBuffer(
|
|
782
|
+
const body = decodeBuffer(
|
|
783
|
+
decompressBody(rawBody, respHeaders["content-encoding"]),
|
|
784
|
+
charset,
|
|
785
|
+
);
|
|
504
786
|
|
|
505
787
|
if (status >= 200 && status < 300 && !hasAuth) {
|
|
506
|
-
const
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
788
|
+
const grantMs = effectiveGrant(respHeaders) ?? 0;
|
|
789
|
+
if (shouldStore(respHeaders, grantMs)) {
|
|
790
|
+
const entry: CacheEntry = {
|
|
791
|
+
body,
|
|
792
|
+
expiresAt: _now() + grantMs,
|
|
793
|
+
grantMs,
|
|
794
|
+
};
|
|
795
|
+
const etag = respHeaders["etag"];
|
|
796
|
+
if (etag) entry.etag = etag;
|
|
797
|
+
evictCacheIfNeeded();
|
|
798
|
+
cache.set(key, entry);
|
|
799
|
+
}
|
|
513
800
|
}
|
|
514
801
|
|
|
515
802
|
return {
|