pi-lean-host 0.7.2 → 0.8.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/core/transport.ts CHANGED
@@ -11,6 +11,9 @@
11
11
  * - Retry-on-429 with exponential backoff + `Retry-After` support
12
12
  * - Configurable timeout
13
13
  * - Automatic charset decoding from Content-Type
14
+ * - Sink mode (`FetchOptions.sink`): stream the body to a caller-supplied
15
+ * Writable — manual redirect loop with hop-drain, cache arms skipped,
16
+ * abort timer scoped to time-to-headers
14
17
  *
15
18
  * Caching is per-URL, module-level (in-memory map). The cache is
16
19
  * transparent to callers; each URL is cached independently.
@@ -31,8 +34,18 @@
31
34
  */
32
35
 
33
36
  import { readFileSync } from "node:fs";
37
+ import { setTimeout as setTimeoutP } from "node:timers/promises";
34
38
  import { request, Agent, interceptors, type Dispatcher } from "undici";
35
- import { gunzipSync, inflateRawSync, inflateSync } from "node:zlib";
39
+ import {
40
+ createGunzip,
41
+ createInflate,
42
+ createInflateRaw,
43
+ gunzipSync,
44
+ inflateRawSync,
45
+ inflateSync,
46
+ } from "node:zlib";
47
+ import { Readable, Transform, Writable } from "node:stream";
48
+ import { pipeline } from "node:stream/promises";
36
49
  import { ssrfGuard } from "./ssrf-guard.js";
37
50
 
38
51
  // User-Agent version tracks the package version (no release-script edit needed).
@@ -70,6 +83,12 @@ const MAX_REDIRECTS = 5;
70
83
  // Types
71
84
  // ═══════════════════════════════════════════════════════════════════
72
85
 
86
+ /** The single stop bound for a sink-mode transfer (see FetchOptions.stop). */
87
+ export interface StopBound {
88
+ bytes: number;
89
+ kind: "cap" | "budget";
90
+ }
91
+
73
92
  export interface FetchOptions {
74
93
  /** Request timeout in ms (default: 30_000). */
75
94
  timeout?: number;
@@ -79,6 +98,18 @@ export interface FetchOptions {
79
98
  maxRetries?: number;
80
99
  /** Skip cache (force fresh fetch). */
81
100
  fresh?: boolean;
101
+ /**
102
+ * Sink-mode signal: a caller-supplied writable the response body is piped
103
+ * into (download transfers — the executor layer opens the file and supplies
104
+ * the writable; the transport never sees a path or owns a file). Absent
105
+ * (collect mode, the default) = today's buffered behavior, byte for byte.
106
+ * In sink mode: the request rides the manual redirect loop (intermediate
107
+ * hop bodies are drained), the cache arms are all skipped, the abort timer
108
+ * covers time-to-headers only, and `body` is "" — nothing stream-like
109
+ * crosses this public boundary; every abandoned body is destroy()ed by
110
+ * the transport, the stream's sole owner.
111
+ */
112
+ sink?: Writable;
82
113
  /** SSRF-check each redirect target before following it. Use it for
83
114
  * server-supplied URLs (paginate nextLink) — a malicious API can 302
84
115
  * to an internal host, and when auth headers ship the Authorization
@@ -135,6 +166,24 @@ export interface FetchOptions {
135
166
  * that serve e.g. ISO-8859-1 bytes without a charset parameter. An
136
167
  * explicit header charset always takes precedence. */
137
168
  fallbackCharset?: string;
169
+ /** Caller's abort signal (tool-call cancellation). Composed with the
170
+ * per-request timeout controller, so cancellation aborts connect,
171
+ * redirect hops, the mid-body stream, and retry backoff alike —
172
+ * undici releases the socket. Accepted in both modes. */
173
+ signal?: AbortSignal;
174
+ /** The run's single stop bound (sink mode; resolved by the executor).
175
+ * A `cap` — the free-disk-derived download ceiling — destroys the pipe
176
+ * with BodyTooLargeError past it, and a Content-Length preflight
177
+ * refuses at header time (TransportRefusalError, code "lengthOverCap")
178
+ * when the declared wire length already exceeds it — before any byte
179
+ * is written; the preflight is skipped when Content-Encoding is
180
+ * present (the wire length is then not the decompressed size — the
181
+ * counting Transform remains the sole enforcement point). A `budget`
182
+ * (the /api verify download probe) stops CLEANLY at `bytes` — a pass
183
+ * signal, never BodyTooLargeError — and no preflight runs (a budgeted
184
+ * probe is intentionally partial). Absent = no stop bound (collect
185
+ * mode never consults one). */
186
+ stop?: StopBound;
138
187
  }
139
188
 
140
189
  export interface FetchResult {
@@ -162,6 +211,9 @@ interface CacheEntry {
162
211
  * revalidate-only when the 304 carries no max-age; because it is
163
212
  * re-stamped, a `no-cache` 304's 0 grant survives later bare 304s. */
164
213
  grantMs: number;
214
+ /** Final URL of the request that populated the entry — preserved so a
215
+ * cache-served response surfaces the same redirect the live fetch did. */
216
+ finalUrl?: string;
165
217
  }
166
218
 
167
219
  const DEFAULT_TIMEOUT = 30_000;
@@ -321,7 +373,7 @@ async function collectBody(
321
373
  total += chunk.length;
322
374
  if (total > MAX_BODY_BYTES) {
323
375
  const err = new Error(`Response body exceeded ${MAX_BODY_BYTES} bytes`);
324
- err.name = "BodyTooLargeError"; // checked by fetchUrl retry logic
376
+ err.name = "BodyTooLargeError"; // non-transient in the fetch retry catch
325
377
  throw err;
326
378
  }
327
379
  chunks.push(Buffer.from(chunk));
@@ -360,6 +412,244 @@ function decompressBody(buf: Buffer, encoding: string | undefined): Buffer {
360
412
  return buf;
361
413
  }
362
414
 
415
+ /**
416
+ * Header-time refusal in sink mode: a response the pipe must not start on
417
+ * (unsupported Content-Encoding, or an over-cap Content-Length). Thrown
418
+ * before any byte reaches the sink, past the retry catch — never retried
419
+ * (a refusal re-evaluated from headers alone can never succeed). The
420
+ * download executor catches it and maps it to a structured HelperError;
421
+ * the transport itself never throws executor vocabulary.
422
+ */
423
+ export class TransportRefusalError extends Error {
424
+ code: "contentEncoding" | "lengthOverCap";
425
+ constructor(code: "contentEncoding" | "lengthOverCap", message: string) {
426
+ super(message);
427
+ this.name = "TransportRefusalError";
428
+ this.code = code;
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Pass-through byte counter for the decompress chain — `bytes` is the
434
+ * DECOMPRESSED size (legitimately different from the wire's Content-Length
435
+ * on a compressed transfer); the stop bound compares against it. The
436
+ * download executor sizes the finished file with statSync instead.
437
+ *
438
+ * The `stop` bound's cap-vs-budget semantics are defined on FetchOptions.stop.
439
+ */
440
+ class BudgetReachedError extends Error {
441
+ constructor(public readonly bytes: number) {
442
+ super(`byte budget reached (${bytes} bytes)`);
443
+ this.name = "BudgetReachedError";
444
+ }
445
+ }
446
+
447
+ class ByteCountingTransform extends Transform {
448
+ bytes = 0;
449
+ constructor(private readonly stop?: StopBound) {
450
+ super();
451
+ }
452
+ _transform(
453
+ chunk: Buffer,
454
+ _enc: BufferEncoding,
455
+ cb: (err?: Error | null, data?: Buffer) => void,
456
+ ): void {
457
+ const stop = this.stop;
458
+ const total = this.bytes + chunk.length;
459
+ if (stop !== undefined) {
460
+ // Cap: a body of EXACTLY cap bytes is legal (the Content-Length
461
+ // preflight uses the same `>` comparison) — only going past throws.
462
+ if (stop.kind === "cap" && total > stop.bytes) {
463
+ this.bytes = total;
464
+ const err = new Error(
465
+ `Download exceeded the effective cap of ${stop.bytes} bytes`,
466
+ );
467
+ err.name = "BodyTooLargeError";
468
+ cb(err);
469
+ return;
470
+ }
471
+ // Budget: forward only the slice that reaches the budget, then stop
472
+ // cleanly — the count lands at exactly the budget whether the stream
473
+ // ends naturally there (pipeline completes) or a further chunk
474
+ // throws BudgetReachedError (resolved as a pass in pipeBodyToSink).
475
+ if (stop.kind === "budget" && total >= stop.bytes) {
476
+ const take = stop.bytes - this.bytes;
477
+ this.bytes = stop.bytes;
478
+ if (take > 0) {
479
+ cb(null, chunk.subarray(0, take));
480
+ } else {
481
+ cb(new BudgetReachedError(stop.bytes));
482
+ }
483
+ return;
484
+ }
485
+ }
486
+ this.bytes = total;
487
+ cb(null, chunk);
488
+ }
489
+ }
490
+
491
+ /** Capped prefix collected from an abandoned non-2xx body — the
492
+ * error-rendering excerpt (~8 KB, the error-body convention). */
493
+ const EXCERPT_BYTES = 8 * 1024;
494
+
495
+ /**
496
+ * Destroy an abandoned response body. Undici's body emits UND_ERR_ABORTED
497
+ * on the stream's error event when destroyed unconsumed — the destroy is
498
+ * deliberate (the transport is the stream's sole owner), so the error
499
+ * event is swallowed; an unhandled 'error' would crash the process.
500
+ */
501
+ function destroyQuietly(
502
+ stream: Dispatcher.ResponseData["body"] | undefined | null,
503
+ ): void {
504
+ if (!stream) return;
505
+ stream.once("error", () => {});
506
+ stream.destroy();
507
+ }
508
+
509
+ /**
510
+ * Collect a bounded prefix of a response body, then destroy the stream —
511
+ * the transport is the body's sole owner and never leaves it abandoned.
512
+ * Used in sink mode for non-2xx responses: no pipe happens there, but the
513
+ * checkResponseStatus excerpt must still work, so the prefix is decoded
514
+ * by the caller with the negotiated charset.
515
+ */
516
+ async function collectExcerpt(
517
+ body: Dispatcher.ResponseData["body"],
518
+ maxBytes: number = EXCERPT_BYTES,
519
+ ): Promise<Buffer> {
520
+ const chunks: Buffer[] = [];
521
+ let total = 0;
522
+ try {
523
+ for await (const chunk of body) {
524
+ const buf = Buffer.from(chunk);
525
+ chunks.push(buf);
526
+ total += buf.length;
527
+ if (total >= maxBytes) break;
528
+ }
529
+ } finally {
530
+ destroyQuietly(body);
531
+ }
532
+ return Buffer.concat(chunks);
533
+ }
534
+
535
+ /**
536
+ * Streaming decode of the truncated error excerpt. The excerpt is a WIRE
537
+ * prefix (collectExcerpt), so a compressed body is an incomplete stream:
538
+ * sync inflate throws on it and the raw bytes would render as mojibake —
539
+ * exactly when the error body is too large to fit the cap, the server's
540
+ * reason is lost. Streaming inflate recovers whatever the truncated input
541
+ * yields up to the last complete deflate block; the budget counter bounds
542
+ * the decompressed output (also capping a small-wire/large-body gzip
543
+ * bomb). An error after partial output is a pass — the excerpt is what
544
+ * reached the memory sink; zero output rethrows so the caller falls back
545
+ * to the raw prefix (a plain-text body behind a wrong Content-Encoding
546
+ * still renders its reason).
547
+ */
548
+ async function inflateExcerpt(
549
+ prefix: Buffer,
550
+ make: () => Transform,
551
+ ): Promise<Buffer> {
552
+ const chunks: Buffer[] = [];
553
+ const counter = new ByteCountingTransform({
554
+ kind: "budget",
555
+ bytes: EXCERPT_BYTES,
556
+ });
557
+ const sink = new Writable({
558
+ write(chunk, _enc, cb) {
559
+ chunks.push(chunk);
560
+ cb();
561
+ },
562
+ });
563
+ try {
564
+ await pipeline(Readable.from([prefix]), make(), counter, sink);
565
+ } catch (err) {
566
+ if (chunks.length === 0) throw err;
567
+ }
568
+ return Buffer.concat(chunks);
569
+ }
570
+
571
+ /**
572
+ * Decode the sink-mode error excerpt like decompressBody would a complete
573
+ * body, tolerant of the truncation the excerpt cap introduces.
574
+ */
575
+ async function decompressExcerpt(
576
+ prefix: Buffer,
577
+ encoding: string | undefined,
578
+ ): Promise<Buffer> {
579
+ const enc = encoding?.toLowerCase().trim();
580
+ if (!enc || enc === "identity") return prefix;
581
+ // Candidate decoders in decompressBody's sync order — deflate is
582
+ // ambiguous on the wire (zlib-wrapped vs raw), so try both.
583
+ let candidates: Array<() => Transform> = [];
584
+ if (enc === "gzip" || enc === "x-gzip") {
585
+ candidates = [createGunzip];
586
+ } else if (enc === "deflate") {
587
+ candidates = [createInflate, createInflateRaw];
588
+ }
589
+ for (const make of candidates) {
590
+ try {
591
+ // Success returns even when empty — a valid empty body is not a
592
+ // fallback signal. Only a decoder that threw with zero output
593
+ // falls through to the next candidate, then the raw prefix.
594
+ return await inflateExcerpt(prefix, make);
595
+ } catch {
596
+ // next candidate, then the raw fallback
597
+ }
598
+ }
599
+ return prefix;
600
+ }
601
+
602
+ /**
603
+ * Sink-mode pipe: run the response body through the shared
604
+ * decompress/count chain into the caller's writable. Decode policy
605
+ * (fail-closed, sink-specific):
606
+ * gzip/x-gzip via createGunzip, identity/absent as the no-ops they are —
607
+ * any other Content-Encoding was already refused at header time by the
608
+ * caller (the pipe has no parse step to fail loudly, so pass-through of
609
+ * an undecodable body would be silent corruption).
610
+ *
611
+ * Called by fetchToSink outside its request try: a mid-body error (socket
612
+ * reset, sink ENOSPC) surfaces past the retry catch and is terminal — the
613
+ * stream is never re-issued into a partially written sink. pipeline()
614
+ * destroys every stream in the chain on error, including the sink.
615
+ */
616
+ async function pipeBodyToSink(
617
+ bodyStream: Dispatcher.ResponseData["body"],
618
+ headers: Record<string, string>,
619
+ sink: Writable,
620
+ stop?: StopBound,
621
+ ): Promise<void> {
622
+ const counter = new ByteCountingTransform(stop);
623
+ try {
624
+ const enc = headers["content-encoding"]?.toLowerCase().trim();
625
+ const gunzip = enc === "gzip" || enc === "x-gzip" ? createGunzip() : null;
626
+ if (gunzip) {
627
+ await pipeline(bodyStream, gunzip, counter, sink);
628
+ } else {
629
+ await pipeline(bodyStream, counter, sink);
630
+ }
631
+ } catch (err) {
632
+ // A budget stop is a pass, not a failure — the verify probe's evidence.
633
+ if (err instanceof BudgetReachedError) return;
634
+ throw err;
635
+ }
636
+ }
637
+
638
+ /**
639
+ * Charset for body decoding — the Content-Type parameter, else the
640
+ * caller's fallback, else utf-8. Shared by the collect decode and the
641
+ * sink-mode error-excerpt decode.
642
+ */
643
+ function resolveCharset(
644
+ headers: Record<string, string>,
645
+ fallback?: string,
646
+ ): string {
647
+ const match = (headers["content-type"] ?? "").match(
648
+ /charset\s*=\s*([^\s;]+)/i,
649
+ );
650
+ return match?.[1] ?? fallback ?? "utf-8";
651
+ }
652
+
363
653
  function decodeBuffer(buf: Buffer, charset: string): string {
364
654
  const cs = charset.toLowerCase().replace(/[^a-z0-9_-]/g, "");
365
655
  if (cs === "utf-8" || cs === "utf8" || cs === "") {
@@ -422,6 +712,11 @@ function shouldStore(
422
712
  return grantMs > 0 || !!headers["etag"];
423
713
  }
424
714
 
715
+ // A server-supplied Retry-After is honored up to this ceiling — waiting out
716
+ // a large ask (hours on a broken or hostile server) would blow the call's
717
+ // own timeout contract, since the timeout check runs only after the sleep.
718
+ const MAX_RETRY_AFTER_MS = 60_000;
719
+
425
720
  /**
426
721
  * Compute the delay before a retry. Prefers Retry-After: delay-seconds;
427
722
  * falls back to parsing an HTTP-date form. If the date is in the past
@@ -435,61 +730,212 @@ export function waitForRetry(
435
730
  const raw = headers["retry-after"];
436
731
  if (raw) {
437
732
  const secs = parseInt(raw, 10);
438
- if (!Number.isNaN(secs) && secs > 0) return secs * 1000;
733
+ if (!Number.isNaN(secs) && secs > 0) {
734
+ return Math.min(secs * 1000, MAX_RETRY_AFTER_MS);
735
+ }
439
736
  const dateMs = Date.parse(raw);
440
737
  if (!Number.isNaN(dateMs)) {
441
738
  const delta = dateMs - Date.now();
442
- if (delta > 0) return delta;
739
+ if (delta > 0) return Math.min(delta, MAX_RETRY_AFTER_MS);
443
740
  }
444
741
  }
445
742
  // Exponential backoff: 1s, 2s, 4s, …
446
743
  return Math.min(1000 * 2 ** attempt, 30_000);
447
744
  }
448
745
 
746
+ // Abortable: a cancelled call preempts its own backoff instead of waiting
747
+ // it out (timers/promises rejects with AbortError and clears the timer).
748
+ const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>
749
+ setTimeoutP(ms, undefined, { signal });
750
+
449
751
  /**
450
- * One GET request with its own abort timer. Returns status, parsed headers,
451
- * and the raw collected body. Redirects are NOT followed here — the caller
452
- * decides whether to follow and guard them.
752
+ * Shared retry-or-throw for both fetch modes' request-phase catch: sleeps
753
+ * the exponential backoff and returns when the error is transient and
754
+ * retries remain; rethrows otherwise. Timeouts/aborts, oversized bodies,
755
+ * SSRF blocks, and header-time refusals are never transient — a re-issued
756
+ * request cannot succeed.
453
757
  */
454
- async function singleGet(
455
- url: string,
456
- reqHeaders: Record<string, string>,
457
- timeoutMs: number,
458
- dispatcher: Dispatcher,
459
- ): Promise<{
758
+ async function retryOrThrow(
759
+ err: unknown,
760
+ attempt: number,
761
+ maxRetries: number,
762
+ signal?: AbortSignal,
763
+ ): Promise<void> {
764
+ const e = err instanceof Error ? err : new Error(String(err));
765
+ const transient =
766
+ e.name !== "AbortError" &&
767
+ e.name !== "BodyTooLargeError" &&
768
+ e.name !== "SsrfBlockedError" &&
769
+ e.name !== "TransportRefusalError" &&
770
+ (e as NodeJS.ErrnoException).code !== "UND_ERR_ABORTED";
771
+ if (attempt < maxRetries && transient) {
772
+ await sleep(Math.min(1000 * 2 ** attempt, 30_000), signal);
773
+ return;
774
+ }
775
+ throw e;
776
+ }
777
+
778
+ /**
779
+ * One attempt's outcome for the shared retry driver: ask for another
780
+ * attempt after `delayMs`, or hand back the final per-attempt result.
781
+ */
782
+ type AttemptOutcome<T> =
783
+ | { kind: "retry"; delayMs: number }
784
+ | { kind: "done"; value: T };
785
+
786
+ /**
787
+ * Shared retry driver for both fetch modes. Owns the attempt loop: the
788
+ * total-timeout deadline check, the request-phase catch (`retryOrThrow`),
789
+ * and the retry sleep (abortable — a cancelled call preempts its own
790
+ * backoff). The callback performs one attempt's request phase and either
791
+ * asks for a retry (mode-specific teardown happens there — sink destroys
792
+ * its live stream before asking) or hands back the final outcome.
793
+ * Everything a mode does after the request phase (decode, cache, pipe)
794
+ * runs on the returned outcome, outside the driver's catch: those
795
+ * failures are terminal — never re-issued (a mid-body write must not
796
+ * resume into a partially written sink; a decode failure cannot be
797
+ * fixed by fetching the same bytes again).
798
+ */
799
+ async function runAttempts<T>(
800
+ args: {
801
+ startTime: number;
802
+ timeout: number;
803
+ maxRetries: number;
804
+ signal?: AbortSignal | undefined;
805
+ },
806
+ attemptFn: (
807
+ attempt: number,
808
+ remainingMs: number,
809
+ ) => Promise<AttemptOutcome<T>>,
810
+ ): Promise<T> {
811
+ for (let attempt = 0; ; attempt++) {
812
+ const remaining = args.timeout - (Date.now() - args.startTime);
813
+ if (remaining <= 0) throw new Error("Request timeout");
814
+ let outcome: AttemptOutcome<T>;
815
+ try {
816
+ outcome = await attemptFn(attempt, remaining);
817
+ } catch (err) {
818
+ await retryOrThrow(err, attempt, args.maxRetries, args.signal);
819
+ continue;
820
+ }
821
+ if (outcome.kind === "retry") {
822
+ await sleep(outcome.delayMs, args.signal);
823
+ continue;
824
+ }
825
+ return outcome.value;
826
+ }
827
+ }
828
+
829
+ /**
830
+ * One request outcome — a discriminated union. Collect mode carries the
831
+ * buffered, still-compressed body; sink mode carries the undici body
832
+ * stream, returned after headers (the caller pipes it into the sink or
833
+ * destroys it; it is never left abandoned). Exactly one variant is ever
834
+ * produced per request; the `kind` tag lets the compiler enforce which
835
+ * fields exist in which mode.
836
+ */
837
+ interface CollectOutcome {
838
+ kind: "collect";
460
839
  status: number;
461
840
  headers: Record<string, string>;
462
841
  rawBody: Buffer;
463
842
  finalUrl: string;
464
- }> {
465
- if (timeoutMs <= 0) throw new Error("Request timeout");
843
+ }
844
+
845
+ interface SinkOutcome {
846
+ kind: "sink";
847
+ status: number;
848
+ headers: Record<string, string>;
849
+ bodyStream: Dispatcher.ResponseData["body"];
850
+ finalUrl: string;
851
+ }
852
+
853
+ type RequestOutcome = CollectOutcome | SinkOutcome;
854
+
855
+ interface SingleGetArgs {
856
+ url: string;
857
+ headers: Record<string, string>;
858
+ /** Milliseconds for this request's abort timer (time-to-headers scope). */
859
+ timeoutMs: number;
860
+ dispatcher: Dispatcher;
861
+ /** Sink mode: return the live body stream un-collected, headers-only. */
862
+ sinkMode?: boolean | undefined;
863
+ signal?: AbortSignal | undefined;
864
+ }
865
+
866
+ /**
867
+ * One GET request with its own abort timer. Returns status, parsed headers,
868
+ * and — collect mode — the raw collected body, or — sink mode — the body
869
+ * stream itself, returned immediately after headers (the abort timer is
870
+ * cleared on return, so it covers time-to-headers only; a multi-minute
871
+ * body transfer must not die at the total timeout — mid-body stalls are
872
+ * undici's bodyTimeout, not this timer). Redirects are NOT followed here —
873
+ * the caller decides whether to follow and guard them.
874
+ */
875
+ async function requestOnce(args: SingleGetArgs): Promise<RequestOutcome> {
876
+ if (args.timeoutMs <= 0) throw new Error("Request timeout");
466
877
  const ac = new AbortController();
467
878
  const timer = setTimeout(
468
879
  () => ac.abort(new Error("Request timeout")),
469
- timeoutMs,
880
+ args.timeoutMs,
470
881
  );
882
+ // Compose the caller's cancellation signal with the timeout controller:
883
+ // either aborting kills the request (connect, redirect hops, and the
884
+ // mid-body stream alike — undici releases the socket).
885
+ const abortSignal = args.signal
886
+ ? AbortSignal.any([ac.signal, args.signal])
887
+ : ac.signal;
471
888
  try {
472
- const resp = await request(url, {
889
+ const resp = await request(args.url, {
473
890
  method: "GET",
474
- headers: reqHeaders,
475
- signal: ac.signal,
476
- dispatcher,
891
+ headers: args.headers,
892
+ signal: abortSignal,
893
+ dispatcher: args.dispatcher,
477
894
  });
478
895
  // The redirect interceptor records the hop chain in context.history;
479
896
  // its last entry is where the response actually came from. No history
480
897
  // (no interceptor / no redirect) means the URL is unchanged.
481
898
  const history = (resp.context as { history?: URL[] } | null)?.history;
899
+ const finalUrl = history?.at(-1) ? String(history.at(-1)) : args.url;
900
+ if (args.sinkMode) {
901
+ // Headers-only: hand the body stream back un-collected. The timer's
902
+ // finally below runs on return — before the caller pipes — so the
903
+ // total timeout never governs the body transfer.
904
+ return {
905
+ kind: "sink",
906
+ status: resp.statusCode,
907
+ headers: parseHeaders(resp.headers),
908
+ bodyStream: resp.body,
909
+ finalUrl,
910
+ };
911
+ }
482
912
  return {
913
+ kind: "collect",
483
914
  status: resp.statusCode,
484
915
  headers: parseHeaders(resp.headers),
485
916
  rawBody: await collectBody(resp.body),
486
- finalUrl: history?.at(-1) ? String(history.at(-1)) : url,
917
+ finalUrl,
487
918
  };
488
919
  } finally {
489
920
  clearTimeout(timer);
490
921
  }
491
922
  }
492
923
 
924
+ /**
925
+ * Mode-static wrappers over requestOnce: a call site's sinkMode decides the
926
+ * outcome type, so callers never narrow the union at runtime (mirrors the
927
+ * redirect loop's overloads).
928
+ */
929
+ function singleGet(
930
+ args: SingleGetArgs & { sinkMode: true },
931
+ ): Promise<SinkOutcome>;
932
+ function singleGet(
933
+ args: SingleGetArgs & { sinkMode?: false | undefined },
934
+ ): Promise<CollectOutcome>;
935
+ async function singleGet(args: SingleGetArgs): Promise<RequestOutcome> {
936
+ return requestOnce(args);
937
+ }
938
+
493
939
  /** Host of a URL, or null when unparseable — treated as cross-domain (strip). */
494
940
  function hostOf(url: string): string | null {
495
941
  try {
@@ -531,7 +977,7 @@ export function stripSecretQueryParams(
531
977
  ): string {
532
978
  if (!secretQueryParamNames || secretQueryParamNames.size === 0) return url;
533
979
  // ponytail: URL() throws on malformed input; pass through unmodified —
534
- // singleGet will surface the real fetch error anyway.
980
+ // requestOnce will surface the real fetch error anyway.
535
981
  let u: URL;
536
982
  try {
537
983
  u = new URL(url);
@@ -548,28 +994,58 @@ export function stripSecretQueryParams(
548
994
  return changed ? u.toString() : url;
549
995
  }
550
996
 
997
+ interface RedirectLoopArgs {
998
+ url: string;
999
+ headers: Record<string, string>;
1000
+ /** Run start (epoch ms from Date.now()) — each hop's remaining timeout. */
1001
+ startTime: number;
1002
+ timeoutMs: number;
1003
+ guardHops: boolean;
1004
+ /** Sink mode: return the final hop's live body stream un-collected. */
1005
+ sinkMode?: boolean | undefined;
1006
+ signal?: AbortSignal | undefined;
1007
+ secretHeaderNames?: Set<string> | undefined;
1008
+ secretQueryParamNames?: Set<string> | undefined;
1009
+ redactPathSecret?: ((url: string) => string) | undefined;
1010
+ }
1011
+
551
1012
  /**
552
- * Follow redirects manually, SSRF-checking each target. Used for
553
- * server-supplied URLs (paginate nextLink) and — forced — any auth-bearing
554
- * request. GET-only, so method is preserved across 301/302/303/307/308
555
- * trivially. Returns the final response; a redirect to a blocked host
556
- * throws before it is fetched. Store-injected secrets are stripped on
557
- * cross-domain hops so a key can't attach to a different host.
1013
+ * Follow redirects manually. GET-only, so method is preserved across
1014
+ * 301/302/303/307/308 trivially. Returns the final response; a redirect to
1015
+ * a blocked host throws before it is fetched — but only when `guardHops`
1016
+ * is set: the guard's contract scopes it to server-supplied URLs and
1017
+ * auth-bearing requests (`guardRedirects || hasAuth`). Sink mode forces
1018
+ * this loop for hop-drain discipline WITHOUT extending the guard — a
1019
+ * credential-free download may follow a redirect to a private host exactly
1020
+ * as undici's auto-redirect would have. Store-injected secrets are
1021
+ * stripped on cross-domain hops unconditionally (a no-op on the empty
1022
+ * secret sets a no-auth call carries) so a key can't attach to a different
1023
+ * host. In sink mode each abandoned redirect hop's body is destroyed
1024
+ * before the loop continues — undici holds the socket otherwise. The two
1025
+ * overloads keep mode-static call sites (sink vs collect) precisely typed
1026
+ * while the single union-returning implementation runs either mode.
558
1027
  */
1028
+ function getWithGuardedRedirects(
1029
+ args: RedirectLoopArgs & { sinkMode: true },
1030
+ ): Promise<SinkOutcome>;
1031
+ function getWithGuardedRedirects(
1032
+ args: RedirectLoopArgs & { sinkMode?: false | undefined },
1033
+ ): Promise<CollectOutcome>;
559
1034
  async function getWithGuardedRedirects(
560
- url: string,
561
- reqHeaders: Record<string, string>,
562
- startTime: number,
563
- timeoutMs: number,
564
- secretHeaderNames?: Set<string>,
565
- secretQueryParamNames?: Set<string>,
566
- redactPathSecret?: (url: string) => string,
567
- ): Promise<{
568
- status: number;
569
- headers: Record<string, string>;
570
- rawBody: Buffer;
571
- finalUrl: string;
572
- }> {
1035
+ args: RedirectLoopArgs,
1036
+ ): Promise<RequestOutcome> {
1037
+ const {
1038
+ url,
1039
+ headers: reqHeaders,
1040
+ startTime,
1041
+ timeoutMs,
1042
+ guardHops,
1043
+ sinkMode,
1044
+ signal,
1045
+ secretHeaderNames,
1046
+ secretQueryParamNames,
1047
+ redactPathSecret,
1048
+ } = args;
573
1049
  let current = url;
574
1050
  const originalHost = hostOf(url);
575
1051
  for (let hops = 0; hops <= MAX_REDIRECTS; hops++) {
@@ -589,22 +1065,35 @@ async function getWithGuardedRedirects(
589
1065
  if (redactPathSecret) hopUrl = redactPathSecret(hopUrl);
590
1066
  }
591
1067
  const remaining = timeoutMs - (Date.now() - startTime);
592
- const res = await singleGet(hopUrl, hopHeaders, remaining, noRedirectAgent);
1068
+ const res = await requestOnce({
1069
+ url: hopUrl,
1070
+ headers: hopHeaders,
1071
+ timeoutMs: remaining,
1072
+ dispatcher: noRedirectAgent,
1073
+ sinkMode,
1074
+ signal,
1075
+ });
593
1076
  const isRedirect =
594
1077
  res.status >= 300 && res.status < 400 && res.status !== 304;
595
1078
  if (!isRedirect || hops === MAX_REDIRECTS) return res;
596
1079
  const loc = res.headers["location"];
597
1080
  if (!loc) return res; // redirect with no Location — return as-is
1081
+ // This hop's body is abandoned — destroy it before continuing; in sink
1082
+ // mode the stream would otherwise hold the socket (collect mode's
1083
+ // requestOnce already consumed it).
1084
+ if (res.kind === "sink") destroyQuietly(res.bodyStream);
598
1085
  // Resolve against hopUrl, not current — a relative redirect inherits
599
1086
  // the base's query string, and current still carries the secret params
600
1087
  // that were just stripped for this hop's fetch.
601
1088
  const next = new URL(loc, hopUrl).toString();
602
- const guard = ssrfGuard(next);
603
- if (!guard.ok) {
604
- // Security-control failure is not transient — don't retry.
605
- const err = new Error(`Redirect to blocked host: ${guard.reason}`);
606
- err.name = "SsrfBlockedError";
607
- throw err;
1089
+ if (guardHops) {
1090
+ const guard = ssrfGuard(next);
1091
+ if (!guard.ok) {
1092
+ // Security-control failure is not transient — don't retry.
1093
+ const err = new Error(`Redirect to blocked host: ${guard.reason}`);
1094
+ err.name = "SsrfBlockedError";
1095
+ throw err;
1096
+ }
608
1097
  }
609
1098
  current = next;
610
1099
  }
@@ -646,14 +1135,34 @@ async function getWithGuardedRedirects(
646
1135
  * - Other 4xx/5xx status codes are returned as-is without retry.
647
1136
  *
648
1137
  * Network errors (DNS, connection refused, timeout) are thrown.
1138
+ *
1139
+ * Sink mode (`opts.sink` set) dispatches to `fetchToSink` instead: the
1140
+ * body streams into the caller-supplied writable — no cache interaction,
1141
+ * and a mid-body failure is terminal.
649
1142
  */
650
1143
  export async function fetchUrl(
651
1144
  url: string,
652
1145
  opts?: FetchOptions,
653
1146
  ): Promise<FetchResult> {
654
- const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;
655
- const maxRetries = opts?.maxRetries ?? DEFAULT_MAX_RETRIES;
1147
+ if (opts?.sink) return fetchToSink(url, opts, opts.sink);
1148
+ return fetchCollect(url, opts);
1149
+ }
656
1150
 
1151
+ /**
1152
+ * Shared request prologue for both fetch modes: auth classification, the
1153
+ * redirect-loop gate, cache key, and request headers (User-Agent default).
1154
+ * The cache lookups (fresh hit, If-None-Match) live in fetchCollect's own
1155
+ * body — sink mode has no cache interaction at all.
1156
+ */
1157
+ function prepareRequest(
1158
+ url: string,
1159
+ opts?: FetchOptions,
1160
+ ): {
1161
+ hasAuth: boolean;
1162
+ guardHops: boolean;
1163
+ key: string;
1164
+ reqHeaders: Record<string, string>;
1165
+ } {
657
1166
  // Responses to requests carrying caller-specific headers (auth keys,
658
1167
  // tokens, …) are private to that caller — never cache or reuse them.
659
1168
  // Only the Accept header (content negotiation) is cache-shareable, and
@@ -672,22 +1181,163 @@ export async function fetchUrl(
672
1181
  hasAuthHeaders ||
673
1182
  (opts?.hasQuerySecret ?? false) ||
674
1183
  (opts?.hasPathSecret ?? false);
675
-
676
- // ── cache hit ───────────────────────────────────────────────
677
- const key = cacheKey(url, opts);
678
- if (!opts?.fresh && !hasAuth) {
679
- const entry = cache.get(key);
680
- if (entry && _now() < entry.expiresAt) {
681
- return { status: 200, headers: {}, body: entry.body, cached: true };
682
- }
683
- }
684
-
685
- // ── request headers ─────────────────────────────────────────
686
1184
  const reqHeaders: Record<string, string> = { ...opts?.headers };
687
1185
  if (!reqHeaders["user-agent"]) {
688
1186
  reqHeaders["user-agent"] =
689
1187
  `pi-lean-host/${HOST_UA_VERSION} (+https://github.com/coreyryanhanson/pi-lean-dimension)`;
690
1188
  }
1189
+ return {
1190
+ hasAuth,
1191
+ guardHops: (opts?.guardRedirects ?? false) || hasAuth,
1192
+ key: cacheKey(url, opts),
1193
+ reqHeaders,
1194
+ };
1195
+ }
1196
+
1197
+ /**
1198
+ * Sink-mode fetch (download transfers): the caller supplied a writable, so
1199
+ * the request rides the manual redirect loop — hop-drain discipline is
1200
+ * enforceable only in code this module owns (undici's auto-redirect
1201
+ * interceptor follows hops invisibly, leaving intermediate bodies
1202
+ * undisposed). Forcing the loop is a DRAIN decision, not a guard decision:
1203
+ * the per-hop SSRF check keeps its own contract (server-supplied targets
1204
+ * and auth-bearing requests) — a credential-free download that redirects
1205
+ * to a private host follows it exactly as undici's auto-redirect would.
1206
+ * The cache arms are all skipped (a sink-mode response has no collected
1207
+ * body: nothing to store, nothing to serve).
1208
+ *
1209
+ * Everything after the request phase runs outside the retry driver's
1210
+ * catch (see runAttempts): a mid-body error (socket reset, sink ENOSPC,
1211
+ * any future stream error) is terminal — the stream is never re-issued
1212
+ * into a partially written sink.
1213
+ */
1214
+ async function fetchToSink(
1215
+ url: string,
1216
+ opts: FetchOptions,
1217
+ sink: Writable,
1218
+ ): Promise<FetchResult> {
1219
+ const timeout = opts.timeout ?? DEFAULT_TIMEOUT;
1220
+ const maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES;
1221
+ const { guardHops, reqHeaders } = prepareRequest(url, opts);
1222
+ const stop = opts.stop;
1223
+ const startTime = Date.now();
1224
+
1225
+ const final = await runAttempts<SinkOutcome>(
1226
+ { startTime, timeout, maxRetries, signal: opts.signal },
1227
+ async (attempt) => {
1228
+ const res = await getWithGuardedRedirects({
1229
+ url,
1230
+ headers: reqHeaders,
1231
+ startTime,
1232
+ timeoutMs: timeout,
1233
+ guardHops,
1234
+ sinkMode: true,
1235
+ signal: opts.signal,
1236
+ secretHeaderNames: opts.secretHeaderNames,
1237
+ secretQueryParamNames: opts.secretQueryParamNames,
1238
+ redactPathSecret: opts.redactPathSecret,
1239
+ });
1240
+ // 429 is pre-body (status known at headers): destroy the abandoned
1241
+ // attempt's body — undici holds the socket otherwise — then retry.
1242
+ if (res.status === 429 && attempt < maxRetries) {
1243
+ destroyQuietly(res.bodyStream);
1244
+ return { kind: "retry", delayMs: waitForRetry(res.headers, attempt) };
1245
+ }
1246
+ return { kind: "done", value: res };
1247
+ },
1248
+ );
1249
+
1250
+ // Everything below runs once, on the final attempt's outcome, outside
1251
+ // the retry driver's catch — terminal by construction.
1252
+ // Explicit 2xx window — the transport's mechanical mirror of the
1253
+ // executor's status gate: pipe only on 2xx, so a 304 or a terminal
1254
+ // 3xx with no Location is never written to the sink.
1255
+ if (final.status >= 200 && final.status < 300) {
1256
+ // Header-time decode refusal — the pipe has no parse step to fail
1257
+ // loudly, so an undecodable body must never start flowing
1258
+ // (pass-through would be silent corruption: a br body written as
1259
+ // "the file", bytes reporting the wrong length). Thrown directly:
1260
+ // evaluated from headers alone, a retry can never succeed.
1261
+ const enc = final.headers["content-encoding"]?.toLowerCase().trim();
1262
+ if (enc && enc !== "identity" && enc !== "gzip" && enc !== "x-gzip") {
1263
+ destroyQuietly(final.bodyStream);
1264
+ throw new TransportRefusalError(
1265
+ "contentEncoding",
1266
+ `Content-Encoding '${enc}' is not supported for downloads (supported: gzip, identity, none)`,
1267
+ );
1268
+ }
1269
+ // Content-Length preflight — refuse an oversized cap run at header
1270
+ // time, before any byte is written (skip conditions per the
1271
+ // FetchOptions.stop contract: compressed bodies, budget runs).
1272
+ const clRaw = final.headers["content-length"];
1273
+ const clBytes = clRaw === undefined ? NaN : Number(clRaw);
1274
+ if (
1275
+ stop?.kind === "cap" &&
1276
+ (!enc || enc === "identity") &&
1277
+ clRaw !== undefined &&
1278
+ Number.isFinite(clBytes) &&
1279
+ clBytes > stop.bytes
1280
+ ) {
1281
+ destroyQuietly(final.bodyStream);
1282
+ throw new TransportRefusalError(
1283
+ "lengthOverCap",
1284
+ `Content-Length ${clRaw} exceeds the effective download cap of ${stop.bytes} bytes`,
1285
+ );
1286
+ }
1287
+ await pipeBodyToSink(final.bodyStream, final.headers, sink, stop);
1288
+ return {
1289
+ status: final.status,
1290
+ headers: final.headers,
1291
+ body: "",
1292
+ cached: false,
1293
+ ...(final.finalUrl === url ? {} : { finalUrl: final.finalUrl }),
1294
+ };
1295
+ }
1296
+ // Non-2xx: no pipe — collect the capped error excerpt (decoded with
1297
+ // the negotiated charset so checkResponseStatus's rendering keeps its
1298
+ // reason) and return it. The excerpt is a bounded collect, so the
1299
+ // abandoned body never outlives this arm.
1300
+ const prefix = await collectExcerpt(final.bodyStream);
1301
+ const charset = resolveCharset(final.headers, opts.fallbackCharset);
1302
+ return {
1303
+ status: final.status,
1304
+ headers: final.headers,
1305
+ body: decodeBuffer(
1306
+ await decompressExcerpt(prefix, final.headers["content-encoding"]),
1307
+ charset,
1308
+ ),
1309
+ cached: false,
1310
+ ...(final.finalUrl === url ? {} : { finalUrl: final.finalUrl }),
1311
+ };
1312
+ }
1313
+
1314
+ /**
1315
+ * Collect-mode fetch (the default): buffered body, grant-based cache, ETag
1316
+ * revalidation, 429 retry. See fetchUrl for the behaviour contract.
1317
+ */
1318
+ async function fetchCollect(
1319
+ url: string,
1320
+ opts?: FetchOptions,
1321
+ ): Promise<FetchResult> {
1322
+ const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;
1323
+ const maxRetries = opts?.maxRetries ?? DEFAULT_MAX_RETRIES;
1324
+ const { hasAuth, guardHops, key, reqHeaders } = prepareRequest(url, opts);
1325
+
1326
+ // ── cache hit ───────────────────────────────────────────────
1327
+ // One cache read serves both arms (fresh hit and If-None-Match) — the
1328
+ // map can't change between them in this synchronous pass.
1329
+ const cachedEntry = !opts?.fresh && !hasAuth ? cache.get(key) : undefined;
1330
+ if (cachedEntry && _now() < cachedEntry.expiresAt) {
1331
+ return {
1332
+ status: 200,
1333
+ headers: {},
1334
+ body: cachedEntry.body,
1335
+ cached: true,
1336
+ ...(cachedEntry.finalUrl === undefined
1337
+ ? {}
1338
+ : { finalUrl: cachedEntry.finalUrl }),
1339
+ };
1340
+ }
691
1341
 
692
1342
  // The entry being revalidated, captured at If-None-Match time. The 304
693
1343
  // arm reads this instead of re-fetching the map: a concurrent caller's
@@ -696,131 +1346,113 @@ export async function fetchUrl(
696
1346
  // 304's empty body as the response.
697
1347
  let revalidate: CacheEntry | undefined;
698
1348
 
699
- if (!opts?.fresh && !hasAuth) {
700
- const entry = cache.get(key);
701
- if (entry?.etag) {
702
- reqHeaders["If-None-Match"] = entry.etag;
703
- revalidate = entry;
704
- }
1349
+ if (cachedEntry?.etag) {
1350
+ reqHeaders["If-None-Match"] = cachedEntry.etag;
1351
+ revalidate = cachedEntry;
705
1352
  }
706
1353
 
707
1354
  const startTime = Date.now();
708
1355
 
709
- for (let attempt = 0; ; attempt++) {
710
- const remaining = timeout - (Date.now() - startTime);
711
- if (remaining <= 0) throw new Error("Request timeout");
712
-
713
- try {
714
- // Guarded redirects when explicitly requested (server-supplied
715
- // nextLink) OR when the request is auth-bearing (hasAuth) — a keyed
716
- // call is always SSRF-checked hop-by-hop and its secrets stripped on
717
- // cross-domain redirects. Otherwise let undici auto-follow up to 5.
718
- const useGuarded = (opts?.guardRedirects ?? false) || hasAuth;
719
- const {
720
- status,
721
- headers: respHeaders,
722
- rawBody,
723
- finalUrl,
724
- } = useGuarded
725
- ? await getWithGuardedRedirects(
1356
+ const final = await runAttempts<CollectOutcome>(
1357
+ { startTime, timeout, maxRetries, signal: opts?.signal },
1358
+ async (attempt, remainingMs) => {
1359
+ const res = guardHops
1360
+ ? await getWithGuardedRedirects({
726
1361
  url,
727
- reqHeaders,
1362
+ headers: reqHeaders,
728
1363
  startTime,
729
- timeout,
730
- opts?.secretHeaderNames,
731
- opts?.secretQueryParamNames,
732
- opts?.redactPathSecret,
733
- )
734
- : await singleGet(url, reqHeaders, remaining, redirectAgent);
735
-
736
- // ── 304 Not Modified ────────────────────────────────
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);
745
- if (entry) {
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
- }
760
- return {
761
- status: 200,
762
- headers: respHeaders,
763
- body: entry.body,
764
- cached: true,
765
- ...(finalUrl === url ? {} : { finalUrl }),
766
- };
767
- }
768
- // No cached entry → fall through to process body.
769
- }
1364
+ timeoutMs: timeout,
1365
+ guardHops,
1366
+ signal: opts?.signal,
1367
+ secretHeaderNames: opts?.secretHeaderNames,
1368
+ secretQueryParamNames: opts?.secretQueryParamNames,
1369
+ redactPathSecret: opts?.redactPathSecret,
1370
+ })
1371
+ : await singleGet({
1372
+ url,
1373
+ headers: reqHeaders,
1374
+ timeoutMs: remainingMs,
1375
+ dispatcher: redirectAgent,
1376
+ signal: opts?.signal,
1377
+ });
770
1378
 
771
- // ── 429 Too Many Requests ───────────────────────────
772
- if (status === 429 && attempt < maxRetries) {
773
- const delay = waitForRetry(respHeaders, attempt);
774
- await new Promise((r) => setTimeout(r, delay));
775
- continue; // retry
1379
+ if (res.status === 429 && attempt < maxRetries) {
1380
+ // The body is already buffered here; nothing to destroy — sink
1381
+ // mode is the arm that must tear down its live stream first.
1382
+ return { kind: "retry", delayMs: waitForRetry(res.headers, attempt) };
776
1383
  }
1384
+ return { kind: "done", value: res };
1385
+ },
1386
+ );
777
1387
 
778
- // ── decode & cache (2xx only) ───────────────────────
779
- const contentType = respHeaders["content-type"] ?? "";
780
- const charsetMatch = contentType.match(/charset\s*=\s*([^\s;]+)/i);
781
- const charset = charsetMatch?.[1] ?? opts?.fallbackCharset ?? "utf-8";
782
- const body = decodeBuffer(
783
- decompressBody(rawBody, respHeaders["content-encoding"]),
784
- charset,
785
- );
1388
+ // Everything below runs once, on the final attempt's outcome, outside
1389
+ // the retry driver's catch — terminal by construction: decode and cache
1390
+ // failures cannot be fixed by re-issuing the request.
1391
+ const { status, headers: respHeaders, rawBody, finalUrl } = final;
786
1392
 
787
- if (status >= 200 && status < 300 && !hasAuth) {
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
- }
1393
+ // ── 304 Not Modified ────────────────────────────────
1394
+ // Gated on !hasAuth like every other cache arm: a keyed request must
1395
+ // never be served a body cached by an unauthenticated caller, even
1396
+ // from a protocol-violating server that sends a spontaneous 304.
1397
+ // Also gated on !fresh for the same reason: a fresh request must not
1398
+ // receive a cached body, so an unsolicited 304 falls through to the
1399
+ // status check instead.
1400
+ if (status === 304 && !hasAuth && !opts?.fresh) {
1401
+ const entry = revalidate ?? cache.get(key);
1402
+ if (entry) {
1403
+ if (/no-store/i.test(respHeaders["cache-control"] ?? "")) {
1404
+ // A no-store revalidation result must not be stored.
1405
+ cache.delete(key);
1406
+ } else {
1407
+ // Refresh from the 304's own effective grant; fall back to the
1408
+ // grant currently recorded on the entry (a granted entry must
1409
+ // not degrade to revalidate-only when the 304 carries no
1410
+ // max-age), and re-stamp it so the newest grant sticks.
1411
+ const grant304 = effectiveGrant(respHeaders) ?? entry.grantMs;
1412
+ entry.grantMs = grant304;
1413
+ entry.expiresAt = _now() + grant304;
1414
+ // The entry object is mutated in place — cache.get returned the
1415
+ // live reference, so no re-set is needed.
800
1416
  }
801
-
802
1417
  return {
803
- status,
1418
+ status: 200,
804
1419
  headers: respHeaders,
805
- body,
806
- cached: false,
1420
+ body: entry.body,
1421
+ cached: true,
807
1422
  ...(finalUrl === url ? {} : { finalUrl }),
808
1423
  };
809
- } catch (err) {
810
- const e = err instanceof Error ? err : new Error(String(err));
811
- // Don't retry on timeout/abort, oversized bodies, or SSRF
812
- // blocks — none are transient.
813
- const transient =
814
- e.name !== "AbortError" &&
815
- e.name !== "BodyTooLargeError" &&
816
- e.name !== "SsrfBlockedError" &&
817
- (e as NodeJS.ErrnoException).code !== "UND_ERR_ABORTED";
818
- if (attempt < maxRetries && transient) {
819
- const delay = Math.min(1000 * 2 ** attempt, 30_000);
820
- await new Promise((r) => setTimeout(r, delay));
821
- continue;
822
- }
823
- throw e;
824
1424
  }
1425
+ // No cached entry → fall through to process body.
825
1426
  }
1427
+
1428
+ // ── decode & cache (2xx only) ───────────────────────
1429
+ const charset = resolveCharset(respHeaders, opts?.fallbackCharset);
1430
+ const body = decodeBuffer(
1431
+ decompressBody(rawBody, respHeaders["content-encoding"]),
1432
+ charset,
1433
+ );
1434
+
1435
+ if (status >= 200 && status < 300 && !hasAuth) {
1436
+ const grantMs = effectiveGrant(respHeaders) ?? 0;
1437
+ if (shouldStore(respHeaders, grantMs)) {
1438
+ const entry: CacheEntry = {
1439
+ body,
1440
+ expiresAt: _now() + grantMs,
1441
+ grantMs,
1442
+ };
1443
+ const etag = respHeaders["etag"];
1444
+ if (etag) entry.etag = etag;
1445
+ if (finalUrl !== url) entry.finalUrl = finalUrl;
1446
+ evictCacheIfNeeded();
1447
+ cache.set(key, entry);
1448
+ }
1449
+ }
1450
+
1451
+ return {
1452
+ status,
1453
+ headers: respHeaders,
1454
+ body,
1455
+ cached: false,
1456
+ ...(finalUrl === url ? {} : { finalUrl }),
1457
+ };
826
1458
  }