@iso4/fetch 0.0.1 → 0.0.2
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 +71 -14
- package/dist/index.d.mts +23 -7
- package/dist/index.mjs +99 -73
- package/package.json +2 -1
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
|
|
69
|
-
|
|
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
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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
|
},
|
|
@@ -191,15 +229,34 @@ no route does the request is denied without consulting `policy`.
|
|
|
191
229
|
|
|
192
230
|
## Security defaults
|
|
193
231
|
|
|
194
|
-
| Threat
|
|
195
|
-
|
|
|
196
|
-
| SSRF / private IP
|
|
197
|
-
| DNS rebinding
|
|
198
|
-
| Redirect bypass
|
|
199
|
-
|
|
|
200
|
-
|
|
|
201
|
-
|
|
|
202
|
-
|
|
|
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 |
|
|
242
|
+
|
|
243
|
+
Paths are matched and forwarded **literally** — iso4 never percent-decodes
|
|
244
|
+
them, so the path the allowlist approves is byte-for-byte the path that is sent.
|
|
245
|
+
This is deliberate: decoding to match while sending the encoded form would let
|
|
246
|
+
the two disagree. The servers iso4 usually targets (h3/Nitro, Express, nginx,
|
|
247
|
+
Apache by default) treat `%2F`/`%5C` as literal too, so a literal match is also
|
|
248
|
+
what they route on. If you point iso4 at a server that **does** decode `%2F` or
|
|
249
|
+
`%5C` before routing (e.g. Tomcat with encoded-slash enabled), a path the
|
|
250
|
+
allowlist permitted could re-resolve to a different one there — iso4 cannot see
|
|
251
|
+
that. In that case, reject encoded separators in your own middleware, e.g.:
|
|
252
|
+
|
|
253
|
+
```ts
|
|
254
|
+
async function denyEncodedSeparators(ctx, next) {
|
|
255
|
+
if (/%2f|%5c/i.test(new URL(ctx.req.url).pathname))
|
|
256
|
+
throw new Error('encoded separator not allowed')
|
|
257
|
+
return next()
|
|
258
|
+
}
|
|
259
|
+
```
|
|
203
260
|
|
|
204
261
|
## License
|
|
205
262
|
|
package/dist/index.d.mts
CHANGED
|
@@ -102,7 +102,11 @@ interface FetchContextReq {
|
|
|
102
102
|
*/
|
|
103
103
|
header: (name: string, value: string) => void;
|
|
104
104
|
/**
|
|
105
|
-
* Replace the outgoing URL.
|
|
105
|
+
* Replace the outgoing URL. Trusted host operation: the new URL is **not**
|
|
106
|
+
* re-checked against the allow/deny + SSRF rules — those run once, on the
|
|
107
|
+
* agent's original URL, which also fixes the middleware pipeline and
|
|
108
|
+
* `params` for the request. Validate a URL derived from agent-influenced
|
|
109
|
+
* data before setting it. (Redirect hops, by contrast, are re-checked.)
|
|
106
110
|
*/
|
|
107
111
|
setUrl: (url: string) => void;
|
|
108
112
|
/**
|
|
@@ -301,8 +305,10 @@ interface SafeFetchRequest {
|
|
|
301
305
|
*/
|
|
302
306
|
headers: Record<string, string>;
|
|
303
307
|
/**
|
|
304
|
-
*
|
|
305
|
-
*
|
|
308
|
+
* Always `null`. DNS is resolved only at connection time — after the request
|
|
309
|
+
* is authorized — so no resolved address is available to a `policy` or
|
|
310
|
+
* `onDenied`. The private/reserved-IP block still runs at that point. Kept
|
|
311
|
+
* for backward compatibility; do not rely on it.
|
|
306
312
|
*/
|
|
307
313
|
resolvedIp: string | null;
|
|
308
314
|
/**
|
|
@@ -340,15 +346,25 @@ interface SafeFetchOptions {
|
|
|
340
346
|
*/
|
|
341
347
|
middleware?: FetchMiddleware;
|
|
342
348
|
/**
|
|
343
|
-
*
|
|
344
|
-
* Prevents SSRF and DNS rebinding.
|
|
349
|
+
* Resolve DNS and pin the connection to the resolved IP, refusing any
|
|
350
|
+
* private/reserved address. Prevents SSRF and DNS rebinding. Resolution
|
|
351
|
+
* happens at connection time, only for a request that already passed the
|
|
352
|
+
* allow/deny check, so a denied host is never looked up.
|
|
353
|
+
*
|
|
354
|
+
* Both address families are used, so a host that resolves to IPv6 only is
|
|
355
|
+
* reachable; every resolved address is checked against the private and
|
|
356
|
+
* reserved ranges of its own family before anything connects.
|
|
345
357
|
*
|
|
346
358
|
* @default true
|
|
347
359
|
*/
|
|
348
360
|
pinDns?: boolean;
|
|
349
361
|
/**
|
|
350
|
-
* Auto-follow redirects up to this many hops. The
|
|
351
|
-
*
|
|
362
|
+
* Auto-follow redirects up to this many hops. The allow/deny policy is
|
|
363
|
+
* re-checked on every hop. On a cross-origin hop `authorization`, `cookie`
|
|
364
|
+
* and `proxy-authorization` are dropped, and on a method-changing hop (303,
|
|
365
|
+
* or POST to GET on 301/302) `content-*` headers are dropped — matching
|
|
366
|
+
* undici. Middleware runs once around the whole request, not per hop. `0`
|
|
367
|
+
* passes 3xx responses through.
|
|
352
368
|
*
|
|
353
369
|
* @default 0
|
|
354
370
|
*/
|
package/dist/index.mjs
CHANGED
|
@@ -1,16 +1,30 @@
|
|
|
1
1
|
import { addRoute, createRouter, findRoute } from "rou3";
|
|
2
2
|
import { Agent, fetch, interceptors } from "undici";
|
|
3
|
-
import { lookup } from "node:dns
|
|
4
|
-
|
|
5
|
-
//#region src/index.ts
|
|
3
|
+
import { lookup } from "node:dns";
|
|
4
|
+
//#region src/dns.ts
|
|
6
5
|
/**
|
|
7
|
-
*
|
|
8
|
-
*
|
|
6
|
+
* DNS for the connection-time pinning interceptor, plus the private/reserved-IP
|
|
7
|
+
* block that runs before undici connects.
|
|
8
|
+
*
|
|
9
|
+
* This is the ONLY place a hostname is resolved. Resolution happens inside the
|
|
10
|
+
* undici DNS interceptor, which runs only when a request actually connects —
|
|
11
|
+
* i.e. after it has passed the allow/deny check. A denied host is therefore
|
|
12
|
+
* never handed to a resolver, so the allow-list also gates DNS, not just the
|
|
13
|
+
* HTTP request.
|
|
14
|
+
*
|
|
15
|
+
* Not re-exported from `index.ts`, so none of this is public API.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* True for addresses that must never be connected to from guest-driven fetch:
|
|
19
|
+
* loopback, link-local, RFC1918 / ULA, IMDS, and other reserved ranges. A
|
|
20
|
+
* malformed address is treated as reserved (fail closed).
|
|
21
|
+
* @param ip dotted-quad or IPv6 literal, brackets tolerated
|
|
9
22
|
*/
|
|
10
23
|
function isReservedIp(ip) {
|
|
11
24
|
if (ip.includes(":")) {
|
|
12
25
|
const addr = ip.toLowerCase().replace(/^\[|\]$/g, "");
|
|
13
26
|
if (addr === "::1") return true;
|
|
27
|
+
if (addr === "::") return true;
|
|
14
28
|
const firstWord = parseInt(addr.split(":")[0] ?? "0", 16);
|
|
15
29
|
if ((firstWord & 65472) === 65152) return true;
|
|
16
30
|
if ((firstWord & 65024) === 64512) return true;
|
|
@@ -24,20 +38,53 @@ function isReservedIp(ip) {
|
|
|
24
38
|
const c = parts[2] ?? 0;
|
|
25
39
|
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
40
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
41
|
+
/**
|
|
42
|
+
* Throw if a hostname resolved to no usable public address. Exported for tests:
|
|
43
|
+
* the undici interceptor is bypassed when `fetch` is mocked, so this is where
|
|
44
|
+
* the SSRF block is exercised directly.
|
|
45
|
+
* @param hostname the hostname that was resolved (for the error message)
|
|
46
|
+
* @param addresses the resolved addresses
|
|
47
|
+
*/
|
|
48
|
+
function assertPublicAddresses(hostname, addresses) {
|
|
49
|
+
if (addresses.length === 0) throw new Error(`fetch: no DNS addresses for "${hostname}"`);
|
|
50
|
+
for (const { address } of addresses) if (isReservedIp(address)) throw new Error(`fetch: request blocked — "${hostname}" resolves to private/reserved IP ${address}`);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The lookup function for undici's DNS interceptor: resolve the hostname and
|
|
54
|
+
* refuse any private/reserved address before a connection is made.
|
|
55
|
+
*/
|
|
56
|
+
function makeDnsLookupFn() {
|
|
57
|
+
return (hostnameOrUrl, _opts, callback) => {
|
|
58
|
+
const rawHostname = typeof hostnameOrUrl === "object" && hostnameOrUrl !== null ? hostnameOrUrl.hostname : hostnameOrUrl;
|
|
59
|
+
const hostname = rawHostname.startsWith("[") && rawHostname.endsWith("]") ? rawHostname.slice(1, -1) : rawHostname;
|
|
60
|
+
lookup(hostname, {
|
|
31
61
|
all: true,
|
|
32
62
|
family: 0
|
|
63
|
+
}, (err, addresses) => {
|
|
64
|
+
if (err) {
|
|
65
|
+
callback(err, []);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
assertPublicAddresses(hostname, addresses);
|
|
70
|
+
} catch (blockErr) {
|
|
71
|
+
callback(blockErr, []);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
callback(null, addresses.map((addr) => ({
|
|
75
|
+
address: addr.address,
|
|
76
|
+
family: addr.family,
|
|
77
|
+
ttl: 1e4
|
|
78
|
+
})));
|
|
33
79
|
});
|
|
34
|
-
}
|
|
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;
|
|
80
|
+
};
|
|
40
81
|
}
|
|
82
|
+
//#endregion
|
|
83
|
+
//#region src/index.ts
|
|
84
|
+
/**
|
|
85
|
+
* \@iso4/fetch — public entry point.
|
|
86
|
+
* See `./types.ts` for the full option surface.
|
|
87
|
+
*/
|
|
41
88
|
function hostExact(requestHost, ruleHost) {
|
|
42
89
|
return !ruleHost.startsWith("*.") && requestHost === ruleHost;
|
|
43
90
|
}
|
|
@@ -64,11 +111,6 @@ function compileRules(rawRules) {
|
|
|
64
111
|
router: buildRouter(rule.routes)
|
|
65
112
|
}));
|
|
66
113
|
}
|
|
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
114
|
/**
|
|
73
115
|
* Two-pass origin matching: exact hostname rules are checked before wildcard
|
|
74
116
|
* rules, regardless of array order. Within the same priority level the first
|
|
@@ -78,21 +120,17 @@ function decodePath(rawPath) {
|
|
|
78
120
|
* @param compiled
|
|
79
121
|
*/
|
|
80
122
|
function matchRules(req, compiled) {
|
|
123
|
+
let hostMatched = false;
|
|
81
124
|
for (const pass of ["exact", "wildcard"]) for (const { rule, hosts, router } of compiled) {
|
|
82
125
|
if (!(pass === "exact" ? hosts.some((rh) => hostExact(req.host, rh)) : hosts.some((rh) => hostWildcard(req.host, rh)))) continue;
|
|
126
|
+
hostMatched = true;
|
|
83
127
|
if (rule.httpsOnly !== false && req.protocol !== "https") continue;
|
|
84
128
|
const standardPort = req.protocol === "https" ? 443 : 80;
|
|
85
129
|
if (rule.port !== void 0) {
|
|
86
130
|
if (!(Array.isArray(rule.port) ? rule.port : [rule.port]).includes(req.port)) continue;
|
|
87
131
|
} else if (req.port !== standardPort) continue;
|
|
88
132
|
if (rule.routes.length === 0) return { kind: "deny-route" };
|
|
89
|
-
|
|
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 });
|
|
133
|
+
const matched = findRoute(router, req.method, new URL(req.url).pathname, { normalize: true });
|
|
96
134
|
if (matched === void 0) return { kind: "deny-route" };
|
|
97
135
|
return {
|
|
98
136
|
kind: "allow",
|
|
@@ -101,10 +139,11 @@ function matchRules(req, compiled) {
|
|
|
101
139
|
params: matched.params ?? {}
|
|
102
140
|
};
|
|
103
141
|
}
|
|
104
|
-
return { kind: "no-origin" };
|
|
142
|
+
return hostMatched ? { kind: "deny-route" } : { kind: "no-origin" };
|
|
105
143
|
}
|
|
106
144
|
function makeFetchContext(initialUrl, method, initialHeaders, initialBody, params, hop, raw) {
|
|
107
145
|
let _url = initialUrl;
|
|
146
|
+
let _body = initialBody;
|
|
108
147
|
const _headers = { ...initialHeaders };
|
|
109
148
|
return {
|
|
110
149
|
req: {
|
|
@@ -112,10 +151,15 @@ function makeFetchContext(initialUrl, method, initialHeaders, initialBody, param
|
|
|
112
151
|
params,
|
|
113
152
|
hop,
|
|
114
153
|
raw,
|
|
115
|
-
body: initialBody,
|
|
116
154
|
get url() {
|
|
117
155
|
return _url;
|
|
118
156
|
},
|
|
157
|
+
get body() {
|
|
158
|
+
return _body;
|
|
159
|
+
},
|
|
160
|
+
set body(b) {
|
|
161
|
+
_body = b;
|
|
162
|
+
},
|
|
119
163
|
get headers() {
|
|
120
164
|
return _headers;
|
|
121
165
|
},
|
|
@@ -126,39 +170,12 @@ function makeFetchContext(initialUrl, method, initialHeaders, initialBody, param
|
|
|
126
170
|
_url = url;
|
|
127
171
|
},
|
|
128
172
|
setBody(b) {
|
|
129
|
-
|
|
173
|
+
_body = b;
|
|
130
174
|
}
|
|
131
175
|
},
|
|
132
176
|
res: null
|
|
133
177
|
};
|
|
134
178
|
}
|
|
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
179
|
async function readBody(body, maxBytes) {
|
|
163
180
|
if (body === null) return null;
|
|
164
181
|
const reader = body.getReader();
|
|
@@ -193,10 +210,7 @@ const REDIRECT_STATUSES = new Set([
|
|
|
193
210
|
307,
|
|
194
211
|
308
|
|
195
212
|
]);
|
|
196
|
-
async function httpRequest(url, method, headers, body, agent,
|
|
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);
|
|
213
|
+
async function httpRequest(url, method, headers, body, agent, maxBodyBytes, signal) {
|
|
200
214
|
const response = await fetch(url, {
|
|
201
215
|
method,
|
|
202
216
|
headers,
|
|
@@ -310,19 +324,15 @@ function buildSafeFetchHandler(options) {
|
|
|
310
324
|
const allowCompressed = options.allowCompressedResponses ?? false;
|
|
311
325
|
const agent = doPinDns ? new Agent().compose(interceptors.dns({
|
|
312
326
|
lookup: makeDnsLookupFn(),
|
|
313
|
-
maxTTL: 1e4
|
|
314
|
-
dualStack: false,
|
|
315
|
-
affinity: 4
|
|
327
|
+
maxTTL: 1e4
|
|
316
328
|
})) : new Agent();
|
|
317
|
-
|
|
329
|
+
function buildSafeFetchRequest(parsedUrl, method, headers, hop) {
|
|
318
330
|
const protocol = parsedUrl.protocol.slice(0, -1);
|
|
319
331
|
if (protocol !== "http" && protocol !== "https") throw new Error(`fetch: unsupported protocol "${parsedUrl.protocol}"`);
|
|
320
332
|
const host = parsedUrl.hostname.toLowerCase();
|
|
321
333
|
const port = parsedUrl.port !== "" ? parseInt(parsedUrl.port, 10) : protocol === "https" ? 443 : 80;
|
|
322
|
-
let resolvedIp = null;
|
|
323
334
|
if (doPinDns) {
|
|
324
|
-
if (
|
|
325
|
-
else if (isReservedIp(host.replace(/^\[|\]$/g, ""))) throw new Error(`fetch: request blocked — IP literal ${host} is private/reserved`);
|
|
335
|
+
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
336
|
}
|
|
327
337
|
return {
|
|
328
338
|
url: parsedUrl.toString(),
|
|
@@ -332,7 +342,7 @@ function buildSafeFetchHandler(options) {
|
|
|
332
342
|
path: parsedUrl.pathname + parsedUrl.search,
|
|
333
343
|
method,
|
|
334
344
|
headers,
|
|
335
|
-
resolvedIp,
|
|
345
|
+
resolvedIp: null,
|
|
336
346
|
hop
|
|
337
347
|
};
|
|
338
348
|
}
|
|
@@ -413,7 +423,7 @@ function buildSafeFetchHandler(options) {
|
|
|
413
423
|
if (!allowCompressed) baseHeaders["accept-encoding"] = "identity";
|
|
414
424
|
delete baseHeaders["host"];
|
|
415
425
|
const method = hostRequest.method.toUpperCase();
|
|
416
|
-
const match = await checkRequest(
|
|
426
|
+
const match = await checkRequest(buildSafeFetchRequest(parsedUrl, method, baseHeaders, 0));
|
|
417
427
|
const ctx = makeFetchContext(parsedUrl.toString(), method, baseHeaders, hostRequest.body, match?.params ?? {}, 0, hostRequest);
|
|
418
428
|
const middlewares = [
|
|
419
429
|
options.middleware,
|
|
@@ -424,9 +434,12 @@ function buildSafeFetchHandler(options) {
|
|
|
424
434
|
let currentUrl = ctx.req.url;
|
|
425
435
|
let currentMethod = method;
|
|
426
436
|
let currentBody = ctx.req.body;
|
|
437
|
+
let currentHeaders = ctx.req.headers;
|
|
427
438
|
let hop = 0;
|
|
439
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
440
|
+
const signal = hostRequest.signal !== void 0 ? AbortSignal.any([deadline, hostRequest.signal]) : deadline;
|
|
428
441
|
for (;;) {
|
|
429
|
-
const { response, bodyBytes } = await httpRequest(currentUrl, currentMethod,
|
|
442
|
+
const { response, bodyBytes } = await httpRequest(currentUrl, currentMethod, currentHeaders, currentBody, agent, maxBodyBytes, signal);
|
|
430
443
|
if (!REDIRECT_STATUSES.has(response.status) || hop >= maxRedirects) {
|
|
431
444
|
ctx.res = toHostFetchResponse(response, bodyBytes);
|
|
432
445
|
return;
|
|
@@ -443,9 +456,22 @@ function buildSafeFetchHandler(options) {
|
|
|
443
456
|
ctx.res = toHostFetchResponse(response, bodyBytes);
|
|
444
457
|
return;
|
|
445
458
|
}
|
|
459
|
+
const crossOrigin = nextUrl.origin !== new URL(currentUrl).origin;
|
|
460
|
+
const methodChanges = response.status === 303 || (response.status === 301 || response.status === 302) && currentMethod === "POST";
|
|
461
|
+
if (crossOrigin || methodChanges) {
|
|
462
|
+
currentHeaders = { ...currentHeaders };
|
|
463
|
+
if (crossOrigin) {
|
|
464
|
+
delete currentHeaders["authorization"];
|
|
465
|
+
delete currentHeaders["cookie"];
|
|
466
|
+
delete currentHeaders["proxy-authorization"];
|
|
467
|
+
}
|
|
468
|
+
if (methodChanges) {
|
|
469
|
+
for (const name of Object.keys(currentHeaders)) if (name.startsWith("content-")) delete currentHeaders[name];
|
|
470
|
+
}
|
|
471
|
+
}
|
|
446
472
|
hop++;
|
|
447
|
-
await checkRequest(
|
|
448
|
-
if (
|
|
473
|
+
await checkRequest(buildSafeFetchRequest(nextUrl, currentMethod, currentHeaders, hop));
|
|
474
|
+
if (methodChanges) {
|
|
449
475
|
currentMethod = "GET";
|
|
450
476
|
currentBody = null;
|
|
451
477
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@iso4/fetch",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.2",
|
|
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
|
},
|