@iso4/fetch 0.0.2 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -10
- package/dist/index.d.mts +22 -2
- package/dist/index.mjs +115 -26
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -227,18 +227,39 @@ 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
|
|
233
|
-
|
|
|
234
|
-
| SSRF / private IP
|
|
235
|
-
| DNS rebinding
|
|
236
|
-
| Redirect bypass
|
|
237
|
-
| Credential leak on redirect
|
|
238
|
-
| Response amplification
|
|
239
|
-
| Host auth leakage
|
|
240
|
-
| Path traversal
|
|
241
|
-
| Path/allowlist consistency
|
|
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
|
+
| Credentials in error messages | URLs with credentials refused; invalid-URL and invalid-header errors use fixed messages that never quote the URL or value |
|
|
242
263
|
|
|
243
264
|
Paths are matched and forwarded **literally** — iso4 never percent-decodes
|
|
244
265
|
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
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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
|
/**
|
|
@@ -210,7 +242,18 @@ const REDIRECT_STATUSES = new Set([
|
|
|
210
242
|
307,
|
|
211
243
|
308
|
|
212
244
|
]);
|
|
245
|
+
const INVALID_URL = "fetch: invalid URL";
|
|
246
|
+
const URL_CREDENTIALS = "fetch: URL must not contain credentials";
|
|
247
|
+
const INVALID_HEADER = "fetch: invalid header name or value";
|
|
213
248
|
async function httpRequest(url, method, headers, body, agent, maxBodyBytes, signal) {
|
|
249
|
+
const target = URL.parse(url);
|
|
250
|
+
if (target === null) throw new TypeError(INVALID_URL);
|
|
251
|
+
if (target.username !== "" || target.password !== "") throw new TypeError(URL_CREDENTIALS);
|
|
252
|
+
try {
|
|
253
|
+
new Headers(headers);
|
|
254
|
+
} catch {
|
|
255
|
+
throw new TypeError(INVALID_HEADER);
|
|
256
|
+
}
|
|
214
257
|
const response = await fetch(url, {
|
|
215
258
|
method,
|
|
216
259
|
headers,
|
|
@@ -296,9 +339,10 @@ function parseFetchArgs(args) {
|
|
|
296
339
|
* @param options
|
|
297
340
|
*/
|
|
298
341
|
function createSafeFetch(options) {
|
|
342
|
+
const run = buildSafeFetchHandler(options);
|
|
299
343
|
return {
|
|
300
344
|
kind: "bridge-with-shim",
|
|
301
|
-
handler:
|
|
345
|
+
handler: async (...args) => run(parseFetchArgs(args)),
|
|
302
346
|
shim: `(result) => ({
|
|
303
347
|
...result,
|
|
304
348
|
ok: result.status >= 200 && result.status < 300,
|
|
@@ -311,18 +355,71 @@ function createSafeFetch(options) {
|
|
|
311
355
|
};
|
|
312
356
|
}
|
|
313
357
|
/**
|
|
314
|
-
*
|
|
358
|
+
* Build a `fetch`-compatible function that runs the same safe pipeline as
|
|
359
|
+
* `createSafeFetch` directly in host code, with its own connection pool.
|
|
360
|
+
*
|
|
361
|
+
* ```ts
|
|
362
|
+
* const safeFetch = createSafeFetcher({ rules: [...] })
|
|
363
|
+
* const users = await (await safeFetch('https://api.example.com/v1/users')).json()
|
|
364
|
+
* ```
|
|
365
|
+
*
|
|
366
|
+
* `redirect`, `credentials` and the other transport options in `init` are
|
|
367
|
+
* ignored; `maxRedirects` decides. A middleware body that is not bytes or text
|
|
368
|
+
* is JSON-encoded.
|
|
369
|
+
* @param options
|
|
370
|
+
*/
|
|
371
|
+
function createSafeFetcher(options) {
|
|
372
|
+
const run = buildSafeFetchHandler(options);
|
|
373
|
+
return async (input, init) => {
|
|
374
|
+
if (!(input instanceof Request)) {
|
|
375
|
+
const target = URL.parse(input.toString());
|
|
376
|
+
if (target === null) throw new TypeError(INVALID_URL);
|
|
377
|
+
if (target.username !== "" || target.password !== "") throw new TypeError(URL_CREDENTIALS);
|
|
378
|
+
}
|
|
379
|
+
try {
|
|
380
|
+
new Headers(init?.headers);
|
|
381
|
+
} catch {
|
|
382
|
+
throw new TypeError(INVALID_HEADER);
|
|
383
|
+
}
|
|
384
|
+
const request = new Request(input, init);
|
|
385
|
+
const headers = {};
|
|
386
|
+
request.headers.forEach((value, key) => {
|
|
387
|
+
headers[key] = value;
|
|
388
|
+
});
|
|
389
|
+
const { status, statusText, headers: resHeaders, body } = await run({
|
|
390
|
+
url: request.url,
|
|
391
|
+
method: request.method,
|
|
392
|
+
headers,
|
|
393
|
+
body: request.body === null ? null : new Uint8Array(await request.arrayBuffer()),
|
|
394
|
+
signal: request.signal
|
|
395
|
+
});
|
|
396
|
+
const nullBody = body === null || body === void 0 || [
|
|
397
|
+
101,
|
|
398
|
+
103,
|
|
399
|
+
204,
|
|
400
|
+
205,
|
|
401
|
+
304
|
|
402
|
+
].includes(status);
|
|
403
|
+
return new Response(nullBody ? null : body instanceof Uint8Array || typeof body === "string" ? body : JSON.stringify(body), {
|
|
404
|
+
status,
|
|
405
|
+
headers: resHeaders,
|
|
406
|
+
...statusText !== void 0 ? { statusText } : {}
|
|
407
|
+
});
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Internal: builds the safe pipeline shared by `createSafeFetch` and `createSafeFetcher`.
|
|
315
412
|
* @param options
|
|
316
413
|
*/
|
|
317
414
|
function buildSafeFetchHandler(options) {
|
|
318
|
-
if (options.rules === void 0 && options.policy === void 0) throw new TypeError("
|
|
415
|
+
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
416
|
const compiled = options.rules !== void 0 ? compileRules(options.rules) : [];
|
|
320
417
|
const doPinDns = options.pinDns !== false;
|
|
321
418
|
const maxRedirects = options.maxRedirects ?? 0;
|
|
322
419
|
const timeoutMs = options.timeoutMs ?? 3e4;
|
|
323
420
|
const maxBodyBytes = options.maxBodyBytes ?? 16 * 1024 * 1024;
|
|
324
421
|
const allowCompressed = options.allowCompressedResponses ?? false;
|
|
325
|
-
const agent = doPinDns ? new Agent().compose(interceptors.dns({
|
|
422
|
+
const agent = doPinDns ? new Agent({ connect: makeGuardedConnector() }).compose(interceptors.dns({
|
|
326
423
|
lookup: makeDnsLookupFn(),
|
|
327
424
|
maxTTL: 1e4
|
|
328
425
|
})) : new Agent();
|
|
@@ -407,18 +504,10 @@ function buildSafeFetchHandler(options) {
|
|
|
407
504
|
return ctx.res;
|
|
408
505
|
});
|
|
409
506
|
}
|
|
410
|
-
return async (
|
|
411
|
-
const
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
parsedUrl = new URL(hostRequest.url);
|
|
415
|
-
} catch {
|
|
416
|
-
throw new Error(`fetch: invalid URL "${hostRequest.url}"`);
|
|
417
|
-
}
|
|
418
|
-
if (parsedUrl.username !== "" || parsedUrl.password !== "") {
|
|
419
|
-
parsedUrl.username = "";
|
|
420
|
-
parsedUrl.password = "";
|
|
421
|
-
}
|
|
507
|
+
return async (hostRequest) => {
|
|
508
|
+
const parsedUrl = URL.parse(hostRequest.url);
|
|
509
|
+
if (parsedUrl === null) throw new TypeError(INVALID_URL);
|
|
510
|
+
if (parsedUrl.username !== "" || parsedUrl.password !== "") throw new TypeError(URL_CREDENTIALS);
|
|
422
511
|
const baseHeaders = { ...hostRequest.headers };
|
|
423
512
|
if (!allowCompressed) baseHeaders["accept-encoding"] = "identity";
|
|
424
513
|
delete baseHeaders["host"];
|
|
@@ -482,4 +571,4 @@ function buildSafeFetchHandler(options) {
|
|
|
482
571
|
};
|
|
483
572
|
}
|
|
484
573
|
//#endregion
|
|
485
|
-
export { createSafeFetch };
|
|
574
|
+
export { createSafeFetch, createSafeFetcher };
|
package/package.json
CHANGED