@iso4/fetch 0.0.2 → 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
@@ -227,18 +227,38 @@ createSafeFetch({
227
227
  `policy` runs only when no `rules` origin matched. If an origin matches but
228
228
  no route does the request is denied without consulting `policy`.
229
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
+
230
250
  ## Security defaults
231
251
 
232
- | Threat | Mitigation |
233
- | --------------------------- | ---------------------------------------------------------------------------------------------- |
234
- | SSRF / private IP | DNS resolved at connection time (allowed requests only); loopback, RFC1918, link-local blocked |
235
- | DNS rebinding | undici DNS interceptor pins the connection to the resolved IP |
236
- | Redirect bypass | No auto-follow by default; allow/deny re-checked on each hop |
237
- | Credential leak on redirect | `authorization`/`cookie`/`proxy-authorization` dropped on a cross-origin hop |
238
- | Response amplification | Body streamed with `maxBodyBytes` cap |
239
- | Host auth leakage | Isolated undici `Agent` — no shared pool, cookies, or auth with the host app |
240
- | Path traversal | `.`/`..` (and the `%2e` forms) normalised by the URL parser before matching |
241
- | Path/allowlist consistency | Paths matched literally, never decoded, so the approved path is sent verbatim |
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 |
242
262
 
243
263
  Paths are matched and forwarded **literally** — iso4 never percent-decodes
244
264
  them, so the path the allowlist approves is byte-for-byte the path that is sent.
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
  *
@@ -414,5 +419,20 @@ interface SafeFetchOptions {
414
419
  * @param options
415
420
  */
416
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;
417
437
  //#endregion
418
- 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,6 +1,7 @@
1
1
  import { addRoute, createRouter, findRoute } from "rou3";
2
- import { Agent, fetch, interceptors } from "undici";
2
+ import { Agent, buildConnector, fetch, interceptors } from "undici";
3
3
  import { lookup } from "node:dns";
4
+ import { isIPv6 } from "node:net";
4
5
  //#region src/dns.ts
5
6
  /**
6
7
  * DNS for the connection-time pinning interceptor, plus the private/reserved-IP
@@ -22,14 +23,23 @@ import { lookup } from "node:dns";
22
23
  */
23
24
  function isReservedIp(ip) {
24
25
  if (ip.includes(":")) {
25
- const addr = ip.toLowerCase().replace(/^\[|\]$/g, "");
26
- if (addr === "::1") return true;
27
- if (addr === "::") return true;
28
- const firstWord = parseInt(addr.split(":")[0] ?? "0", 16);
29
- if ((firstWord & 65472) === 65152) return true;
30
- if ((firstWord & 65024) === 64512) return true;
31
- if (addr.startsWith("::ffff:")) return isReservedIp(addr.slice(7));
32
- 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;
33
43
  }
34
44
  const parts = ip.split(".").map(Number);
35
45
  if (parts.length !== 4 || parts.some((p) => Number.isNaN(p) || p < 0 || p > 255)) return true;
@@ -79,6 +89,28 @@ function makeDnsLookupFn() {
79
89
  });
80
90
  };
81
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
+ }
82
114
  //#endregion
83
115
  //#region src/index.ts
84
116
  /**
@@ -296,9 +328,10 @@ function parseFetchArgs(args) {
296
328
  * @param options
297
329
  */
298
330
  function createSafeFetch(options) {
331
+ const run = buildSafeFetchHandler(options);
299
332
  return {
300
333
  kind: "bridge-with-shim",
301
- handler: buildSafeFetchHandler(options),
334
+ handler: async (...args) => run(parseFetchArgs(args)),
302
335
  shim: `(result) => ({
303
336
  ...result,
304
337
  ok: result.status >= 200 && result.status < 300,
@@ -311,18 +344,61 @@ function createSafeFetch(options) {
311
344
  };
312
345
  }
313
346
  /**
314
- * 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`.
315
391
  * @param options
316
392
  */
317
393
  function buildSafeFetchHandler(options) {
318
- 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");
319
395
  const compiled = options.rules !== void 0 ? compileRules(options.rules) : [];
320
396
  const doPinDns = options.pinDns !== false;
321
397
  const maxRedirects = options.maxRedirects ?? 0;
322
398
  const timeoutMs = options.timeoutMs ?? 3e4;
323
399
  const maxBodyBytes = options.maxBodyBytes ?? 16 * 1024 * 1024;
324
400
  const allowCompressed = options.allowCompressedResponses ?? false;
325
- const agent = doPinDns ? new Agent().compose(interceptors.dns({
401
+ const agent = doPinDns ? new Agent({ connect: makeGuardedConnector() }).compose(interceptors.dns({
326
402
  lookup: makeDnsLookupFn(),
327
403
  maxTTL: 1e4
328
404
  })) : new Agent();
@@ -407,8 +483,7 @@ function buildSafeFetchHandler(options) {
407
483
  return ctx.res;
408
484
  });
409
485
  }
410
- return async (...args) => {
411
- const hostRequest = parseFetchArgs(args);
486
+ return async (hostRequest) => {
412
487
  let parsedUrl;
413
488
  try {
414
489
  parsedUrl = new URL(hostRequest.url);
@@ -482,4 +557,4 @@ function buildSafeFetchHandler(options) {
482
557
  };
483
558
  }
484
559
  //#endregion
485
- 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.2",
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": [