@iso4/fetch 0.0.0 → 0.0.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/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,206 @@
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 or any
69
+ network call is made. 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
+ ### Request mutation (auth, URL rewrite, headers)
124
+
125
+ ```ts
126
+ async function someRequestMiddleware(ctx, next) {
127
+ ctx.req.header('authorization', `Bearer ${token}`) // injected, agent never sees it
128
+ ctx.req.setUrl(ctx.req.url.replace('/v1/', '/v2/'))
129
+ return next()
130
+ }
131
+ ```
132
+
133
+ `ctx.req` fields: `url` (via `setUrl()`), `method`, `headers` (mutable object
134
+ or `header(name, val)`), `body` (via `setBody()`), `params`, `hop`, `raw`
135
+ (original unmodified bridge request).
136
+
137
+ ### Response inspection / logging
138
+
139
+ ```ts
140
+ async function someResponseMiddleware(ctx, next) {
141
+ const t = Date.now()
142
+ const res = await next()
143
+ console.log(`${ctx.req.method} ${ctx.req.url} → ${res.status} (${Date.now() - t}ms)`)
144
+ return res
145
+ }
146
+ ```
147
+
148
+ ### Response rewrite (replaces `transform`)
149
+
150
+ ```ts
151
+ async function someResponseRewriteMiddleware(_ctx, next) {
152
+ const res = await next()
153
+ const data = JSON.parse(new TextDecoder().decode(res.body as Uint8Array))
154
+ return { ...res, body: data } // agent gets res.body as a parsed object
155
+ }
156
+ ```
157
+
158
+ ### Synthetic response — no HTTP (replaces `handle`)
159
+
160
+ Skip `next()` entirely. No network call is made.
161
+
162
+ ```ts
163
+ async function someSyntheticResponseMiddleware(ctx, _next) {
164
+ return {
165
+ status: 202,
166
+ headers: { 'content-type': 'application/json' },
167
+ body: { queued: true, id: ctx.req.params['id'] },
168
+ }
169
+ }
170
+ ```
171
+
172
+ ## Policy callback
173
+
174
+ For dynamic allow/deny logic that can't be expressed as static rules —
175
+ per-tenant checks, rate limiting, etc. Falls back to this when no origin rule
176
+ matches, or is the sole mechanism when `rules` is omitted.
177
+
178
+ ```ts
179
+ createSafeFetch({
180
+ policy: async ({ host, method, resolvedIp }) => {
181
+ if (resolvedIp && isInternal(resolvedIp))
182
+ return false
183
+ const tenant = await db.findByHost(host)
184
+ return tenant?.allowedMethods.includes(method) ?? false
185
+ },
186
+ })
187
+ ```
188
+
189
+ `policy` runs only when no `rules` origin matched. If an origin matches but
190
+ no route does the request is denied without consulting `policy`.
191
+
192
+ ## Security defaults
193
+
194
+ | Threat | Mitigation |
195
+ | ---------------------- | ---------------------------------------------------------------------------- |
196
+ | SSRF / private IP | DNS pre-resolved before every request; loopback, RFC1918, link-local blocked |
197
+ | DNS rebinding | undici DNS interceptor pins the connection to the resolved IP |
198
+ | Redirect bypass | No auto-follow by default; allow/deny re-checked on each hop |
199
+ | Response amplification | Body streamed with `maxBodyBytes` cap |
200
+ | Host auth leakage | Isolated undici `Agent` — no shared pool, cookies, or auth with the host app |
201
+ | Path traversal | Paths decoded and `.`/`..`-normalised before route matching |
202
+ | Double-encoded paths | Detected and rejected at parse time |
203
+
204
+ ## License
205
+
206
+ MIT
@@ -0,0 +1,402 @@
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.
106
+ */
107
+ setUrl: (url: string) => void;
108
+ /**
109
+ * Replace the outgoing body.
110
+ */
111
+ setBody: (body: Uint8Array | string | null) => void;
112
+ }
113
+ /**
114
+ * Context passed to every `FetchMiddleware`.
115
+ *
116
+ * `req` is the mutable outgoing request (mutate before `next()`).
117
+ * `res` is the response being built (`null` until `next()` completes or a
118
+ * middleware returns a response directly). Read and reassign after `next()`
119
+ * to inspect or replace the response.
120
+ */
121
+ interface FetchContext {
122
+ readonly req: FetchContextReq;
123
+ /**
124
+ * The response. `null` before `next()` is called.
125
+ * After `next()`, holds the response from downstream.
126
+ * Assign to replace it:
127
+ * ```ts
128
+ * await next()
129
+ * ctx.res = { ...ctx.res!, body: parsed }
130
+ * ```
131
+ */
132
+ res: HostFetchResponse | null;
133
+ }
134
+ /**
135
+ * A middleware function that runs after the allow/deny check and before the
136
+ * real HTTP call. Mutations to `ctx.req` are invisible to the agent but
137
+ * applied to every outgoing request that matches the level the middleware
138
+ * is attached to.
139
+ *
140
+ * Three levels of middleware are available — global (on `createSafeFetch`),
141
+ * origin (on `FetchOriginRule`), and route (on `FetchRouteRule`). They run
142
+ * in that order so more specific middleware runs last and can override
143
+ * broader changes.
144
+ *
145
+ * @example inject auth (covers every case: auth, logging, URL rewriting)
146
+ * ```ts
147
+ * async (ctx) => {
148
+ * ctx.req.header('authorization', `Bearer ${await vault.get('key')}`)
149
+ * console.log(`→ ${ctx.req.method} ${ctx.req.url}`)
150
+ * }
151
+ * ```
152
+ */
153
+ /**
154
+ * Runs the downstream middleware chain and ultimately the real HTTP call.
155
+ * Sets `ctx.res` when it completes. Returns `void` — read `ctx.res` after
156
+ * awaiting to inspect the response.
157
+ */
158
+ type Next = () => Promise<void>;
159
+ /**
160
+ * A middleware function in the `(ctx, next)` style.
161
+ *
162
+ * **Return value semantics:**
163
+ * - Return `void` / nothing — chain continues; `ctx.res` propagates as-is.
164
+ * - Return a `HostFetchResponse` — that response is set on `ctx.res` and
165
+ * returned to the agent immediately. Outer middleware still runs its
166
+ * after-`next()` code but the HTTP call is skipped.
167
+ * - `throw` — execution terminates; the sandbox `fetch()` call rejects.
168
+ * Use this to block a request with an error visible to the agent.
169
+ *
170
+ * **Pattern: mutate request (auth, URL rewrite)**
171
+ * ```ts
172
+ * async (ctx, next) => {
173
+ * ctx.req.header('authorization', `Bearer ${await vault.get('key')}`)
174
+ * await next()
175
+ * }
176
+ * ```
177
+ *
178
+ * **Pattern: inspect / rewrite response**
179
+ * ```ts
180
+ * async (ctx, next) => {
181
+ * await next()
182
+ * ctx.res = { ...ctx.res!, body: JSON.parse(new TextDecoder().decode(ctx.res!.body as Uint8Array)) }
183
+ * }
184
+ * ```
185
+ *
186
+ * **Pattern: log timing**
187
+ * ```ts
188
+ * async (ctx, next) => {
189
+ * const t = Date.now()
190
+ * await next()
191
+ * console.log(`${ctx.req.method} ${ctx.req.url} → ${ctx.res?.status} (${Date.now() - t}ms)`)
192
+ * }
193
+ * ```
194
+ *
195
+ * **Pattern: synthetic response (no HTTP)**
196
+ * ```ts
197
+ * async (ctx, _next) => ({
198
+ * status: 202,
199
+ * headers: { 'content-type': 'application/json' },
200
+ * body: { queued: true, id: ctx.req.params['id'] },
201
+ * })
202
+ * ```
203
+ *
204
+ * **Pattern: block with error**
205
+ * ```ts
206
+ * async (ctx, next) => {
207
+ * if (isSuspicious(ctx.req)) throw new Error('request blocked')
208
+ * await next()
209
+ * }
210
+ * ```
211
+ */
212
+ type FetchMiddleware = (ctx: FetchContext, next: Next) => HostFetchResponse | void | Promise<HostFetchResponse | void>;
213
+ /**
214
+ * A single route entry within a `FetchOriginRule`.
215
+ *
216
+ * Path patterns use URLPattern/rou3 syntax:
217
+ * `/users/:id` — named parameter
218
+ * `/v2/events` — exact match
219
+ * `/reports/**` — zero-or-more sub-path segments
220
+ * `/files/:ext(png|jpg)` — constrained parameter
221
+ */
222
+ interface FetchRouteRule {
223
+ /**
224
+ * Path pattern. Must start with `/`.
225
+ * `/**` and `/prefix/**` both match the prefix itself (zero-segment wildcard).
226
+ */
227
+ path: string;
228
+ /**
229
+ * Allowed HTTP method(s). Case-insensitive.
230
+ * A string, an array, `'*'`, or omitted all mean "any method".
231
+ */
232
+ methods?: string | string[];
233
+ /**
234
+ * Middleware that runs for requests matching this specific route,
235
+ * after global and origin middleware. Route middleware runs last so it
236
+ * can override anything set at broader levels.
237
+ */
238
+ middleware?: FetchMiddleware;
239
+ }
240
+ /**
241
+ * Per-origin set of allowed routes.
242
+ */
243
+ interface FetchOriginRule {
244
+ /**
245
+ * Hostname(s) to match.
246
+ * - Exact: `'api.example.com'`
247
+ * - Single-level subdomain wildcard: `'*.example.com'`
248
+ * (matches `sub.example.com`, not `a.b.example.com` or `example.com`)
249
+ * - Array for multiple hostnames under the same routes.
250
+ */
251
+ host: string | string[];
252
+ /**
253
+ * Allowed port(s). When omitted, only the standard port for the protocol
254
+ * is allowed (443 for https, 80 for http).
255
+ */
256
+ port?: number | number[];
257
+ /**
258
+ * Require HTTPS. Default `true`. Must be explicitly `false` to allow HTTP.
259
+ *
260
+ * @default true
261
+ */
262
+ httpsOnly?: boolean;
263
+ /**
264
+ * Route rules for this origin. Method + path must match at least one entry.
265
+ * First match wins. An empty array denies all paths on this origin.
266
+ */
267
+ routes: FetchRouteRule[];
268
+ /**
269
+ * Middleware that runs for every matched request on this origin, after
270
+ * global middleware and before route middleware.
271
+ */
272
+ middleware?: FetchMiddleware;
273
+ }
274
+ interface SafeFetchRequest {
275
+ /**
276
+ * Full canonical URL string.
277
+ */
278
+ url: string;
279
+ /**
280
+ * Protocol without trailing colon — always `'http'` or `'https'`.
281
+ */
282
+ protocol: "http" | "https";
283
+ /**
284
+ * Hostname only, lowercased.
285
+ */
286
+ host: string;
287
+ /**
288
+ * Effective port — 443 or 80 when not explicit in the URL.
289
+ */
290
+ port: number;
291
+ /**
292
+ * Path plus query string, starting with `/`.
293
+ */
294
+ path: string;
295
+ /**
296
+ * Uppercased HTTP method.
297
+ */
298
+ method: string;
299
+ /**
300
+ * Request headers, names lowercased.
301
+ */
302
+ headers: Record<string, string>;
303
+ /**
304
+ * Resolved IP when `pinDns: true`. `null` when `pinDns: false` or when
305
+ * using policy-only mode without rules.
306
+ */
307
+ resolvedIp: string | null;
308
+ /**
309
+ * `0` for the initial request, `1+` for redirect hops.
310
+ */
311
+ hop: number;
312
+ }
313
+ /**
314
+ * Allow/deny predicate for a single request.
315
+ *
316
+ * - Return `true` to allow.
317
+ * - Return `false` to deny with a generic message.
318
+ * - `throw new Error('reason')` to deny with a custom message visible to
319
+ * sandbox code.
320
+ * - Async (returning a `Promise`) is supported.
321
+ */
322
+ type SafeFetchPolicy = (request: SafeFetchRequest) => boolean | Promise<boolean>;
323
+ interface SafeFetchOptions {
324
+ /**
325
+ * Declarative origin + route allowlist. At least one of `rules` or
326
+ * `policy` is required.
327
+ *
328
+ * If an origin matches but no route does → DENY (does not fall through to
329
+ * `policy`). If no origin matches → falls through to `policy` if provided.
330
+ */
331
+ rules?: FetchOriginRule | FetchOriginRule[];
332
+ /**
333
+ * Allow/deny callback — fallback for requests not matched by any rule, or
334
+ * the sole mechanism when `rules` is omitted.
335
+ */
336
+ policy?: SafeFetchPolicy;
337
+ /**
338
+ * Global middleware that runs for every allowed request, before origin and
339
+ * route middleware.
340
+ */
341
+ middleware?: FetchMiddleware;
342
+ /**
343
+ * Pre-resolve DNS and pin the connection to the resolved IP.
344
+ * Prevents SSRF and DNS rebinding. `SafeFetchRequest.resolvedIp` is set.
345
+ *
346
+ * @default true
347
+ */
348
+ pinDns?: boolean;
349
+ /**
350
+ * Auto-follow redirects up to this many hops. The full allow/deny +
351
+ * middleware chain re-runs on each hop. `0` passes 3xx responses through.
352
+ *
353
+ * @default 0
354
+ */
355
+ maxRedirects?: number;
356
+ /**
357
+ * Per-request timeout in milliseconds.
358
+ *
359
+ * @default 30_000
360
+ */
361
+ timeoutMs?: number;
362
+ /**
363
+ * Maximum response body size in bytes (streaming, enforced before the
364
+ * response reaches any caller).
365
+ *
366
+ * @default 16 * 1024 * 1024
367
+ */
368
+ maxBodyBytes?: number;
369
+ /**
370
+ * Allow compressed responses. When `false`, `Accept-Encoding: identity`
371
+ * is sent to prevent response-amplification attacks.
372
+ *
373
+ * @default false
374
+ */
375
+ allowCompressedResponses?: boolean;
376
+ /**
377
+ * Alert hook — called on every denial. Errors thrown here are ignored.
378
+ * For request logging use middleware with `next()`.
379
+ */
380
+ onDenied?: (request: SafeFetchRequest, reason: string) => void | Promise<void>;
381
+ }
382
+ //#endregion
383
+ //#region src/index.d.ts
384
+ /**
385
+ * Build a `BridgeWithShim` global that the sandbox layer wires into the
386
+ * prefix as both a secure bridge handler and a sandbox-side response wrapper.
387
+ *
388
+ * Pass directly as a global value:
389
+ * ```ts
390
+ * await sandbox.precompile({
391
+ * code: prefixSource,
392
+ * globals: { fetch: createSafeFetch({ rules: [...] }) },
393
+ * })
394
+ * ```
395
+ *
396
+ * Inside the sandbox the agent calls `fetch(url, init)` and gets back a
397
+ * response object with `.ok`, `.json()`, `.text()`, and `.bytes()`.
398
+ * @param options
399
+ */
400
+ declare function createSafeFetch(options: SafeFetchOptions): SafeFetchGlobal;
401
+ //#endregion
402
+ export { type FetchContext, type FetchContextReq, type FetchMiddleware, type FetchOriginRule, type FetchRouteRule, type HostFetchRequest, type HostFetchResponse, type Next, type SafeFetchFn, type SafeFetchGlobal, type SafeFetchOptions, type SafeFetchPolicy, type SafeFetchRequest, createSafeFetch };
package/dist/index.mjs ADDED
@@ -0,0 +1,459 @@
1
+ import { addRoute, createRouter, findRoute } from "rou3";
2
+ import { Agent, fetch, interceptors } from "undici";
3
+ import { lookup } from "node:dns/promises";
4
+ import { lookup as lookup$1 } from "node:dns";
5
+ //#region src/index.ts
6
+ /**
7
+ * \@iso4/fetch — public entry point.
8
+ * See `./types.ts` for the full option surface.
9
+ */
10
+ function isReservedIp(ip) {
11
+ if (ip.includes(":")) {
12
+ const addr = ip.toLowerCase().replace(/^\[|\]$/g, "");
13
+ if (addr === "::1") return true;
14
+ const firstWord = parseInt(addr.split(":")[0] ?? "0", 16);
15
+ if ((firstWord & 65472) === 65152) return true;
16
+ if ((firstWord & 65024) === 64512) return true;
17
+ if (addr.startsWith("::ffff:")) return isReservedIp(addr.slice(7));
18
+ return false;
19
+ }
20
+ const parts = ip.split(".").map(Number);
21
+ if (parts.length !== 4 || parts.some((p) => Number.isNaN(p) || p < 0 || p > 255)) return true;
22
+ const a = parts[0];
23
+ const b = parts[1] ?? 0;
24
+ const c = parts[2] ?? 0;
25
+ 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
+ }
27
+ async function resolveAndCheckIp(hostname) {
28
+ let addrs;
29
+ try {
30
+ addrs = await lookup(hostname, {
31
+ all: true,
32
+ family: 0
33
+ });
34
+ } catch (err) {
35
+ throw new Error(`fetch: DNS resolution failed for "${hostname}": ${err.message}`);
36
+ }
37
+ if (addrs.length === 0) throw new Error(`fetch: DNS resolution returned no addresses for "${hostname}"`);
38
+ for (const { address } of addrs) if (isReservedIp(address)) throw new Error(`fetch: request blocked — "${hostname}" resolves to private/reserved IP ${address}`);
39
+ return addrs[0].address;
40
+ }
41
+ function hostExact(requestHost, ruleHost) {
42
+ return !ruleHost.startsWith("*.") && requestHost === ruleHost;
43
+ }
44
+ function hostWildcard(requestHost, ruleHost) {
45
+ if (!ruleHost.startsWith("*.")) return false;
46
+ const domain = ruleHost.slice(2);
47
+ const expectedSegments = domain.split(".").length + 1;
48
+ return requestHost.split(".").length === expectedSegments && requestHost.endsWith(`.${domain}`);
49
+ }
50
+ function routeMethodsToRou3(methods) {
51
+ if (methods === void 0 || methods === "*") return [""];
52
+ if (typeof methods === "string") return [methods.toUpperCase()];
53
+ return methods.map((m) => m.toUpperCase());
54
+ }
55
+ function buildRouter(routes) {
56
+ const router = createRouter();
57
+ for (const route of routes) for (const method of routeMethodsToRou3(route.methods)) addRoute(router, method, route.path, route);
58
+ return router;
59
+ }
60
+ function compileRules(rawRules) {
61
+ return (Array.isArray(rawRules) ? rawRules : [rawRules]).map((rule) => ({
62
+ rule,
63
+ hosts: Array.isArray(rule.host) ? rule.host : [rule.host],
64
+ router: buildRouter(rule.routes)
65
+ }));
66
+ }
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
+ /**
73
+ * Two-pass origin matching: exact hostname rules are checked before wildcard
74
+ * rules, regardless of array order. Within the same priority level the first
75
+ * entry in the array wins. A `deny-route` result from any pass is final —
76
+ * the explicit origin grant is exhaustive.
77
+ * @param req
78
+ * @param compiled
79
+ */
80
+ function matchRules(req, compiled) {
81
+ for (const pass of ["exact", "wildcard"]) for (const { rule, hosts, router } of compiled) {
82
+ if (!(pass === "exact" ? hosts.some((rh) => hostExact(req.host, rh)) : hosts.some((rh) => hostWildcard(req.host, rh)))) continue;
83
+ if (rule.httpsOnly !== false && req.protocol !== "https") continue;
84
+ const standardPort = req.protocol === "https" ? 443 : 80;
85
+ if (rule.port !== void 0) {
86
+ if (!(Array.isArray(rule.port) ? rule.port : [rule.port]).includes(req.port)) continue;
87
+ } else if (req.port !== standardPort) continue;
88
+ if (rule.routes.length === 0) return { kind: "deny-route" };
89
+ let decodedPathname;
90
+ try {
91
+ decodedPathname = decodePath(new URL(req.url).pathname);
92
+ } catch {
93
+ return { kind: "deny-route" };
94
+ }
95
+ const matched = findRoute(router, req.method, decodedPathname, { normalize: true });
96
+ if (matched === void 0) return { kind: "deny-route" };
97
+ return {
98
+ kind: "allow",
99
+ originRule: rule,
100
+ matchedRule: matched.data,
101
+ params: matched.params ?? {}
102
+ };
103
+ }
104
+ return { kind: "no-origin" };
105
+ }
106
+ function makeFetchContext(initialUrl, method, initialHeaders, initialBody, params, hop, raw) {
107
+ let _url = initialUrl;
108
+ const _headers = { ...initialHeaders };
109
+ return {
110
+ req: {
111
+ method,
112
+ params,
113
+ hop,
114
+ raw,
115
+ body: initialBody,
116
+ get url() {
117
+ return _url;
118
+ },
119
+ get headers() {
120
+ return _headers;
121
+ },
122
+ header(name, value) {
123
+ _headers[name.toLowerCase()] = value;
124
+ },
125
+ setUrl(url) {
126
+ _url = url;
127
+ },
128
+ setBody(b) {
129
+ this.body = b;
130
+ }
131
+ },
132
+ res: null
133
+ };
134
+ }
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
+ async function readBody(body, maxBytes) {
163
+ if (body === null) return null;
164
+ const reader = body.getReader();
165
+ const chunks = [];
166
+ let total = 0;
167
+ try {
168
+ for (;;) {
169
+ const { done, value } = await reader.read();
170
+ if (done) break;
171
+ total += value.byteLength;
172
+ if (total > maxBytes) {
173
+ await reader.cancel();
174
+ throw new Error(`fetch: response body exceeds maxBodyBytes limit (${maxBytes} bytes)`);
175
+ }
176
+ chunks.push(value);
177
+ }
178
+ } finally {
179
+ reader.releaseLock();
180
+ }
181
+ const result = new Uint8Array(total);
182
+ let offset = 0;
183
+ for (const chunk of chunks) {
184
+ result.set(chunk, offset);
185
+ offset += chunk.byteLength;
186
+ }
187
+ return result;
188
+ }
189
+ const REDIRECT_STATUSES = new Set([
190
+ 301,
191
+ 302,
192
+ 303,
193
+ 307,
194
+ 308
195
+ ]);
196
+ async function httpRequest(url, method, headers, body, agent, timeoutMs, maxBodyBytes, incomingSignal) {
197
+ const signals = [AbortSignal.timeout(timeoutMs)];
198
+ if (incomingSignal !== void 0) signals.push(incomingSignal);
199
+ const signal = signals.length === 1 ? signals[0] : AbortSignal.any(signals);
200
+ const response = await fetch(url, {
201
+ method,
202
+ headers,
203
+ ...body !== null ? { body } : {},
204
+ dispatcher: agent,
205
+ signal,
206
+ redirect: "manual"
207
+ });
208
+ return {
209
+ response,
210
+ bodyBytes: await readBody(response.body, maxBodyBytes)
211
+ };
212
+ }
213
+ function headersToRecord(headers) {
214
+ const out = {};
215
+ headers.forEach((value, key) => {
216
+ out[key] = value;
217
+ });
218
+ return out;
219
+ }
220
+ function toHostFetchResponse(response, bodyBytes) {
221
+ return {
222
+ status: response.status,
223
+ statusText: response.statusText,
224
+ headers: headersToRecord(response.headers),
225
+ body: bodyBytes
226
+ };
227
+ }
228
+ /**
229
+ * Validates and parses the raw `...args: unknown[]` received from the bridge
230
+ * when sandbox code calls the registered global/import function.
231
+ *
232
+ * Expected call shape (mirrors the web fetch API):
233
+ * fn(url: string, init?: { method?: string, headers?: Record<string,string>, body?: string | Uint8Array | null })
234
+ *
235
+ * Throws a descriptive Error (visible to sandbox code) on any type mismatch.
236
+ * @param args
237
+ */
238
+ function parseFetchArgs(args) {
239
+ const url = args[0];
240
+ if (typeof url !== "string" || url.length === 0) throw new Error("fetch: first argument must be a non-empty URL string");
241
+ const init = args[1];
242
+ if (init !== void 0 && init !== null) {
243
+ if (typeof init !== "object" || Array.isArray(init)) throw new Error("fetch: second argument must be a plain object");
244
+ }
245
+ const initObj = init ?? {};
246
+ const method = initObj["method"];
247
+ if (method !== void 0 && typeof method !== "string") throw new Error("fetch: init.method must be a string");
248
+ const rawHeaders = initObj["headers"];
249
+ const headers = {};
250
+ if (rawHeaders !== void 0 && rawHeaders !== null) {
251
+ if (typeof rawHeaders !== "object" || Array.isArray(rawHeaders)) throw new Error("fetch: init.headers must be a plain object");
252
+ for (const [k, v] of Object.entries(rawHeaders)) {
253
+ if (typeof v !== "string") throw new Error(`fetch: init.headers["${k}"] must be a string`);
254
+ if (/[\r\n\x00]/.test(k) || /[\r\n\x00]/.test(v)) throw new Error(`fetch: header "${k}" contains illegal characters (CR, LF, or NUL)`);
255
+ if (k.toLowerCase() === "host") continue;
256
+ headers[k.toLowerCase()] = v;
257
+ }
258
+ }
259
+ const body = initObj["body"] ?? null;
260
+ if (body !== null && typeof body !== "string" && !(body instanceof Uint8Array)) throw new Error("fetch: init.body must be a string, Uint8Array, or null");
261
+ return {
262
+ url,
263
+ method: typeof method === "string" ? method.toUpperCase() : "GET",
264
+ headers,
265
+ body
266
+ };
267
+ }
268
+ /**
269
+ * Build a `BridgeWithShim` global that the sandbox layer wires into the
270
+ * prefix as both a secure bridge handler and a sandbox-side response wrapper.
271
+ *
272
+ * Pass directly as a global value:
273
+ * ```ts
274
+ * await sandbox.precompile({
275
+ * code: prefixSource,
276
+ * globals: { fetch: createSafeFetch({ rules: [...] }) },
277
+ * })
278
+ * ```
279
+ *
280
+ * Inside the sandbox the agent calls `fetch(url, init)` and gets back a
281
+ * response object with `.ok`, `.json()`, `.text()`, and `.bytes()`.
282
+ * @param options
283
+ */
284
+ function createSafeFetch(options) {
285
+ return {
286
+ kind: "bridge-with-shim",
287
+ handler: buildSafeFetchHandler(options),
288
+ shim: `(result) => ({
289
+ ...result,
290
+ ok: result.status >= 200 && result.status < 300,
291
+ json: () => JSON.parse(new TextDecoder().decode(result.body)),
292
+ text: () => new TextDecoder().decode(result.body),
293
+ bytes: () => result.body instanceof Uint8Array
294
+ ? result.body
295
+ : new TextEncoder().encode(String(result.body ?? '')),
296
+ })`
297
+ };
298
+ }
299
+ /**
300
+ * Internal: builds the bridge handler (SafeFetchFn) without the shim.
301
+ * @param options
302
+ */
303
+ function buildSafeFetchHandler(options) {
304
+ if (options.rules === void 0 && options.policy === void 0) throw new TypeError("createSafeFetch: at least one of `rules` or `policy` must be provided");
305
+ const compiled = options.rules !== void 0 ? compileRules(options.rules) : [];
306
+ const doPinDns = options.pinDns !== false;
307
+ const maxRedirects = options.maxRedirects ?? 0;
308
+ const timeoutMs = options.timeoutMs ?? 3e4;
309
+ const maxBodyBytes = options.maxBodyBytes ?? 16 * 1024 * 1024;
310
+ const allowCompressed = options.allowCompressedResponses ?? false;
311
+ const agent = doPinDns ? new Agent().compose(interceptors.dns({
312
+ lookup: makeDnsLookupFn(),
313
+ maxTTL: 1e4,
314
+ dualStack: false,
315
+ affinity: 4
316
+ })) : new Agent();
317
+ async function buildSafeFetchRequest(parsedUrl, method, headers, hop) {
318
+ const protocol = parsedUrl.protocol.slice(0, -1);
319
+ if (protocol !== "http" && protocol !== "https") throw new Error(`fetch: unsupported protocol "${parsedUrl.protocol}"`);
320
+ const host = parsedUrl.hostname.toLowerCase();
321
+ const port = parsedUrl.port !== "" ? parseInt(parsedUrl.port, 10) : protocol === "https" ? 443 : 80;
322
+ let resolvedIp = null;
323
+ if (doPinDns) {
324
+ if (!(/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host) || host.startsWith("["))) resolvedIp = await resolveAndCheckIp(host);
325
+ else if (isReservedIp(host.replace(/^\[|\]$/g, ""))) throw new Error(`fetch: request blocked — IP literal ${host} is private/reserved`);
326
+ }
327
+ return {
328
+ url: parsedUrl.toString(),
329
+ protocol,
330
+ host,
331
+ port,
332
+ path: parsedUrl.pathname + parsedUrl.search,
333
+ method,
334
+ headers,
335
+ resolvedIp,
336
+ hop
337
+ };
338
+ }
339
+ async function runDeny(req, reason) {
340
+ try {
341
+ (options.onDenied?.(req, reason))?.catch(() => void 0);
342
+ } catch {}
343
+ throw new Error(reason);
344
+ }
345
+ async function checkRequest(req) {
346
+ if (compiled.length > 0) {
347
+ const result = matchRules(req, compiled);
348
+ if (result.kind === "allow") return {
349
+ originRule: result.originRule,
350
+ matchedRule: result.matchedRule,
351
+ params: result.params
352
+ };
353
+ if (result.kind === "deny-route") return runDeny(req, `fetch: request denied — no matching route for ${req.method} ${req.path} on ${req.host}`);
354
+ }
355
+ if (options.policy !== void 0) {
356
+ let allowed;
357
+ try {
358
+ allowed = await options.policy(req);
359
+ } catch (err) {
360
+ const reason = err.message || "request denied by policy";
361
+ try {
362
+ (options.onDenied?.(req, reason))?.catch(() => void 0);
363
+ } catch {}
364
+ throw err instanceof Error ? err : new Error(reason);
365
+ }
366
+ if (allowed) return null;
367
+ }
368
+ return runDeny(req, "fetch: request denied by policy");
369
+ }
370
+ /**
371
+ * Compose the middleware chain.
372
+ *
373
+ * Each middleware receives `next` = a function that runs the rest of the
374
+ * chain and sets `ctx.res`. If a middleware returns a `HostFetchResponse`
375
+ * the chain sets `ctx.res` to that value immediately (outer middleware still
376
+ * runs its after-next code). If middleware returns void the current `ctx.res`
377
+ * propagates. If middleware throws the whole chain rejects.
378
+ *
379
+ * `finalNext` is the innermost handler: real HTTP call + redirect loop.
380
+ * It sets `ctx.res` and returns void.
381
+ * @param middlewares
382
+ * @param ctx
383
+ * @param finalNext
384
+ */
385
+ function runMiddlewareChain(middlewares, ctx, finalNext) {
386
+ const active = middlewares.filter((m) => m !== void 0);
387
+ const dispatch = async (i) => {
388
+ if (i >= active.length) {
389
+ await finalNext();
390
+ return;
391
+ }
392
+ const result = await active[i](ctx, () => dispatch(i + 1));
393
+ if (result !== void 0 && result !== null) ctx.res = result;
394
+ };
395
+ return dispatch(0).then(() => {
396
+ if (ctx.res === null) throw new Error("fetch: middleware chain produced no response — at least one middleware must call next() or return a response");
397
+ return ctx.res;
398
+ });
399
+ }
400
+ return async (...args) => {
401
+ const hostRequest = parseFetchArgs(args);
402
+ let parsedUrl;
403
+ try {
404
+ parsedUrl = new URL(hostRequest.url);
405
+ } catch {
406
+ throw new Error(`fetch: invalid URL "${hostRequest.url}"`);
407
+ }
408
+ if (parsedUrl.username !== "" || parsedUrl.password !== "") {
409
+ parsedUrl.username = "";
410
+ parsedUrl.password = "";
411
+ }
412
+ const baseHeaders = { ...hostRequest.headers };
413
+ if (!allowCompressed) baseHeaders["accept-encoding"] = "identity";
414
+ delete baseHeaders["host"];
415
+ const method = hostRequest.method.toUpperCase();
416
+ const match = await checkRequest(await buildSafeFetchRequest(parsedUrl, method, baseHeaders, 0));
417
+ const ctx = makeFetchContext(parsedUrl.toString(), method, baseHeaders, hostRequest.body, match?.params ?? {}, 0, hostRequest);
418
+ const middlewares = [
419
+ options.middleware,
420
+ match?.originRule.middleware,
421
+ match?.matchedRule.middleware
422
+ ];
423
+ const finalNext = async () => {
424
+ let currentUrl = ctx.req.url;
425
+ let currentMethod = method;
426
+ let currentBody = ctx.req.body;
427
+ let hop = 0;
428
+ for (;;) {
429
+ const { response, bodyBytes } = await httpRequest(currentUrl, currentMethod, ctx.req.headers, currentBody, agent, timeoutMs, maxBodyBytes, hostRequest.signal);
430
+ if (!REDIRECT_STATUSES.has(response.status) || hop >= maxRedirects) {
431
+ ctx.res = toHostFetchResponse(response, bodyBytes);
432
+ return;
433
+ }
434
+ const location = response.headers.get("location");
435
+ if (location === null) {
436
+ ctx.res = toHostFetchResponse(response, bodyBytes);
437
+ return;
438
+ }
439
+ let nextUrl;
440
+ try {
441
+ nextUrl = new URL(location, currentUrl);
442
+ } catch {
443
+ ctx.res = toHostFetchResponse(response, bodyBytes);
444
+ return;
445
+ }
446
+ hop++;
447
+ await checkRequest(await buildSafeFetchRequest(nextUrl, currentMethod, ctx.req.headers, hop));
448
+ if (response.status === 303 || (response.status === 301 || response.status === 302) && currentMethod === "POST") {
449
+ currentMethod = "GET";
450
+ currentBody = null;
451
+ }
452
+ currentUrl = nextUrl.toString();
453
+ }
454
+ };
455
+ return runMiddlewareChain(middlewares, ctx, finalNext);
456
+ };
457
+ }
458
+ //#endregion
459
+ export { createSafeFetch };
package/package.json CHANGED
@@ -1,8 +1,60 @@
1
1
  {
2
2
  "name": "@iso4/fetch",
3
- "version": "0.0.0",
4
- "description": "placeholder",
5
- "license": "MIT",
3
+ "version": "0.0.1",
6
4
  "type": "module",
7
- "exports": {}
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
+ "typescript": "^6.0.3",
49
+ "vitest": "^4.1.5"
50
+ },
51
+ "engines": {
52
+ "node": ">=24.0.0"
53
+ },
54
+ "scripts": {
55
+ "build": "tsdown",
56
+ "typecheck": "tsc --noEmit",
57
+ "test": "vitest",
58
+ "test:run": "vitest run"
59
+ }
60
+ }