@iso4/fetch 0.0.0 → 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/LICENSE +21 -0
- package/README.md +263 -0
- package/dist/index.d.mts +418 -0
- package/dist/index.mjs +485 -0
- package/package.json +58 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 schplitt
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
# @iso4/fetch
|
|
2
|
+
|
|
3
|
+
Secure HTTP plumbing for host-authored APIs exposed to [@iso4/sandbox](../iso4-sandbox) agents.
|
|
4
|
+
|
|
5
|
+
## The pattern
|
|
6
|
+
|
|
7
|
+
The sandbox bridge only carries plain data — the agent can never receive a
|
|
8
|
+
real `Response` object with `.json()` or `.text()`. Exposing a raw `fetch`
|
|
9
|
+
global is therefore the wrong shape.
|
|
10
|
+
|
|
11
|
+
The right pattern: author a typed host module with a domain-specific API
|
|
12
|
+
and wire it to real HTTP internally. The agent learns the API from TypeScript
|
|
13
|
+
types you provide and never touches raw fetch.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
// agent code — clean, typed by the host
|
|
17
|
+
import { getUsers, queueDeletion } from 'host:api'
|
|
18
|
+
|
|
19
|
+
const users = await getUsers() // res.body is a ready-to-use array
|
|
20
|
+
const ack = await queueDeletion(42) // no real DELETE was sent
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
// host code
|
|
25
|
+
import { createSafeFetch } from '@iso4/fetch'
|
|
26
|
+
|
|
27
|
+
const fetch = createSafeFetch({
|
|
28
|
+
rules: {
|
|
29
|
+
host: 'api.example.com',
|
|
30
|
+
// all routes on this origin get auth injected automatically
|
|
31
|
+
middleware: async (ctx, next) => {
|
|
32
|
+
ctx.req.header('authorization', `Bearer ${await vault.get('token')}`)
|
|
33
|
+
return next()
|
|
34
|
+
},
|
|
35
|
+
routes: [
|
|
36
|
+
{
|
|
37
|
+
path: '/v1/users/**',
|
|
38
|
+
methods: 'GET',
|
|
39
|
+
// real HTTP + unwrap the response for the agent
|
|
40
|
+
middleware: async (_ctx, next) => {
|
|
41
|
+
const res = await next()
|
|
42
|
+
return await res.json() // agent gets res.body as a parsed object
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
path: '/v1/items/:id',
|
|
47
|
+
methods: 'DELETE',
|
|
48
|
+
// no HTTP — synthesise the response entirely
|
|
49
|
+
middleware: async (ctx, _next) => ({
|
|
50
|
+
status: 202,
|
|
51
|
+
headers: { 'content-type': 'application/json' },
|
|
52
|
+
body: { queued: true, id: ctx.req.params['id'] },
|
|
53
|
+
}),
|
|
54
|
+
},
|
|
55
|
+
],
|
|
56
|
+
},
|
|
57
|
+
})
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Install
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
npm i @iso4/sandbox @iso4/fetch
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Rules
|
|
67
|
+
|
|
68
|
+
Every request must match a declared rule before any middleware runs.
|
|
69
|
+
Unmatched requests are denied immediately.
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
const fetch = createSafeFetch({
|
|
73
|
+
rules: [
|
|
74
|
+
{
|
|
75
|
+
host: 'api.github.com', // exact hostname or '*.example.com' (single level)
|
|
76
|
+
httpsOnly: true, // default — set false to allow HTTP
|
|
77
|
+
// port: 443 // default; list explicit ports to allow others
|
|
78
|
+
routes: [
|
|
79
|
+
{ path: '/repos/**', methods: ['GET', 'POST'] },
|
|
80
|
+
{ path: '/repos/:owner/:repo/issues/:id', methods: 'GET' },
|
|
81
|
+
],
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
host: 'raw.githubusercontent.com',
|
|
85
|
+
routes: [{ path: '/**', methods: 'GET' }],
|
|
86
|
+
},
|
|
87
|
+
],
|
|
88
|
+
})
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Path patterns use [rou3](https://github.com/h3js/rou3) / URLPattern syntax:
|
|
92
|
+
|
|
93
|
+
| Pattern | Matches |
|
|
94
|
+
| ----------------------- | -------------------------------------------------------------- |
|
|
95
|
+
| `/users/:id` | `/users/42` — named param, available as `ctx.req.params.id` |
|
|
96
|
+
| `/api/**` | `/api`, `/api/users`, `/api/users/123` — zero-or-more segments |
|
|
97
|
+
| `/files/:ext(png\|jpg)` | `/files/png` — constrained param |
|
|
98
|
+
|
|
99
|
+
An empty `routes: []` denies all paths on that origin.
|
|
100
|
+
|
|
101
|
+
## Middleware
|
|
102
|
+
|
|
103
|
+
Middleware is the single extension point. The `(ctx, next)` pattern covers
|
|
104
|
+
every use case: request mutation, response inspection, logging, and synthetic
|
|
105
|
+
overrides.
|
|
106
|
+
|
|
107
|
+
Three levels, running in order — global wraps origin wraps route:
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
createSafeFetch({
|
|
111
|
+
middleware: someGlobalMiddleware, // global — every request
|
|
112
|
+
rules: {
|
|
113
|
+
host: 'api.example.com',
|
|
114
|
+
middleware: someOriginMiddleware, // origin — every request to this host
|
|
115
|
+
routes: [{
|
|
116
|
+
path: '/v1/**',
|
|
117
|
+
middleware: someRouteMiddleware, // route — this path only
|
|
118
|
+
}],
|
|
119
|
+
},
|
|
120
|
+
})
|
|
121
|
+
```
|
|
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
|
+
|
|
150
|
+
### Request mutation (auth, URL rewrite, headers)
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
async function someRequestMiddleware(ctx, next) {
|
|
154
|
+
ctx.req.header('authorization', `Bearer ${token}`) // injected, agent never sees it
|
|
155
|
+
ctx.req.setUrl(ctx.req.url.replace('/v1/', '/v2/'))
|
|
156
|
+
return next()
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
`ctx.req` fields: `url` (via `setUrl()`), `method`, `headers` (mutable object
|
|
161
|
+
or `header(name, val)`), `body` (via `setBody()`), `params`, `hop`, `raw`
|
|
162
|
+
(original unmodified bridge request).
|
|
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
|
+
|
|
175
|
+
### Response inspection / logging
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
async function someResponseMiddleware(ctx, next) {
|
|
179
|
+
const t = Date.now()
|
|
180
|
+
const res = await next()
|
|
181
|
+
console.log(`${ctx.req.method} ${ctx.req.url} → ${res.status} (${Date.now() - t}ms)`)
|
|
182
|
+
return res
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### Response rewrite (replaces `transform`)
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
async function someResponseRewriteMiddleware(_ctx, next) {
|
|
190
|
+
const res = await next()
|
|
191
|
+
const data = JSON.parse(new TextDecoder().decode(res.body as Uint8Array))
|
|
192
|
+
return { ...res, body: data } // agent gets res.body as a parsed object
|
|
193
|
+
}
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### Synthetic response — no HTTP (replaces `handle`)
|
|
197
|
+
|
|
198
|
+
Skip `next()` entirely. No network call is made.
|
|
199
|
+
|
|
200
|
+
```ts
|
|
201
|
+
async function someSyntheticResponseMiddleware(ctx, _next) {
|
|
202
|
+
return {
|
|
203
|
+
status: 202,
|
|
204
|
+
headers: { 'content-type': 'application/json' },
|
|
205
|
+
body: { queued: true, id: ctx.req.params['id'] },
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## Policy callback
|
|
211
|
+
|
|
212
|
+
For dynamic allow/deny logic that can't be expressed as static rules —
|
|
213
|
+
per-tenant checks, rate limiting, etc. Falls back to this when no origin rule
|
|
214
|
+
matches, or is the sole mechanism when `rules` is omitted.
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
createSafeFetch({
|
|
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 }) => {
|
|
221
|
+
const tenant = await db.findByHost(host)
|
|
222
|
+
return tenant?.allowedMethods.includes(method) ?? false
|
|
223
|
+
},
|
|
224
|
+
})
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
`policy` runs only when no `rules` origin matched. If an origin matches but
|
|
228
|
+
no route does the request is denied without consulting `policy`.
|
|
229
|
+
|
|
230
|
+
## Security defaults
|
|
231
|
+
|
|
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
|
+
```
|
|
260
|
+
|
|
261
|
+
## License
|
|
262
|
+
|
|
263
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* \@iso4/fetch — FetchHandler types and option/policy types for hardened fetch.
|
|
4
|
+
*
|
|
5
|
+
* The responsibility split: `iso4` handles mechanical hygiene, this package
|
|
6
|
+
* provides hardened defaults, and host application code supplies policy.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* The request object a FetchHandler receives from the bridge when the sandbox
|
|
10
|
+
* calls `fetch(url, init)`.
|
|
11
|
+
*/
|
|
12
|
+
interface HostFetchRequest {
|
|
13
|
+
url: string;
|
|
14
|
+
method: string;
|
|
15
|
+
/**
|
|
16
|
+
* Header names are lowercased.
|
|
17
|
+
*/
|
|
18
|
+
headers: Record<string, string>;
|
|
19
|
+
/**
|
|
20
|
+
* `null` for bodyless methods.
|
|
21
|
+
*/
|
|
22
|
+
body: Uint8Array | string | null;
|
|
23
|
+
/**
|
|
24
|
+
* Planned — not yet wired from the bridge; present here so the type is
|
|
25
|
+
* forward-compatible.
|
|
26
|
+
*/
|
|
27
|
+
signal?: AbortSignal;
|
|
28
|
+
}
|
|
29
|
+
interface HostFetchResponse {
|
|
30
|
+
status: number;
|
|
31
|
+
statusText?: string;
|
|
32
|
+
headers: Record<string, string>;
|
|
33
|
+
/**
|
|
34
|
+
* Any V8-serializable value — the bridge carries it as plain data.
|
|
35
|
+
* Use `Uint8Array` for raw bytes, `string` for text, a plain object or
|
|
36
|
+
* array for parsed JSON, or `null` for bodyless responses.
|
|
37
|
+
*/
|
|
38
|
+
body: unknown;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The internal bridge handler produced by `createSafeFetch`. Validates raw
|
|
42
|
+
* bridge args, runs allow/deny, makes the HTTP call, and returns plain data.
|
|
43
|
+
*
|
|
44
|
+
* Returned as the `handler` field of `BridgeWithShim` — not meant to be
|
|
45
|
+
* used directly. Assign `createSafeFetch({...})` to a global and the sandbox
|
|
46
|
+
* layer handles wiring.
|
|
47
|
+
*/
|
|
48
|
+
type SafeFetchFn = (...args: unknown[]) => Promise<HostFetchResponse>;
|
|
49
|
+
/**
|
|
50
|
+
* What `createSafeFetch` returns. Conforms to `BridgeWithShim` from
|
|
51
|
+
* `@iso4/sandbox` so it can be passed directly as a global value.
|
|
52
|
+
*
|
|
53
|
+
* Declared locally to avoid a cross-package type dependency — structurally
|
|
54
|
+
* compatible with the sandbox type.
|
|
55
|
+
*/
|
|
56
|
+
interface SafeFetchGlobal {
|
|
57
|
+
kind: "bridge-with-shim";
|
|
58
|
+
handler: SafeFetchFn;
|
|
59
|
+
shim: string;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The mutable request side of the middleware context.
|
|
63
|
+
*
|
|
64
|
+
* All mutations are invisible to the sandbox agent — they only affect what
|
|
65
|
+
* goes on the wire. `raw` preserves the original unmodified request from
|
|
66
|
+
* the bridge at all times.
|
|
67
|
+
*/
|
|
68
|
+
interface FetchContextReq {
|
|
69
|
+
/**
|
|
70
|
+
* Current URL (starts as the agent's URL; updated by `setUrl`).
|
|
71
|
+
*/
|
|
72
|
+
readonly url: string;
|
|
73
|
+
/**
|
|
74
|
+
* HTTP method, uppercased.
|
|
75
|
+
*/
|
|
76
|
+
readonly method: string;
|
|
77
|
+
/**
|
|
78
|
+
* Route parameters extracted by the path pattern.
|
|
79
|
+
* e.g. `/users/:id` matching `/users/42` → `{ id: '42' }`.
|
|
80
|
+
*/
|
|
81
|
+
readonly params: Record<string, string>;
|
|
82
|
+
/**
|
|
83
|
+
* Redirect hop index — 0 for the initial request.
|
|
84
|
+
*/
|
|
85
|
+
readonly hop: number;
|
|
86
|
+
/**
|
|
87
|
+
* Original untouched request from the bridge.
|
|
88
|
+
*/
|
|
89
|
+
readonly raw: HostFetchRequest;
|
|
90
|
+
/**
|
|
91
|
+
* Outgoing headers. Mutate directly or use `header()` for automatic
|
|
92
|
+
* lowercasing. These replace whatever the agent sent.
|
|
93
|
+
*/
|
|
94
|
+
headers: Record<string, string>;
|
|
95
|
+
/**
|
|
96
|
+
* Outgoing body. Mutate directly or use `setBody()`.
|
|
97
|
+
*/
|
|
98
|
+
body: Uint8Array | string | null;
|
|
99
|
+
/**
|
|
100
|
+
* Set (or overwrite) a single outgoing header.
|
|
101
|
+
* The name is lowercased automatically.
|
|
102
|
+
*/
|
|
103
|
+
header: (name: string, value: string) => void;
|
|
104
|
+
/**
|
|
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.)
|
|
110
|
+
*/
|
|
111
|
+
setUrl: (url: string) => void;
|
|
112
|
+
/**
|
|
113
|
+
* Replace the outgoing body.
|
|
114
|
+
*/
|
|
115
|
+
setBody: (body: Uint8Array | string | null) => void;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Context passed to every `FetchMiddleware`.
|
|
119
|
+
*
|
|
120
|
+
* `req` is the mutable outgoing request (mutate before `next()`).
|
|
121
|
+
* `res` is the response being built (`null` until `next()` completes or a
|
|
122
|
+
* middleware returns a response directly). Read and reassign after `next()`
|
|
123
|
+
* to inspect or replace the response.
|
|
124
|
+
*/
|
|
125
|
+
interface FetchContext {
|
|
126
|
+
readonly req: FetchContextReq;
|
|
127
|
+
/**
|
|
128
|
+
* The response. `null` before `next()` is called.
|
|
129
|
+
* After `next()`, holds the response from downstream.
|
|
130
|
+
* Assign to replace it:
|
|
131
|
+
* ```ts
|
|
132
|
+
* await next()
|
|
133
|
+
* ctx.res = { ...ctx.res!, body: parsed }
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
res: HostFetchResponse | null;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* A middleware function that runs after the allow/deny check and before the
|
|
140
|
+
* real HTTP call. Mutations to `ctx.req` are invisible to the agent but
|
|
141
|
+
* applied to every outgoing request that matches the level the middleware
|
|
142
|
+
* is attached to.
|
|
143
|
+
*
|
|
144
|
+
* Three levels of middleware are available — global (on `createSafeFetch`),
|
|
145
|
+
* origin (on `FetchOriginRule`), and route (on `FetchRouteRule`). They run
|
|
146
|
+
* in that order so more specific middleware runs last and can override
|
|
147
|
+
* broader changes.
|
|
148
|
+
*
|
|
149
|
+
* @example inject auth (covers every case: auth, logging, URL rewriting)
|
|
150
|
+
* ```ts
|
|
151
|
+
* async (ctx) => {
|
|
152
|
+
* ctx.req.header('authorization', `Bearer ${await vault.get('key')}`)
|
|
153
|
+
* console.log(`→ ${ctx.req.method} ${ctx.req.url}`)
|
|
154
|
+
* }
|
|
155
|
+
* ```
|
|
156
|
+
*/
|
|
157
|
+
/**
|
|
158
|
+
* Runs the downstream middleware chain and ultimately the real HTTP call.
|
|
159
|
+
* Sets `ctx.res` when it completes. Returns `void` — read `ctx.res` after
|
|
160
|
+
* awaiting to inspect the response.
|
|
161
|
+
*/
|
|
162
|
+
type Next = () => Promise<void>;
|
|
163
|
+
/**
|
|
164
|
+
* A middleware function in the `(ctx, next)` style.
|
|
165
|
+
*
|
|
166
|
+
* **Return value semantics:**
|
|
167
|
+
* - Return `void` / nothing — chain continues; `ctx.res` propagates as-is.
|
|
168
|
+
* - Return a `HostFetchResponse` — that response is set on `ctx.res` and
|
|
169
|
+
* returned to the agent immediately. Outer middleware still runs its
|
|
170
|
+
* after-`next()` code but the HTTP call is skipped.
|
|
171
|
+
* - `throw` — execution terminates; the sandbox `fetch()` call rejects.
|
|
172
|
+
* Use this to block a request with an error visible to the agent.
|
|
173
|
+
*
|
|
174
|
+
* **Pattern: mutate request (auth, URL rewrite)**
|
|
175
|
+
* ```ts
|
|
176
|
+
* async (ctx, next) => {
|
|
177
|
+
* ctx.req.header('authorization', `Bearer ${await vault.get('key')}`)
|
|
178
|
+
* await next()
|
|
179
|
+
* }
|
|
180
|
+
* ```
|
|
181
|
+
*
|
|
182
|
+
* **Pattern: inspect / rewrite response**
|
|
183
|
+
* ```ts
|
|
184
|
+
* async (ctx, next) => {
|
|
185
|
+
* await next()
|
|
186
|
+
* ctx.res = { ...ctx.res!, body: JSON.parse(new TextDecoder().decode(ctx.res!.body as Uint8Array)) }
|
|
187
|
+
* }
|
|
188
|
+
* ```
|
|
189
|
+
*
|
|
190
|
+
* **Pattern: log timing**
|
|
191
|
+
* ```ts
|
|
192
|
+
* async (ctx, next) => {
|
|
193
|
+
* const t = Date.now()
|
|
194
|
+
* await next()
|
|
195
|
+
* console.log(`${ctx.req.method} ${ctx.req.url} → ${ctx.res?.status} (${Date.now() - t}ms)`)
|
|
196
|
+
* }
|
|
197
|
+
* ```
|
|
198
|
+
*
|
|
199
|
+
* **Pattern: synthetic response (no HTTP)**
|
|
200
|
+
* ```ts
|
|
201
|
+
* async (ctx, _next) => ({
|
|
202
|
+
* status: 202,
|
|
203
|
+
* headers: { 'content-type': 'application/json' },
|
|
204
|
+
* body: { queued: true, id: ctx.req.params['id'] },
|
|
205
|
+
* })
|
|
206
|
+
* ```
|
|
207
|
+
*
|
|
208
|
+
* **Pattern: block with error**
|
|
209
|
+
* ```ts
|
|
210
|
+
* async (ctx, next) => {
|
|
211
|
+
* if (isSuspicious(ctx.req)) throw new Error('request blocked')
|
|
212
|
+
* await next()
|
|
213
|
+
* }
|
|
214
|
+
* ```
|
|
215
|
+
*/
|
|
216
|
+
type FetchMiddleware = (ctx: FetchContext, next: Next) => HostFetchResponse | void | Promise<HostFetchResponse | void>;
|
|
217
|
+
/**
|
|
218
|
+
* A single route entry within a `FetchOriginRule`.
|
|
219
|
+
*
|
|
220
|
+
* Path patterns use URLPattern/rou3 syntax:
|
|
221
|
+
* `/users/:id` — named parameter
|
|
222
|
+
* `/v2/events` — exact match
|
|
223
|
+
* `/reports/**` — zero-or-more sub-path segments
|
|
224
|
+
* `/files/:ext(png|jpg)` — constrained parameter
|
|
225
|
+
*/
|
|
226
|
+
interface FetchRouteRule {
|
|
227
|
+
/**
|
|
228
|
+
* Path pattern. Must start with `/`.
|
|
229
|
+
* `/**` and `/prefix/**` both match the prefix itself (zero-segment wildcard).
|
|
230
|
+
*/
|
|
231
|
+
path: string;
|
|
232
|
+
/**
|
|
233
|
+
* Allowed HTTP method(s). Case-insensitive.
|
|
234
|
+
* A string, an array, `'*'`, or omitted all mean "any method".
|
|
235
|
+
*/
|
|
236
|
+
methods?: string | string[];
|
|
237
|
+
/**
|
|
238
|
+
* Middleware that runs for requests matching this specific route,
|
|
239
|
+
* after global and origin middleware. Route middleware runs last so it
|
|
240
|
+
* can override anything set at broader levels.
|
|
241
|
+
*/
|
|
242
|
+
middleware?: FetchMiddleware;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Per-origin set of allowed routes.
|
|
246
|
+
*/
|
|
247
|
+
interface FetchOriginRule {
|
|
248
|
+
/**
|
|
249
|
+
* Hostname(s) to match.
|
|
250
|
+
* - Exact: `'api.example.com'`
|
|
251
|
+
* - Single-level subdomain wildcard: `'*.example.com'`
|
|
252
|
+
* (matches `sub.example.com`, not `a.b.example.com` or `example.com`)
|
|
253
|
+
* - Array for multiple hostnames under the same routes.
|
|
254
|
+
*/
|
|
255
|
+
host: string | string[];
|
|
256
|
+
/**
|
|
257
|
+
* Allowed port(s). When omitted, only the standard port for the protocol
|
|
258
|
+
* is allowed (443 for https, 80 for http).
|
|
259
|
+
*/
|
|
260
|
+
port?: number | number[];
|
|
261
|
+
/**
|
|
262
|
+
* Require HTTPS. Default `true`. Must be explicitly `false` to allow HTTP.
|
|
263
|
+
*
|
|
264
|
+
* @default true
|
|
265
|
+
*/
|
|
266
|
+
httpsOnly?: boolean;
|
|
267
|
+
/**
|
|
268
|
+
* Route rules for this origin. Method + path must match at least one entry.
|
|
269
|
+
* First match wins. An empty array denies all paths on this origin.
|
|
270
|
+
*/
|
|
271
|
+
routes: FetchRouteRule[];
|
|
272
|
+
/**
|
|
273
|
+
* Middleware that runs for every matched request on this origin, after
|
|
274
|
+
* global middleware and before route middleware.
|
|
275
|
+
*/
|
|
276
|
+
middleware?: FetchMiddleware;
|
|
277
|
+
}
|
|
278
|
+
interface SafeFetchRequest {
|
|
279
|
+
/**
|
|
280
|
+
* Full canonical URL string.
|
|
281
|
+
*/
|
|
282
|
+
url: string;
|
|
283
|
+
/**
|
|
284
|
+
* Protocol without trailing colon — always `'http'` or `'https'`.
|
|
285
|
+
*/
|
|
286
|
+
protocol: "http" | "https";
|
|
287
|
+
/**
|
|
288
|
+
* Hostname only, lowercased.
|
|
289
|
+
*/
|
|
290
|
+
host: string;
|
|
291
|
+
/**
|
|
292
|
+
* Effective port — 443 or 80 when not explicit in the URL.
|
|
293
|
+
*/
|
|
294
|
+
port: number;
|
|
295
|
+
/**
|
|
296
|
+
* Path plus query string, starting with `/`.
|
|
297
|
+
*/
|
|
298
|
+
path: string;
|
|
299
|
+
/**
|
|
300
|
+
* Uppercased HTTP method.
|
|
301
|
+
*/
|
|
302
|
+
method: string;
|
|
303
|
+
/**
|
|
304
|
+
* Request headers, names lowercased.
|
|
305
|
+
*/
|
|
306
|
+
headers: Record<string, string>;
|
|
307
|
+
/**
|
|
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.
|
|
312
|
+
*/
|
|
313
|
+
resolvedIp: string | null;
|
|
314
|
+
/**
|
|
315
|
+
* `0` for the initial request, `1+` for redirect hops.
|
|
316
|
+
*/
|
|
317
|
+
hop: number;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Allow/deny predicate for a single request.
|
|
321
|
+
*
|
|
322
|
+
* - Return `true` to allow.
|
|
323
|
+
* - Return `false` to deny with a generic message.
|
|
324
|
+
* - `throw new Error('reason')` to deny with a custom message visible to
|
|
325
|
+
* sandbox code.
|
|
326
|
+
* - Async (returning a `Promise`) is supported.
|
|
327
|
+
*/
|
|
328
|
+
type SafeFetchPolicy = (request: SafeFetchRequest) => boolean | Promise<boolean>;
|
|
329
|
+
interface SafeFetchOptions {
|
|
330
|
+
/**
|
|
331
|
+
* Declarative origin + route allowlist. At least one of `rules` or
|
|
332
|
+
* `policy` is required.
|
|
333
|
+
*
|
|
334
|
+
* If an origin matches but no route does → DENY (does not fall through to
|
|
335
|
+
* `policy`). If no origin matches → falls through to `policy` if provided.
|
|
336
|
+
*/
|
|
337
|
+
rules?: FetchOriginRule | FetchOriginRule[];
|
|
338
|
+
/**
|
|
339
|
+
* Allow/deny callback — fallback for requests not matched by any rule, or
|
|
340
|
+
* the sole mechanism when `rules` is omitted.
|
|
341
|
+
*/
|
|
342
|
+
policy?: SafeFetchPolicy;
|
|
343
|
+
/**
|
|
344
|
+
* Global middleware that runs for every allowed request, before origin and
|
|
345
|
+
* route middleware.
|
|
346
|
+
*/
|
|
347
|
+
middleware?: FetchMiddleware;
|
|
348
|
+
/**
|
|
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.
|
|
357
|
+
*
|
|
358
|
+
* @default true
|
|
359
|
+
*/
|
|
360
|
+
pinDns?: boolean;
|
|
361
|
+
/**
|
|
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.
|
|
368
|
+
*
|
|
369
|
+
* @default 0
|
|
370
|
+
*/
|
|
371
|
+
maxRedirects?: number;
|
|
372
|
+
/**
|
|
373
|
+
* Per-request timeout in milliseconds.
|
|
374
|
+
*
|
|
375
|
+
* @default 30_000
|
|
376
|
+
*/
|
|
377
|
+
timeoutMs?: number;
|
|
378
|
+
/**
|
|
379
|
+
* Maximum response body size in bytes (streaming, enforced before the
|
|
380
|
+
* response reaches any caller).
|
|
381
|
+
*
|
|
382
|
+
* @default 16 * 1024 * 1024
|
|
383
|
+
*/
|
|
384
|
+
maxBodyBytes?: number;
|
|
385
|
+
/**
|
|
386
|
+
* Allow compressed responses. When `false`, `Accept-Encoding: identity`
|
|
387
|
+
* is sent to prevent response-amplification attacks.
|
|
388
|
+
*
|
|
389
|
+
* @default false
|
|
390
|
+
*/
|
|
391
|
+
allowCompressedResponses?: boolean;
|
|
392
|
+
/**
|
|
393
|
+
* Alert hook — called on every denial. Errors thrown here are ignored.
|
|
394
|
+
* For request logging use middleware with `next()`.
|
|
395
|
+
*/
|
|
396
|
+
onDenied?: (request: SafeFetchRequest, reason: string) => void | Promise<void>;
|
|
397
|
+
}
|
|
398
|
+
//#endregion
|
|
399
|
+
//#region src/index.d.ts
|
|
400
|
+
/**
|
|
401
|
+
* Build a `BridgeWithShim` global that the sandbox layer wires into the
|
|
402
|
+
* prefix as both a secure bridge handler and a sandbox-side response wrapper.
|
|
403
|
+
*
|
|
404
|
+
* Pass directly as a global value:
|
|
405
|
+
* ```ts
|
|
406
|
+
* await sandbox.precompile({
|
|
407
|
+
* code: prefixSource,
|
|
408
|
+
* globals: { fetch: createSafeFetch({ rules: [...] }) },
|
|
409
|
+
* })
|
|
410
|
+
* ```
|
|
411
|
+
*
|
|
412
|
+
* Inside the sandbox the agent calls `fetch(url, init)` and gets back a
|
|
413
|
+
* response object with `.ok`, `.json()`, `.text()`, and `.bytes()`.
|
|
414
|
+
* @param options
|
|
415
|
+
*/
|
|
416
|
+
declare function createSafeFetch(options: SafeFetchOptions): SafeFetchGlobal;
|
|
417
|
+
//#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 };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
import { addRoute, createRouter, findRoute } from "rou3";
|
|
2
|
+
import { Agent, fetch, interceptors } from "undici";
|
|
3
|
+
import { lookup } from "node:dns";
|
|
4
|
+
//#region src/dns.ts
|
|
5
|
+
/**
|
|
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
|
|
22
|
+
*/
|
|
23
|
+
function isReservedIp(ip) {
|
|
24
|
+
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;
|
|
33
|
+
}
|
|
34
|
+
const parts = ip.split(".").map(Number);
|
|
35
|
+
if (parts.length !== 4 || parts.some((p) => Number.isNaN(p) || p < 0 || p > 255)) return true;
|
|
36
|
+
const a = parts[0];
|
|
37
|
+
const b = parts[1] ?? 0;
|
|
38
|
+
const c = parts[2] ?? 0;
|
|
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;
|
|
40
|
+
}
|
|
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, {
|
|
61
|
+
all: true,
|
|
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
|
+
})));
|
|
79
|
+
});
|
|
80
|
+
};
|
|
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
|
+
*/
|
|
88
|
+
function hostExact(requestHost, ruleHost) {
|
|
89
|
+
return !ruleHost.startsWith("*.") && requestHost === ruleHost;
|
|
90
|
+
}
|
|
91
|
+
function hostWildcard(requestHost, ruleHost) {
|
|
92
|
+
if (!ruleHost.startsWith("*.")) return false;
|
|
93
|
+
const domain = ruleHost.slice(2);
|
|
94
|
+
const expectedSegments = domain.split(".").length + 1;
|
|
95
|
+
return requestHost.split(".").length === expectedSegments && requestHost.endsWith(`.${domain}`);
|
|
96
|
+
}
|
|
97
|
+
function routeMethodsToRou3(methods) {
|
|
98
|
+
if (methods === void 0 || methods === "*") return [""];
|
|
99
|
+
if (typeof methods === "string") return [methods.toUpperCase()];
|
|
100
|
+
return methods.map((m) => m.toUpperCase());
|
|
101
|
+
}
|
|
102
|
+
function buildRouter(routes) {
|
|
103
|
+
const router = createRouter();
|
|
104
|
+
for (const route of routes) for (const method of routeMethodsToRou3(route.methods)) addRoute(router, method, route.path, route);
|
|
105
|
+
return router;
|
|
106
|
+
}
|
|
107
|
+
function compileRules(rawRules) {
|
|
108
|
+
return (Array.isArray(rawRules) ? rawRules : [rawRules]).map((rule) => ({
|
|
109
|
+
rule,
|
|
110
|
+
hosts: Array.isArray(rule.host) ? rule.host : [rule.host],
|
|
111
|
+
router: buildRouter(rule.routes)
|
|
112
|
+
}));
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Two-pass origin matching: exact hostname rules are checked before wildcard
|
|
116
|
+
* rules, regardless of array order. Within the same priority level the first
|
|
117
|
+
* entry in the array wins. A `deny-route` result from any pass is final —
|
|
118
|
+
* the explicit origin grant is exhaustive.
|
|
119
|
+
* @param req
|
|
120
|
+
* @param compiled
|
|
121
|
+
*/
|
|
122
|
+
function matchRules(req, compiled) {
|
|
123
|
+
let hostMatched = false;
|
|
124
|
+
for (const pass of ["exact", "wildcard"]) for (const { rule, hosts, router } of compiled) {
|
|
125
|
+
if (!(pass === "exact" ? hosts.some((rh) => hostExact(req.host, rh)) : hosts.some((rh) => hostWildcard(req.host, rh)))) continue;
|
|
126
|
+
hostMatched = true;
|
|
127
|
+
if (rule.httpsOnly !== false && req.protocol !== "https") continue;
|
|
128
|
+
const standardPort = req.protocol === "https" ? 443 : 80;
|
|
129
|
+
if (rule.port !== void 0) {
|
|
130
|
+
if (!(Array.isArray(rule.port) ? rule.port : [rule.port]).includes(req.port)) continue;
|
|
131
|
+
} else if (req.port !== standardPort) continue;
|
|
132
|
+
if (rule.routes.length === 0) return { kind: "deny-route" };
|
|
133
|
+
const matched = findRoute(router, req.method, new URL(req.url).pathname, { normalize: true });
|
|
134
|
+
if (matched === void 0) return { kind: "deny-route" };
|
|
135
|
+
return {
|
|
136
|
+
kind: "allow",
|
|
137
|
+
originRule: rule,
|
|
138
|
+
matchedRule: matched.data,
|
|
139
|
+
params: matched.params ?? {}
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
return hostMatched ? { kind: "deny-route" } : { kind: "no-origin" };
|
|
143
|
+
}
|
|
144
|
+
function makeFetchContext(initialUrl, method, initialHeaders, initialBody, params, hop, raw) {
|
|
145
|
+
let _url = initialUrl;
|
|
146
|
+
let _body = initialBody;
|
|
147
|
+
const _headers = { ...initialHeaders };
|
|
148
|
+
return {
|
|
149
|
+
req: {
|
|
150
|
+
method,
|
|
151
|
+
params,
|
|
152
|
+
hop,
|
|
153
|
+
raw,
|
|
154
|
+
get url() {
|
|
155
|
+
return _url;
|
|
156
|
+
},
|
|
157
|
+
get body() {
|
|
158
|
+
return _body;
|
|
159
|
+
},
|
|
160
|
+
set body(b) {
|
|
161
|
+
_body = b;
|
|
162
|
+
},
|
|
163
|
+
get headers() {
|
|
164
|
+
return _headers;
|
|
165
|
+
},
|
|
166
|
+
header(name, value) {
|
|
167
|
+
_headers[name.toLowerCase()] = value;
|
|
168
|
+
},
|
|
169
|
+
setUrl(url) {
|
|
170
|
+
_url = url;
|
|
171
|
+
},
|
|
172
|
+
setBody(b) {
|
|
173
|
+
_body = b;
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
res: null
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
async function readBody(body, maxBytes) {
|
|
180
|
+
if (body === null) return null;
|
|
181
|
+
const reader = body.getReader();
|
|
182
|
+
const chunks = [];
|
|
183
|
+
let total = 0;
|
|
184
|
+
try {
|
|
185
|
+
for (;;) {
|
|
186
|
+
const { done, value } = await reader.read();
|
|
187
|
+
if (done) break;
|
|
188
|
+
total += value.byteLength;
|
|
189
|
+
if (total > maxBytes) {
|
|
190
|
+
await reader.cancel();
|
|
191
|
+
throw new Error(`fetch: response body exceeds maxBodyBytes limit (${maxBytes} bytes)`);
|
|
192
|
+
}
|
|
193
|
+
chunks.push(value);
|
|
194
|
+
}
|
|
195
|
+
} finally {
|
|
196
|
+
reader.releaseLock();
|
|
197
|
+
}
|
|
198
|
+
const result = new Uint8Array(total);
|
|
199
|
+
let offset = 0;
|
|
200
|
+
for (const chunk of chunks) {
|
|
201
|
+
result.set(chunk, offset);
|
|
202
|
+
offset += chunk.byteLength;
|
|
203
|
+
}
|
|
204
|
+
return result;
|
|
205
|
+
}
|
|
206
|
+
const REDIRECT_STATUSES = new Set([
|
|
207
|
+
301,
|
|
208
|
+
302,
|
|
209
|
+
303,
|
|
210
|
+
307,
|
|
211
|
+
308
|
|
212
|
+
]);
|
|
213
|
+
async function httpRequest(url, method, headers, body, agent, maxBodyBytes, signal) {
|
|
214
|
+
const response = await fetch(url, {
|
|
215
|
+
method,
|
|
216
|
+
headers,
|
|
217
|
+
...body !== null ? { body } : {},
|
|
218
|
+
dispatcher: agent,
|
|
219
|
+
signal,
|
|
220
|
+
redirect: "manual"
|
|
221
|
+
});
|
|
222
|
+
return {
|
|
223
|
+
response,
|
|
224
|
+
bodyBytes: await readBody(response.body, maxBodyBytes)
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
function headersToRecord(headers) {
|
|
228
|
+
const out = {};
|
|
229
|
+
headers.forEach((value, key) => {
|
|
230
|
+
out[key] = value;
|
|
231
|
+
});
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
function toHostFetchResponse(response, bodyBytes) {
|
|
235
|
+
return {
|
|
236
|
+
status: response.status,
|
|
237
|
+
statusText: response.statusText,
|
|
238
|
+
headers: headersToRecord(response.headers),
|
|
239
|
+
body: bodyBytes
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Validates and parses the raw `...args: unknown[]` received from the bridge
|
|
244
|
+
* when sandbox code calls the registered global/import function.
|
|
245
|
+
*
|
|
246
|
+
* Expected call shape (mirrors the web fetch API):
|
|
247
|
+
* fn(url: string, init?: { method?: string, headers?: Record<string,string>, body?: string | Uint8Array | null })
|
|
248
|
+
*
|
|
249
|
+
* Throws a descriptive Error (visible to sandbox code) on any type mismatch.
|
|
250
|
+
* @param args
|
|
251
|
+
*/
|
|
252
|
+
function parseFetchArgs(args) {
|
|
253
|
+
const url = args[0];
|
|
254
|
+
if (typeof url !== "string" || url.length === 0) throw new Error("fetch: first argument must be a non-empty URL string");
|
|
255
|
+
const init = args[1];
|
|
256
|
+
if (init !== void 0 && init !== null) {
|
|
257
|
+
if (typeof init !== "object" || Array.isArray(init)) throw new Error("fetch: second argument must be a plain object");
|
|
258
|
+
}
|
|
259
|
+
const initObj = init ?? {};
|
|
260
|
+
const method = initObj["method"];
|
|
261
|
+
if (method !== void 0 && typeof method !== "string") throw new Error("fetch: init.method must be a string");
|
|
262
|
+
const rawHeaders = initObj["headers"];
|
|
263
|
+
const headers = {};
|
|
264
|
+
if (rawHeaders !== void 0 && rawHeaders !== null) {
|
|
265
|
+
if (typeof rawHeaders !== "object" || Array.isArray(rawHeaders)) throw new Error("fetch: init.headers must be a plain object");
|
|
266
|
+
for (const [k, v] of Object.entries(rawHeaders)) {
|
|
267
|
+
if (typeof v !== "string") throw new Error(`fetch: init.headers["${k}"] must be a string`);
|
|
268
|
+
if (/[\r\n\x00]/.test(k) || /[\r\n\x00]/.test(v)) throw new Error(`fetch: header "${k}" contains illegal characters (CR, LF, or NUL)`);
|
|
269
|
+
if (k.toLowerCase() === "host") continue;
|
|
270
|
+
headers[k.toLowerCase()] = v;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const body = initObj["body"] ?? null;
|
|
274
|
+
if (body !== null && typeof body !== "string" && !(body instanceof Uint8Array)) throw new Error("fetch: init.body must be a string, Uint8Array, or null");
|
|
275
|
+
return {
|
|
276
|
+
url,
|
|
277
|
+
method: typeof method === "string" ? method.toUpperCase() : "GET",
|
|
278
|
+
headers,
|
|
279
|
+
body
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Build a `BridgeWithShim` global that the sandbox layer wires into the
|
|
284
|
+
* prefix as both a secure bridge handler and a sandbox-side response wrapper.
|
|
285
|
+
*
|
|
286
|
+
* Pass directly as a global value:
|
|
287
|
+
* ```ts
|
|
288
|
+
* await sandbox.precompile({
|
|
289
|
+
* code: prefixSource,
|
|
290
|
+
* globals: { fetch: createSafeFetch({ rules: [...] }) },
|
|
291
|
+
* })
|
|
292
|
+
* ```
|
|
293
|
+
*
|
|
294
|
+
* Inside the sandbox the agent calls `fetch(url, init)` and gets back a
|
|
295
|
+
* response object with `.ok`, `.json()`, `.text()`, and `.bytes()`.
|
|
296
|
+
* @param options
|
|
297
|
+
*/
|
|
298
|
+
function createSafeFetch(options) {
|
|
299
|
+
return {
|
|
300
|
+
kind: "bridge-with-shim",
|
|
301
|
+
handler: buildSafeFetchHandler(options),
|
|
302
|
+
shim: `(result) => ({
|
|
303
|
+
...result,
|
|
304
|
+
ok: result.status >= 200 && result.status < 300,
|
|
305
|
+
json: () => JSON.parse(new TextDecoder().decode(result.body)),
|
|
306
|
+
text: () => new TextDecoder().decode(result.body),
|
|
307
|
+
bytes: () => result.body instanceof Uint8Array
|
|
308
|
+
? result.body
|
|
309
|
+
: new TextEncoder().encode(String(result.body ?? '')),
|
|
310
|
+
})`
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Internal: builds the bridge handler (SafeFetchFn) without the shim.
|
|
315
|
+
* @param options
|
|
316
|
+
*/
|
|
317
|
+
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");
|
|
319
|
+
const compiled = options.rules !== void 0 ? compileRules(options.rules) : [];
|
|
320
|
+
const doPinDns = options.pinDns !== false;
|
|
321
|
+
const maxRedirects = options.maxRedirects ?? 0;
|
|
322
|
+
const timeoutMs = options.timeoutMs ?? 3e4;
|
|
323
|
+
const maxBodyBytes = options.maxBodyBytes ?? 16 * 1024 * 1024;
|
|
324
|
+
const allowCompressed = options.allowCompressedResponses ?? false;
|
|
325
|
+
const agent = doPinDns ? new Agent().compose(interceptors.dns({
|
|
326
|
+
lookup: makeDnsLookupFn(),
|
|
327
|
+
maxTTL: 1e4
|
|
328
|
+
})) : new Agent();
|
|
329
|
+
function buildSafeFetchRequest(parsedUrl, method, headers, hop) {
|
|
330
|
+
const protocol = parsedUrl.protocol.slice(0, -1);
|
|
331
|
+
if (protocol !== "http" && protocol !== "https") throw new Error(`fetch: unsupported protocol "${parsedUrl.protocol}"`);
|
|
332
|
+
const host = parsedUrl.hostname.toLowerCase();
|
|
333
|
+
const port = parsedUrl.port !== "" ? parseInt(parsedUrl.port, 10) : protocol === "https" ? 443 : 80;
|
|
334
|
+
if (doPinDns) {
|
|
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`);
|
|
336
|
+
}
|
|
337
|
+
return {
|
|
338
|
+
url: parsedUrl.toString(),
|
|
339
|
+
protocol,
|
|
340
|
+
host,
|
|
341
|
+
port,
|
|
342
|
+
path: parsedUrl.pathname + parsedUrl.search,
|
|
343
|
+
method,
|
|
344
|
+
headers,
|
|
345
|
+
resolvedIp: null,
|
|
346
|
+
hop
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
async function runDeny(req, reason) {
|
|
350
|
+
try {
|
|
351
|
+
(options.onDenied?.(req, reason))?.catch(() => void 0);
|
|
352
|
+
} catch {}
|
|
353
|
+
throw new Error(reason);
|
|
354
|
+
}
|
|
355
|
+
async function checkRequest(req) {
|
|
356
|
+
if (compiled.length > 0) {
|
|
357
|
+
const result = matchRules(req, compiled);
|
|
358
|
+
if (result.kind === "allow") return {
|
|
359
|
+
originRule: result.originRule,
|
|
360
|
+
matchedRule: result.matchedRule,
|
|
361
|
+
params: result.params
|
|
362
|
+
};
|
|
363
|
+
if (result.kind === "deny-route") return runDeny(req, `fetch: request denied — no matching route for ${req.method} ${req.path} on ${req.host}`);
|
|
364
|
+
}
|
|
365
|
+
if (options.policy !== void 0) {
|
|
366
|
+
let allowed;
|
|
367
|
+
try {
|
|
368
|
+
allowed = await options.policy(req);
|
|
369
|
+
} catch (err) {
|
|
370
|
+
const reason = err.message || "request denied by policy";
|
|
371
|
+
try {
|
|
372
|
+
(options.onDenied?.(req, reason))?.catch(() => void 0);
|
|
373
|
+
} catch {}
|
|
374
|
+
throw err instanceof Error ? err : new Error(reason);
|
|
375
|
+
}
|
|
376
|
+
if (allowed) return null;
|
|
377
|
+
}
|
|
378
|
+
return runDeny(req, "fetch: request denied by policy");
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Compose the middleware chain.
|
|
382
|
+
*
|
|
383
|
+
* Each middleware receives `next` = a function that runs the rest of the
|
|
384
|
+
* chain and sets `ctx.res`. If a middleware returns a `HostFetchResponse`
|
|
385
|
+
* the chain sets `ctx.res` to that value immediately (outer middleware still
|
|
386
|
+
* runs its after-next code). If middleware returns void the current `ctx.res`
|
|
387
|
+
* propagates. If middleware throws the whole chain rejects.
|
|
388
|
+
*
|
|
389
|
+
* `finalNext` is the innermost handler: real HTTP call + redirect loop.
|
|
390
|
+
* It sets `ctx.res` and returns void.
|
|
391
|
+
* @param middlewares
|
|
392
|
+
* @param ctx
|
|
393
|
+
* @param finalNext
|
|
394
|
+
*/
|
|
395
|
+
function runMiddlewareChain(middlewares, ctx, finalNext) {
|
|
396
|
+
const active = middlewares.filter((m) => m !== void 0);
|
|
397
|
+
const dispatch = async (i) => {
|
|
398
|
+
if (i >= active.length) {
|
|
399
|
+
await finalNext();
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
const result = await active[i](ctx, () => dispatch(i + 1));
|
|
403
|
+
if (result !== void 0 && result !== null) ctx.res = result;
|
|
404
|
+
};
|
|
405
|
+
return dispatch(0).then(() => {
|
|
406
|
+
if (ctx.res === null) throw new Error("fetch: middleware chain produced no response — at least one middleware must call next() or return a response");
|
|
407
|
+
return ctx.res;
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
return async (...args) => {
|
|
411
|
+
const hostRequest = parseFetchArgs(args);
|
|
412
|
+
let parsedUrl;
|
|
413
|
+
try {
|
|
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
|
+
}
|
|
422
|
+
const baseHeaders = { ...hostRequest.headers };
|
|
423
|
+
if (!allowCompressed) baseHeaders["accept-encoding"] = "identity";
|
|
424
|
+
delete baseHeaders["host"];
|
|
425
|
+
const method = hostRequest.method.toUpperCase();
|
|
426
|
+
const match = await checkRequest(buildSafeFetchRequest(parsedUrl, method, baseHeaders, 0));
|
|
427
|
+
const ctx = makeFetchContext(parsedUrl.toString(), method, baseHeaders, hostRequest.body, match?.params ?? {}, 0, hostRequest);
|
|
428
|
+
const middlewares = [
|
|
429
|
+
options.middleware,
|
|
430
|
+
match?.originRule.middleware,
|
|
431
|
+
match?.matchedRule.middleware
|
|
432
|
+
];
|
|
433
|
+
const finalNext = async () => {
|
|
434
|
+
let currentUrl = ctx.req.url;
|
|
435
|
+
let currentMethod = method;
|
|
436
|
+
let currentBody = ctx.req.body;
|
|
437
|
+
let currentHeaders = ctx.req.headers;
|
|
438
|
+
let hop = 0;
|
|
439
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
440
|
+
const signal = hostRequest.signal !== void 0 ? AbortSignal.any([deadline, hostRequest.signal]) : deadline;
|
|
441
|
+
for (;;) {
|
|
442
|
+
const { response, bodyBytes } = await httpRequest(currentUrl, currentMethod, currentHeaders, currentBody, agent, maxBodyBytes, signal);
|
|
443
|
+
if (!REDIRECT_STATUSES.has(response.status) || hop >= maxRedirects) {
|
|
444
|
+
ctx.res = toHostFetchResponse(response, bodyBytes);
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
const location = response.headers.get("location");
|
|
448
|
+
if (location === null) {
|
|
449
|
+
ctx.res = toHostFetchResponse(response, bodyBytes);
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
let nextUrl;
|
|
453
|
+
try {
|
|
454
|
+
nextUrl = new URL(location, currentUrl);
|
|
455
|
+
} catch {
|
|
456
|
+
ctx.res = toHostFetchResponse(response, bodyBytes);
|
|
457
|
+
return;
|
|
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
|
+
}
|
|
472
|
+
hop++;
|
|
473
|
+
await checkRequest(buildSafeFetchRequest(nextUrl, currentMethod, currentHeaders, hop));
|
|
474
|
+
if (methodChanges) {
|
|
475
|
+
currentMethod = "GET";
|
|
476
|
+
currentBody = null;
|
|
477
|
+
}
|
|
478
|
+
currentUrl = nextUrl.toString();
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
return runMiddlewareChain(middlewares, ctx, finalNext);
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
//#endregion
|
|
485
|
+
export { createSafeFetch };
|
package/package.json
CHANGED
|
@@ -1,8 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@iso4/fetch",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"description": "placeholder",
|
|
5
|
-
"license": "MIT",
|
|
3
|
+
"version": "0.0.2",
|
|
6
4
|
"type": "module",
|
|
7
|
-
"
|
|
8
|
-
|
|
5
|
+
"description": "Hardened FetchHandler for the @iso4/sandbox runtime: DNS pinning, host allowlist, private-IP blocking, no auto-redirect",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"iso4",
|
|
8
|
+
"sandbox",
|
|
9
|
+
"fetch",
|
|
10
|
+
"ssrf",
|
|
11
|
+
"security",
|
|
12
|
+
"permissions"
|
|
13
|
+
],
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"author": "schplitt",
|
|
16
|
+
"homepage": "https://github.com/schplitt/iso4/tree/main/packages/iso4-fetch#readme",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "https://github.com/schplitt/iso4.git",
|
|
20
|
+
"directory": "packages/iso4-fetch"
|
|
21
|
+
},
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/schplitt/iso4/issues"
|
|
24
|
+
},
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.mts",
|
|
28
|
+
"import": "./dist/index.mjs"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"main": "./dist/index.mjs",
|
|
32
|
+
"module": "./dist/index.mjs",
|
|
33
|
+
"types": "./dist/index.d.mts",
|
|
34
|
+
"files": [
|
|
35
|
+
"LICENSE",
|
|
36
|
+
"README.md",
|
|
37
|
+
"dist"
|
|
38
|
+
],
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"rou3": "^0.8.1",
|
|
41
|
+
"undici": "^6.25.0"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@changesets/cli": "^2.27.10",
|
|
45
|
+
"@schplitt/eslint-config": "^1.5.0",
|
|
46
|
+
"eslint": "^10.2.1",
|
|
47
|
+
"tsdown": "^0.21.10",
|
|
48
|
+
"tsnapi": "^1.2.0",
|
|
49
|
+
"typescript": "^6.0.3",
|
|
50
|
+
"vitest": "^4.1.5"
|
|
51
|
+
},
|
|
52
|
+
"engines": {
|
|
53
|
+
"node": ">=24.0.0"
|
|
54
|
+
},
|
|
55
|
+
"scripts": {
|
|
56
|
+
"build": "tsdown",
|
|
57
|
+
"typecheck": "tsc --noEmit",
|
|
58
|
+
"test": "vitest",
|
|
59
|
+
"test:run": "vitest run"
|
|
60
|
+
}
|
|
61
|
+
}
|