@iso4/fetch 0.0.1 → 0.1.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 CHANGED
@@ -65,8 +65,8 @@ npm i @iso4/sandbox @iso4/fetch
65
65
 
66
66
  ## Rules
67
67
 
68
- Every request must match a declared rule before any middleware runs or any
69
- network call is made. Unmatched requests are denied immediately.
68
+ Every request must match a declared rule before any middleware runs.
69
+ Unmatched requests are denied immediately.
70
70
 
71
71
  ```ts
72
72
  const fetch = createSafeFetch({
@@ -120,6 +120,33 @@ createSafeFetch({
120
120
  })
121
121
  ```
122
122
 
123
+ The rules are matched once, on the agent's original URL — that match runs the
124
+ allow/deny + SSRF checks and picks the middleware pipeline and `params`. The
125
+ three layers then wrap the HTTP call, sharing one `ctx.req`:
126
+
127
+ ```
128
+ agent request
129
+ │
130
+ ▼
131
+ match rules ──────────── once, on the original URL
132
+ │ allow/deny · SSRF · picks middleware + params
133
+ ▼
134
+ global → origin → route mutate ctx.req (header/setUrl/setBody)
135
+ │ setUrl retargets but is NOT re-checked
136
+ ▼
137
+ HTTP request → redirects each redirect hop IS re-checked
138
+ │
139
+ ▼
140
+ route → origin → global unwind; may read or rewrite the response
141
+ │
142
+ ▼
143
+ response
144
+ ```
145
+
146
+ `setUrl` is a trusted retarget: it changes the outgoing URL without re-running
147
+ the rules, and the pipeline and `params` stay fixed to the original route.
148
+ Validate a URL built from agent-influenced data before passing it to `setUrl`.
149
+
123
150
  ### Request mutation (auth, URL rewrite, headers)
124
151
 
125
152
  ```ts
@@ -134,6 +161,17 @@ async function someRequestMiddleware(ctx, next) {
134
161
  or `header(name, val)`), `body` (via `setBody()`), `params`, `hop`, `raw`
135
162
  (original unmodified bridge request).
136
163
 
164
+ > **Header content is not re-validated by iso4.** iso4 does not guarantee that
165
+ > header names and values crossing the sandbox boundary are well-formed. On the
166
+ > normal path this is safe: a Request or Response is reconstructed host-side
167
+ > through Node's `undici`, which rejects CR/LF in header values, invalid names
168
+ > and methods, and URL credentials — so a malformed header fails the run before
169
+ > it reaches the network (see
170
+ > `packages/iso4-sandbox/tests/web-types.test.ts`, "smuggled past sandbox
171
+ > validation"). If your middleware pulls `ctx.req.headers` out and forwards them
172
+ > to something other than undici (a raw socket, a log line, another HTTP
173
+ > client), validate the names and values yourself first.
174
+
137
175
  ### Response inspection / logging
138
176
 
139
177
  ```ts
@@ -177,9 +215,9 @@ matches, or is the sole mechanism when `rules` is omitted.
177
215
 
178
216
  ```ts
179
217
  createSafeFetch({
180
- policy: async ({ host, method, resolvedIp }) => {
181
- if (resolvedIp && isInternal(resolvedIp))
182
- return false
218
+ // Private/reserved IPs are refused automatically at connection time, so the
219
+ // policy only needs to decide on host/method/path.
220
+ policy: async ({ host, method }) => {
183
221
  const tenant = await db.findByHost(host)
184
222
  return tenant?.allowedMethods.includes(method) ?? false
185
223
  },
@@ -189,17 +227,56 @@ return false
189
227
  `policy` runs only when no `rules` origin matched. If an origin matches but
190
228
  no route does the request is denied without consulting `policy`.
191
229
 
230
+ ## Host-side fetch
231
+
232
+ `createSafeFetcher` takes the same options and returns a `fetch`-compatible
233
+ function for host code: same rules, policy, middleware and security defaults,
234
+ but it resolves to a real `Response`.
235
+
236
+ ```ts
237
+ import { createSafeFetcher } from '@iso4/fetch'
238
+
239
+ const safeFetch = createSafeFetcher({ rules: { host: 'api.example.com', routes: [{ path: '/v1/**' }] } })
240
+ const res = await safeFetch('https://api.example.com/v1/users', { headers: { accept: 'application/json' } })
241
+ const users = await res.json()
242
+ ```
243
+
244
+ It accepts what `fetch` accepts (a URL, a `Request`, any `init` with headers,
245
+ body and `signal`). Transport options such as `redirect` are ignored —
246
+ `maxRedirects` decides. The body is buffered under `maxBodyBytes`, and a
247
+ middleware body that is not bytes or text is JSON-encoded. Each call to
248
+ `createSafeFetcher` gets its own connection pool.
249
+
192
250
  ## Security defaults
193
251
 
194
- | Threat | Mitigation |
195
- | ---------------------- | ---------------------------------------------------------------------------- |
196
- | SSRF / private IP | DNS pre-resolved before every request; loopback, RFC1918, link-local blocked |
197
- | DNS rebinding | undici DNS interceptor pins the connection to the resolved IP |
198
- | Redirect bypass | No auto-follow by default; allow/deny re-checked on each hop |
199
- | Response amplification | Body streamed with `maxBodyBytes` cap |
200
- | Host auth leakage | Isolated undici `Agent` — no shared pool, cookies, or auth with the host app |
201
- | Path traversal | Paths decoded and `.`/`..`-normalised before route matching |
202
- | Double-encoded paths | Detected and rejected at parse time |
252
+ | Threat | Mitigation |
253
+ | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
254
+ | SSRF / private IP | DNS resolved at connection time (allowed requests only); loopback, RFC1918, link-local blocked; the connected socket's address is checked again |
255
+ | DNS rebinding | undici DNS interceptor pins the connection to the resolved IP |
256
+ | Redirect bypass | No auto-follow by default; allow/deny re-checked on each hop |
257
+ | Credential leak on redirect | `authorization`/`cookie`/`proxy-authorization` dropped on a cross-origin hop |
258
+ | Response amplification | Body streamed with `maxBodyBytes` cap |
259
+ | Host auth leakage | Isolated undici `Agent` — no shared pool, cookies, or auth with the host app |
260
+ | Path traversal | `.`/`..` (and the `%2e` forms) normalised by the URL parser before matching |
261
+ | Path/allowlist consistency | Paths matched literally, never decoded, so the approved path is sent verbatim |
262
+
263
+ Paths are matched and forwarded **literally** — iso4 never percent-decodes
264
+ them, so the path the allowlist approves is byte-for-byte the path that is sent.
265
+ This is deliberate: decoding to match while sending the encoded form would let
266
+ the two disagree. The servers iso4 usually targets (h3/Nitro, Express, nginx,
267
+ Apache by default) treat `%2F`/`%5C` as literal too, so a literal match is also
268
+ what they route on. If you point iso4 at a server that **does** decode `%2F` or
269
+ `%5C` before routing (e.g. Tomcat with encoded-slash enabled), a path the
270
+ allowlist permitted could re-resolve to a different one there — iso4 cannot see
271
+ that. In that case, reject encoded separators in your own middleware, e.g.:
272
+
273
+ ```ts
274
+ async function denyEncodedSeparators(ctx, next) {
275
+ if (/%2f|%5c/i.test(new URL(ctx.req.url).pathname))
276
+ throw new Error('encoded separator not allowed')
277
+ return next()
278
+ }
279
+ ```
203
280
 
204
281
  ## License
205
282
 
package/dist/index.d.mts CHANGED
@@ -43,10 +43,15 @@ interface HostFetchResponse {
43
43
  *
44
44
  * Returned as the `handler` field of `BridgeWithShim` — not meant to be
45
45
  * used directly. Assign `createSafeFetch({...})` to a global and the sandbox
46
- * layer handles wiring.
46
+ * layer handles wiring. For host code use `createSafeFetcher`.
47
47
  */
48
48
  type SafeFetchFn = (...args: unknown[]) => Promise<HostFetchResponse>;
49
49
  /**
50
+ * What `createSafeFetcher` returns: a `fetch`-compatible function that runs
51
+ * the safe pipeline in host code and resolves to a real `Response`.
52
+ */
53
+ type SafeFetcher = (...args: Parameters<typeof fetch>) => Promise<Response>;
54
+ /**
50
55
  * What `createSafeFetch` returns. Conforms to `BridgeWithShim` from
51
56
  * `@iso4/sandbox` so it can be passed directly as a global value.
52
57
  *
@@ -102,7 +107,11 @@ interface FetchContextReq {
102
107
  */
103
108
  header: (name: string, value: string) => void;
104
109
  /**
105
- * Replace the outgoing URL.
110
+ * Replace the outgoing URL. Trusted host operation: the new URL is **not**
111
+ * re-checked against the allow/deny + SSRF rules — those run once, on the
112
+ * agent's original URL, which also fixes the middleware pipeline and
113
+ * `params` for the request. Validate a URL derived from agent-influenced
114
+ * data before setting it. (Redirect hops, by contrast, are re-checked.)
106
115
  */
107
116
  setUrl: (url: string) => void;
108
117
  /**
@@ -301,8 +310,10 @@ interface SafeFetchRequest {
301
310
  */
302
311
  headers: Record<string, string>;
303
312
  /**
304
- * Resolved IP when `pinDns: true`. `null` when `pinDns: false` or when
305
- * using policy-only mode without rules.
313
+ * Always `null`. DNS is resolved only at connection time — after the request
314
+ * is authorized — so no resolved address is available to a `policy` or
315
+ * `onDenied`. The private/reserved-IP block still runs at that point. Kept
316
+ * for backward compatibility; do not rely on it.
306
317
  */
307
318
  resolvedIp: string | null;
308
319
  /**
@@ -340,15 +351,25 @@ interface SafeFetchOptions {
340
351
  */
341
352
  middleware?: FetchMiddleware;
342
353
  /**
343
- * Pre-resolve DNS and pin the connection to the resolved IP.
344
- * Prevents SSRF and DNS rebinding. `SafeFetchRequest.resolvedIp` is set.
354
+ * Resolve DNS and pin the connection to the resolved IP, refusing any
355
+ * private/reserved address. Prevents SSRF and DNS rebinding. Resolution
356
+ * happens at connection time, only for a request that already passed the
357
+ * allow/deny check, so a denied host is never looked up.
358
+ *
359
+ * Both address families are used, so a host that resolves to IPv6 only is
360
+ * reachable; every resolved address is checked against the private and
361
+ * reserved ranges of its own family before anything connects.
345
362
  *
346
363
  * @default true
347
364
  */
348
365
  pinDns?: boolean;
349
366
  /**
350
- * Auto-follow redirects up to this many hops. The full allow/deny +
351
- * middleware chain re-runs on each hop. `0` passes 3xx responses through.
367
+ * Auto-follow redirects up to this many hops. The allow/deny policy is
368
+ * re-checked on every hop. On a cross-origin hop `authorization`, `cookie`
369
+ * and `proxy-authorization` are dropped, and on a method-changing hop (303,
370
+ * or POST to GET on 301/302) `content-*` headers are dropped — matching
371
+ * undici. Middleware runs once around the whole request, not per hop. `0`
372
+ * passes 3xx responses through.
352
373
  *
353
374
  * @default 0
354
375
  */
@@ -398,5 +419,20 @@ interface SafeFetchOptions {
398
419
  * @param options
399
420
  */
400
421
  declare function createSafeFetch(options: SafeFetchOptions): SafeFetchGlobal;
422
+ /**
423
+ * Build a `fetch`-compatible function that runs the same safe pipeline as
424
+ * `createSafeFetch` directly in host code, with its own connection pool.
425
+ *
426
+ * ```ts
427
+ * const safeFetch = createSafeFetcher({ rules: [...] })
428
+ * const users = await (await safeFetch('https://api.example.com/v1/users')).json()
429
+ * ```
430
+ *
431
+ * `redirect`, `credentials` and the other transport options in `init` are
432
+ * ignored; `maxRedirects` decides. A middleware body that is not bytes or text
433
+ * is JSON-encoded.
434
+ * @param options
435
+ */
436
+ declare function createSafeFetcher(options: SafeFetchOptions): SafeFetcher;
401
437
  //#endregion
402
- export { type FetchContext, type FetchContextReq, type FetchMiddleware, type FetchOriginRule, type FetchRouteRule, type HostFetchRequest, type HostFetchResponse, type Next, type SafeFetchFn, type SafeFetchGlobal, type SafeFetchOptions, type SafeFetchPolicy, type SafeFetchRequest, createSafeFetch };
438
+ export { type FetchContext, type FetchContextReq, type FetchMiddleware, type FetchOriginRule, type FetchRouteRule, type HostFetchRequest, type HostFetchResponse, type Next, type SafeFetchFn, type SafeFetchGlobal, type SafeFetchOptions, type SafeFetchPolicy, type SafeFetchRequest, type SafeFetcher, createSafeFetch, createSafeFetcher };
package/dist/index.mjs CHANGED
@@ -1,21 +1,45 @@
1
1
  import { addRoute, createRouter, findRoute } from "rou3";
2
- import { Agent, fetch, interceptors } from "undici";
3
- import { lookup } from "node:dns/promises";
4
- import { lookup as lookup$1 } from "node:dns";
5
- //#region src/index.ts
2
+ import { Agent, buildConnector, fetch, interceptors } from "undici";
3
+ import { lookup } from "node:dns";
4
+ import { isIPv6 } from "node:net";
5
+ //#region src/dns.ts
6
6
  /**
7
- * \@iso4/fetch — public entry point.
8
- * See `./types.ts` for the full option surface.
7
+ * DNS for the connection-time pinning interceptor, plus the private/reserved-IP
8
+ * block that runs before undici connects.
9
+ *
10
+ * This is the ONLY place a hostname is resolved. Resolution happens inside the
11
+ * undici DNS interceptor, which runs only when a request actually connects —
12
+ * i.e. after it has passed the allow/deny check. A denied host is therefore
13
+ * never handed to a resolver, so the allow-list also gates DNS, not just the
14
+ * HTTP request.
15
+ *
16
+ * Not re-exported from `index.ts`, so none of this is public API.
17
+ */
18
+ /**
19
+ * True for addresses that must never be connected to from guest-driven fetch:
20
+ * loopback, link-local, RFC1918 / ULA, IMDS, and other reserved ranges. A
21
+ * malformed address is treated as reserved (fail closed).
22
+ * @param ip dotted-quad or IPv6 literal, brackets tolerated
9
23
  */
10
24
  function isReservedIp(ip) {
11
25
  if (ip.includes(":")) {
12
- const addr = ip.toLowerCase().replace(/^\[|\]$/g, "");
13
- if (addr === "::1") return true;
14
- const firstWord = parseInt(addr.split(":")[0] ?? "0", 16);
15
- if ((firstWord & 65472) === 65152) return true;
16
- if ((firstWord & 65024) === 64512) return true;
17
- if (addr.startsWith("::ffff:")) return isReservedIp(addr.slice(7));
18
- return false;
26
+ const addr = ip.toLowerCase().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
27
+ if (!isIPv6(addr)) return true;
28
+ const [head = "", tail] = addr.replace(/(\d+)\.(\d+)\.(\d+)\.(\d+)$/, (_m, a, b, c, d) => `${(Number(a) * 256 + Number(b)).toString(16)}:${(Number(c) * 256 + Number(d)).toString(16)}`).split("::");
29
+ const headWords = head === "" ? [] : head.split(":");
30
+ const tailWords = tail === void 0 || tail === "" ? [] : tail.split(":");
31
+ const w = [
32
+ ...headWords,
33
+ ...Array.from({ length: 8 - headWords.length - tailWords.length }).fill("0"),
34
+ ...tailWords
35
+ ].map((word) => parseInt(word, 16));
36
+ const v4 = (hi, lo) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;
37
+ if (w[0] === 0 && w[1] === 0 && w[2] === 0 && w[3] === 0 && w[4] === 0 && (w[5] === 0 || w[5] === 65535)) return isReservedIp(v4(w[6], w[7]));
38
+ if (w[0] === 0 && w[1] === 0 && w[2] === 0 && w[3] === 0 && w[4] === 65535 && w[5] === 0) return isReservedIp(v4(w[6], w[7]));
39
+ if (w[0] === 100 && w[1] === 65435 && w[2] === 0 && w[3] === 0 && w[4] === 0 && w[5] === 0) return isReservedIp(v4(w[6], w[7]));
40
+ if (w[0] === 8194) return isReservedIp(v4(w[1], w[2]));
41
+ const first = w[0];
42
+ return first === 100 && w[1] === 65435 && w[2] === 1 || first === 8193 && w[1] === 0 || (first & 65472) === 65152 || (first & 65472) === 65216 || (first & 65024) === 64512 || (first & 65280) === 65280;
19
43
  }
20
44
  const parts = ip.split(".").map(Number);
21
45
  if (parts.length !== 4 || parts.some((p) => Number.isNaN(p) || p < 0 || p > 255)) return true;
@@ -24,20 +48,75 @@ function isReservedIp(ip) {
24
48
  const c = parts[2] ?? 0;
25
49
  return a === 0 || a === 10 || a === 127 || a === 100 && (b & 192) === 64 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 0 && (c === 0 || c === 2) || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19) || a === 198 && b === 51 && c === 100 || a === 203 && b === 0 && c === 113 || a >= 224;
26
50
  }
27
- async function resolveAndCheckIp(hostname) {
28
- let addrs;
29
- try {
30
- addrs = await lookup(hostname, {
51
+ /**
52
+ * Throw if a hostname resolved to no usable public address. Exported for tests:
53
+ * the undici interceptor is bypassed when `fetch` is mocked, so this is where
54
+ * the SSRF block is exercised directly.
55
+ * @param hostname the hostname that was resolved (for the error message)
56
+ * @param addresses the resolved addresses
57
+ */
58
+ function assertPublicAddresses(hostname, addresses) {
59
+ if (addresses.length === 0) throw new Error(`fetch: no DNS addresses for "${hostname}"`);
60
+ for (const { address } of addresses) if (isReservedIp(address)) throw new Error(`fetch: request blocked — "${hostname}" resolves to private/reserved IP ${address}`);
61
+ }
62
+ /**
63
+ * The lookup function for undici's DNS interceptor: resolve the hostname and
64
+ * refuse any private/reserved address before a connection is made.
65
+ */
66
+ function makeDnsLookupFn() {
67
+ return (hostnameOrUrl, _opts, callback) => {
68
+ const rawHostname = typeof hostnameOrUrl === "object" && hostnameOrUrl !== null ? hostnameOrUrl.hostname : hostnameOrUrl;
69
+ const hostname = rawHostname.startsWith("[") && rawHostname.endsWith("]") ? rawHostname.slice(1, -1) : rawHostname;
70
+ lookup(hostname, {
31
71
  all: true,
32
72
  family: 0
73
+ }, (err, addresses) => {
74
+ if (err) {
75
+ callback(err, []);
76
+ return;
77
+ }
78
+ try {
79
+ assertPublicAddresses(hostname, addresses);
80
+ } catch (blockErr) {
81
+ callback(blockErr, []);
82
+ return;
83
+ }
84
+ callback(null, addresses.map((addr) => ({
85
+ address: addr.address,
86
+ family: addr.family,
87
+ ttl: 1e4
88
+ })));
33
89
  });
34
- } catch (err) {
35
- throw new Error(`fetch: DNS resolution failed for "${hostname}": ${err.message}`);
36
- }
37
- if (addrs.length === 0) throw new Error(`fetch: DNS resolution returned no addresses for "${hostname}"`);
38
- for (const { address } of addrs) if (isReservedIp(address)) throw new Error(`fetch: request blocked — "${hostname}" resolves to private/reserved IP ${address}`);
39
- return addrs[0].address;
90
+ };
40
91
  }
92
+ /**
93
+ * undici connector that drops a socket whose actual remote address is reserved.
94
+ * Catches whatever the literal and DNS checks miss, before any request bytes are sent.
95
+ */
96
+ function makeGuardedConnector() {
97
+ const connect = buildConnector({});
98
+ return (opts, callback) => {
99
+ connect(opts, (err, socket) => {
100
+ if (err !== null) {
101
+ callback(err, null);
102
+ return;
103
+ }
104
+ const address = socket.remoteAddress ?? "";
105
+ if (isReservedIp(address)) {
106
+ socket.destroy();
107
+ callback(/* @__PURE__ */ new Error(`fetch: request blocked — "${opts.hostname}" connected to private/reserved IP ${address}`), null);
108
+ return;
109
+ }
110
+ callback(null, socket);
111
+ });
112
+ };
113
+ }
114
+ //#endregion
115
+ //#region src/index.ts
116
+ /**
117
+ * \@iso4/fetch — public entry point.
118
+ * See `./types.ts` for the full option surface.
119
+ */
41
120
  function hostExact(requestHost, ruleHost) {
42
121
  return !ruleHost.startsWith("*.") && requestHost === ruleHost;
43
122
  }
@@ -64,11 +143,6 @@ function compileRules(rawRules) {
64
143
  router: buildRouter(rule.routes)
65
144
  }));
66
145
  }
67
- function decodePath(rawPath) {
68
- const once = decodeURIComponent(rawPath);
69
- if (once !== decodeURIComponent(once)) throw new Error("fetch: request denied — double-encoded path detected");
70
- return once;
71
- }
72
146
  /**
73
147
  * Two-pass origin matching: exact hostname rules are checked before wildcard
74
148
  * rules, regardless of array order. Within the same priority level the first
@@ -78,21 +152,17 @@ function decodePath(rawPath) {
78
152
  * @param compiled
79
153
  */
80
154
  function matchRules(req, compiled) {
155
+ let hostMatched = false;
81
156
  for (const pass of ["exact", "wildcard"]) for (const { rule, hosts, router } of compiled) {
82
157
  if (!(pass === "exact" ? hosts.some((rh) => hostExact(req.host, rh)) : hosts.some((rh) => hostWildcard(req.host, rh)))) continue;
158
+ hostMatched = true;
83
159
  if (rule.httpsOnly !== false && req.protocol !== "https") continue;
84
160
  const standardPort = req.protocol === "https" ? 443 : 80;
85
161
  if (rule.port !== void 0) {
86
162
  if (!(Array.isArray(rule.port) ? rule.port : [rule.port]).includes(req.port)) continue;
87
163
  } else if (req.port !== standardPort) continue;
88
164
  if (rule.routes.length === 0) return { kind: "deny-route" };
89
- let decodedPathname;
90
- try {
91
- decodedPathname = decodePath(new URL(req.url).pathname);
92
- } catch {
93
- return { kind: "deny-route" };
94
- }
95
- const matched = findRoute(router, req.method, decodedPathname, { normalize: true });
165
+ const matched = findRoute(router, req.method, new URL(req.url).pathname, { normalize: true });
96
166
  if (matched === void 0) return { kind: "deny-route" };
97
167
  return {
98
168
  kind: "allow",
@@ -101,10 +171,11 @@ function matchRules(req, compiled) {
101
171
  params: matched.params ?? {}
102
172
  };
103
173
  }
104
- return { kind: "no-origin" };
174
+ return hostMatched ? { kind: "deny-route" } : { kind: "no-origin" };
105
175
  }
106
176
  function makeFetchContext(initialUrl, method, initialHeaders, initialBody, params, hop, raw) {
107
177
  let _url = initialUrl;
178
+ let _body = initialBody;
108
179
  const _headers = { ...initialHeaders };
109
180
  return {
110
181
  req: {
@@ -112,10 +183,15 @@ function makeFetchContext(initialUrl, method, initialHeaders, initialBody, param
112
183
  params,
113
184
  hop,
114
185
  raw,
115
- body: initialBody,
116
186
  get url() {
117
187
  return _url;
118
188
  },
189
+ get body() {
190
+ return _body;
191
+ },
192
+ set body(b) {
193
+ _body = b;
194
+ },
119
195
  get headers() {
120
196
  return _headers;
121
197
  },
@@ -126,39 +202,12 @@ function makeFetchContext(initialUrl, method, initialHeaders, initialBody, param
126
202
  _url = url;
127
203
  },
128
204
  setBody(b) {
129
- this.body = b;
205
+ _body = b;
130
206
  }
131
207
  },
132
208
  res: null
133
209
  };
134
210
  }
135
- function makeDnsLookupFn() {
136
- return (hostnameOrUrl, _opts, callback) => {
137
- const hostname = typeof hostnameOrUrl === "object" && hostnameOrUrl !== null ? hostnameOrUrl.hostname : hostnameOrUrl;
138
- lookup$1(hostname, {
139
- all: true,
140
- family: 0
141
- }, (err, addresses) => {
142
- if (err) {
143
- callback(err, []);
144
- return;
145
- }
146
- if (addresses.length === 0) {
147
- callback(/* @__PURE__ */ new Error(`fetch: no DNS addresses for "${hostname}"`), []);
148
- return;
149
- }
150
- for (const { address } of addresses) if (isReservedIp(address)) {
151
- callback(/* @__PURE__ */ new Error(`fetch: request blocked — "${hostname}" resolves to private/reserved IP ${address}`), []);
152
- return;
153
- }
154
- callback(null, addresses.map((addr) => ({
155
- address: addr.address,
156
- family: addr.family,
157
- ttl: 1e4
158
- })));
159
- });
160
- };
161
- }
162
211
  async function readBody(body, maxBytes) {
163
212
  if (body === null) return null;
164
213
  const reader = body.getReader();
@@ -193,10 +242,7 @@ const REDIRECT_STATUSES = new Set([
193
242
  307,
194
243
  308
195
244
  ]);
196
- async function httpRequest(url, method, headers, body, agent, timeoutMs, maxBodyBytes, incomingSignal) {
197
- const signals = [AbortSignal.timeout(timeoutMs)];
198
- if (incomingSignal !== void 0) signals.push(incomingSignal);
199
- const signal = signals.length === 1 ? signals[0] : AbortSignal.any(signals);
245
+ async function httpRequest(url, method, headers, body, agent, maxBodyBytes, signal) {
200
246
  const response = await fetch(url, {
201
247
  method,
202
248
  headers,
@@ -282,9 +328,10 @@ function parseFetchArgs(args) {
282
328
  * @param options
283
329
  */
284
330
  function createSafeFetch(options) {
331
+ const run = buildSafeFetchHandler(options);
285
332
  return {
286
333
  kind: "bridge-with-shim",
287
- handler: buildSafeFetchHandler(options),
334
+ handler: async (...args) => run(parseFetchArgs(args)),
288
335
  shim: `(result) => ({
289
336
  ...result,
290
337
  ok: result.status >= 200 && result.status < 300,
@@ -297,32 +344,71 @@ function createSafeFetch(options) {
297
344
  };
298
345
  }
299
346
  /**
300
- * Internal: builds the bridge handler (SafeFetchFn) without the shim.
347
+ * Build a `fetch`-compatible function that runs the same safe pipeline as
348
+ * `createSafeFetch` directly in host code, with its own connection pool.
349
+ *
350
+ * ```ts
351
+ * const safeFetch = createSafeFetcher({ rules: [...] })
352
+ * const users = await (await safeFetch('https://api.example.com/v1/users')).json()
353
+ * ```
354
+ *
355
+ * `redirect`, `credentials` and the other transport options in `init` are
356
+ * ignored; `maxRedirects` decides. A middleware body that is not bytes or text
357
+ * is JSON-encoded.
358
+ * @param options
359
+ */
360
+ function createSafeFetcher(options) {
361
+ const run = buildSafeFetchHandler(options);
362
+ return async (input, init) => {
363
+ const request = new Request(input, init);
364
+ const headers = {};
365
+ request.headers.forEach((value, key) => {
366
+ headers[key] = value;
367
+ });
368
+ const { status, statusText, headers: resHeaders, body } = await run({
369
+ url: request.url,
370
+ method: request.method,
371
+ headers,
372
+ body: request.body === null ? null : new Uint8Array(await request.arrayBuffer()),
373
+ signal: request.signal
374
+ });
375
+ const nullBody = body === null || body === void 0 || [
376
+ 101,
377
+ 103,
378
+ 204,
379
+ 205,
380
+ 304
381
+ ].includes(status);
382
+ return new Response(nullBody ? null : body instanceof Uint8Array || typeof body === "string" ? body : JSON.stringify(body), {
383
+ status,
384
+ headers: resHeaders,
385
+ ...statusText !== void 0 ? { statusText } : {}
386
+ });
387
+ };
388
+ }
389
+ /**
390
+ * Internal: builds the safe pipeline shared by `createSafeFetch` and `createSafeFetcher`.
301
391
  * @param options
302
392
  */
303
393
  function buildSafeFetchHandler(options) {
304
- if (options.rules === void 0 && options.policy === void 0) throw new TypeError("createSafeFetch: at least one of `rules` or `policy` must be provided");
394
+ if (options.rules === void 0 && options.policy === void 0) throw new TypeError("@iso4/fetch: at least one of `rules` or `policy` must be provided");
305
395
  const compiled = options.rules !== void 0 ? compileRules(options.rules) : [];
306
396
  const doPinDns = options.pinDns !== false;
307
397
  const maxRedirects = options.maxRedirects ?? 0;
308
398
  const timeoutMs = options.timeoutMs ?? 3e4;
309
399
  const maxBodyBytes = options.maxBodyBytes ?? 16 * 1024 * 1024;
310
400
  const allowCompressed = options.allowCompressedResponses ?? false;
311
- const agent = doPinDns ? new Agent().compose(interceptors.dns({
401
+ const agent = doPinDns ? new Agent({ connect: makeGuardedConnector() }).compose(interceptors.dns({
312
402
  lookup: makeDnsLookupFn(),
313
- maxTTL: 1e4,
314
- dualStack: false,
315
- affinity: 4
403
+ maxTTL: 1e4
316
404
  })) : new Agent();
317
- async function buildSafeFetchRequest(parsedUrl, method, headers, hop) {
405
+ function buildSafeFetchRequest(parsedUrl, method, headers, hop) {
318
406
  const protocol = parsedUrl.protocol.slice(0, -1);
319
407
  if (protocol !== "http" && protocol !== "https") throw new Error(`fetch: unsupported protocol "${parsedUrl.protocol}"`);
320
408
  const host = parsedUrl.hostname.toLowerCase();
321
409
  const port = parsedUrl.port !== "" ? parseInt(parsedUrl.port, 10) : protocol === "https" ? 443 : 80;
322
- let resolvedIp = null;
323
410
  if (doPinDns) {
324
- if (!(/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host) || host.startsWith("["))) resolvedIp = await resolveAndCheckIp(host);
325
- else if (isReservedIp(host.replace(/^\[|\]$/g, ""))) throw new Error(`fetch: request blocked — IP literal ${host} is private/reserved`);
411
+ if ((/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host) || host.startsWith("[")) && isReservedIp(host.replace(/^\[|\]$/g, ""))) throw new Error(`fetch: request blocked — IP literal ${host} is private/reserved`);
326
412
  }
327
413
  return {
328
414
  url: parsedUrl.toString(),
@@ -332,7 +418,7 @@ function buildSafeFetchHandler(options) {
332
418
  path: parsedUrl.pathname + parsedUrl.search,
333
419
  method,
334
420
  headers,
335
- resolvedIp,
421
+ resolvedIp: null,
336
422
  hop
337
423
  };
338
424
  }
@@ -397,8 +483,7 @@ function buildSafeFetchHandler(options) {
397
483
  return ctx.res;
398
484
  });
399
485
  }
400
- return async (...args) => {
401
- const hostRequest = parseFetchArgs(args);
486
+ return async (hostRequest) => {
402
487
  let parsedUrl;
403
488
  try {
404
489
  parsedUrl = new URL(hostRequest.url);
@@ -413,7 +498,7 @@ function buildSafeFetchHandler(options) {
413
498
  if (!allowCompressed) baseHeaders["accept-encoding"] = "identity";
414
499
  delete baseHeaders["host"];
415
500
  const method = hostRequest.method.toUpperCase();
416
- const match = await checkRequest(await buildSafeFetchRequest(parsedUrl, method, baseHeaders, 0));
501
+ const match = await checkRequest(buildSafeFetchRequest(parsedUrl, method, baseHeaders, 0));
417
502
  const ctx = makeFetchContext(parsedUrl.toString(), method, baseHeaders, hostRequest.body, match?.params ?? {}, 0, hostRequest);
418
503
  const middlewares = [
419
504
  options.middleware,
@@ -424,9 +509,12 @@ function buildSafeFetchHandler(options) {
424
509
  let currentUrl = ctx.req.url;
425
510
  let currentMethod = method;
426
511
  let currentBody = ctx.req.body;
512
+ let currentHeaders = ctx.req.headers;
427
513
  let hop = 0;
514
+ const deadline = AbortSignal.timeout(timeoutMs);
515
+ const signal = hostRequest.signal !== void 0 ? AbortSignal.any([deadline, hostRequest.signal]) : deadline;
428
516
  for (;;) {
429
- const { response, bodyBytes } = await httpRequest(currentUrl, currentMethod, ctx.req.headers, currentBody, agent, timeoutMs, maxBodyBytes, hostRequest.signal);
517
+ const { response, bodyBytes } = await httpRequest(currentUrl, currentMethod, currentHeaders, currentBody, agent, maxBodyBytes, signal);
430
518
  if (!REDIRECT_STATUSES.has(response.status) || hop >= maxRedirects) {
431
519
  ctx.res = toHostFetchResponse(response, bodyBytes);
432
520
  return;
@@ -443,9 +531,22 @@ function buildSafeFetchHandler(options) {
443
531
  ctx.res = toHostFetchResponse(response, bodyBytes);
444
532
  return;
445
533
  }
534
+ const crossOrigin = nextUrl.origin !== new URL(currentUrl).origin;
535
+ const methodChanges = response.status === 303 || (response.status === 301 || response.status === 302) && currentMethod === "POST";
536
+ if (crossOrigin || methodChanges) {
537
+ currentHeaders = { ...currentHeaders };
538
+ if (crossOrigin) {
539
+ delete currentHeaders["authorization"];
540
+ delete currentHeaders["cookie"];
541
+ delete currentHeaders["proxy-authorization"];
542
+ }
543
+ if (methodChanges) {
544
+ for (const name of Object.keys(currentHeaders)) if (name.startsWith("content-")) delete currentHeaders[name];
545
+ }
546
+ }
446
547
  hop++;
447
- await checkRequest(await buildSafeFetchRequest(nextUrl, currentMethod, ctx.req.headers, hop));
448
- if (response.status === 303 || (response.status === 301 || response.status === 302) && currentMethod === "POST") {
548
+ await checkRequest(buildSafeFetchRequest(nextUrl, currentMethod, currentHeaders, hop));
549
+ if (methodChanges) {
449
550
  currentMethod = "GET";
450
551
  currentBody = null;
451
552
  }
@@ -456,4 +557,4 @@ function buildSafeFetchHandler(options) {
456
557
  };
457
558
  }
458
559
  //#endregion
459
- export { createSafeFetch };
560
+ export { createSafeFetch, createSafeFetcher };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iso4/fetch",
3
- "version": "0.0.1",
3
+ "version": "0.1.0",
4
4
  "type": "module",
5
5
  "description": "Hardened FetchHandler for the @iso4/sandbox runtime: DNS pinning, host allowlist, private-IP blocking, no auto-redirect",
6
6
  "keywords": [
@@ -45,6 +45,7 @@
45
45
  "@schplitt/eslint-config": "^1.5.0",
46
46
  "eslint": "^10.2.1",
47
47
  "tsdown": "^0.21.10",
48
+ "tsnapi": "^1.2.0",
48
49
  "typescript": "^6.0.3",
49
50
  "vitest": "^4.1.5"
50
51
  },