@iso4/fetch 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/index.d.mts +307 -309
- package/dist/index.mjs +4 -6
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -88,14 +88,18 @@ const fetch = createSafeFetch({
|
|
|
88
88
|
})
|
|
89
89
|
```
|
|
90
90
|
|
|
91
|
-
Path patterns use [rou3](https://github.com/h3js/rou3) / URLPattern syntax:
|
|
91
|
+
Path patterns use [rou3](https://github.com/h3js/rou3) 1.x / URLPattern syntax:
|
|
92
92
|
|
|
93
93
|
| Pattern | Matches |
|
|
94
94
|
| ----------------------- | -------------------------------------------------------------- |
|
|
95
95
|
| `/users/:id` | `/users/42` — named param, available as `ctx.req.params.id` |
|
|
96
96
|
| `/api/**` | `/api`, `/api/users`, `/api/users/123` — zero-or-more segments |
|
|
97
|
+
| `/files/*` | `/files`, `/files/a`, `/files/a/b` — `*` spans segments too |
|
|
97
98
|
| `/files/:ext(png\|jpg)` | `/files/png` — constrained param |
|
|
98
99
|
|
|
100
|
+
Use `:name` when a part must stay inside one segment. A pattern rou3 cannot
|
|
101
|
+
read throws when the rules are created.
|
|
102
|
+
|
|
99
103
|
An empty `routes: []` denies all paths on that origin.
|
|
100
104
|
|
|
101
105
|
## Middleware
|
package/dist/index.d.mts
CHANGED
|
@@ -1,29 +1,28 @@
|
|
|
1
|
-
//#region src/types.d.ts
|
|
2
1
|
/**
|
|
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
|
-
*/
|
|
2
|
+
* \@iso4/fetch — FetchHandler types and option/policy types for hardened fetch.
|
|
3
|
+
*
|
|
4
|
+
* The responsibility split: `iso4` handles mechanical hygiene, this package
|
|
5
|
+
* provides hardened defaults, and host application code supplies policy.
|
|
6
|
+
*/
|
|
8
7
|
/**
|
|
9
|
-
* The request object a FetchHandler receives from the bridge when the sandbox
|
|
10
|
-
* calls `fetch(url, init)`.
|
|
11
|
-
*/
|
|
8
|
+
* The request object a FetchHandler receives from the bridge when the sandbox
|
|
9
|
+
* calls `fetch(url, init)`.
|
|
10
|
+
*/
|
|
12
11
|
interface HostFetchRequest {
|
|
13
12
|
url: string;
|
|
14
13
|
method: string;
|
|
15
14
|
/**
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
* Header names are lowercased.
|
|
16
|
+
*/
|
|
18
17
|
headers: Record<string, string>;
|
|
19
18
|
/**
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
* `null` for bodyless methods.
|
|
20
|
+
*/
|
|
22
21
|
body: Uint8Array | string | null;
|
|
23
22
|
/**
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
23
|
+
* Planned — not yet wired from the bridge; present here so the type is
|
|
24
|
+
* forward-compatible.
|
|
25
|
+
*/
|
|
27
26
|
signal?: AbortSignal;
|
|
28
27
|
}
|
|
29
28
|
interface HostFetchResponse {
|
|
@@ -31,408 +30,407 @@ interface HostFetchResponse {
|
|
|
31
30
|
statusText?: string;
|
|
32
31
|
headers: Record<string, string>;
|
|
33
32
|
/**
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
33
|
+
* Any V8-serializable value — the bridge carries it as plain data.
|
|
34
|
+
* Use `Uint8Array` for raw bytes, `string` for text, a plain object or
|
|
35
|
+
* array for parsed JSON, or `null` for bodyless responses.
|
|
36
|
+
*/
|
|
38
37
|
body: unknown;
|
|
39
38
|
}
|
|
40
39
|
/**
|
|
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. For host code use `createSafeFetcher`.
|
|
47
|
-
*/
|
|
40
|
+
* The internal bridge handler produced by `createSafeFetch`. Validates raw
|
|
41
|
+
* bridge args, runs allow/deny, makes the HTTP call, and returns plain data.
|
|
42
|
+
*
|
|
43
|
+
* Returned as the `handler` field of `BridgeWithShim` — not meant to be
|
|
44
|
+
* used directly. Assign `createSafeFetch({...})` to a global and the sandbox
|
|
45
|
+
* layer handles wiring. For host code use `createSafeFetcher`.
|
|
46
|
+
*/
|
|
48
47
|
type SafeFetchFn = (...args: unknown[]) => Promise<HostFetchResponse>;
|
|
49
48
|
/**
|
|
50
|
-
* What `createSafeFetcher` returns: a `fetch`-compatible function that runs
|
|
51
|
-
* the safe pipeline in host code and resolves to a real `Response`.
|
|
52
|
-
*/
|
|
49
|
+
* What `createSafeFetcher` returns: a `fetch`-compatible function that runs
|
|
50
|
+
* the safe pipeline in host code and resolves to a real `Response`.
|
|
51
|
+
*/
|
|
53
52
|
type SafeFetcher = (...args: Parameters<typeof fetch>) => Promise<Response>;
|
|
54
53
|
/**
|
|
55
|
-
* What `createSafeFetch` returns. Conforms to `BridgeWithShim` from
|
|
56
|
-
* `@iso4/sandbox` so it can be passed directly as a global value.
|
|
57
|
-
*
|
|
58
|
-
* Declared locally to avoid a cross-package type dependency — structurally
|
|
59
|
-
* compatible with the sandbox type.
|
|
60
|
-
*/
|
|
54
|
+
* What `createSafeFetch` returns. Conforms to `BridgeWithShim` from
|
|
55
|
+
* `@iso4/sandbox` so it can be passed directly as a global value.
|
|
56
|
+
*
|
|
57
|
+
* Declared locally to avoid a cross-package type dependency — structurally
|
|
58
|
+
* compatible with the sandbox type.
|
|
59
|
+
*/
|
|
61
60
|
interface SafeFetchGlobal {
|
|
62
61
|
kind: "bridge-with-shim";
|
|
63
62
|
handler: SafeFetchFn;
|
|
64
63
|
shim: string;
|
|
65
64
|
}
|
|
66
65
|
/**
|
|
67
|
-
* The mutable request side of the middleware context.
|
|
68
|
-
*
|
|
69
|
-
* All mutations are invisible to the sandbox agent — they only affect what
|
|
70
|
-
* goes on the wire. `raw` preserves the original unmodified request from
|
|
71
|
-
* the bridge at all times.
|
|
72
|
-
*/
|
|
66
|
+
* The mutable request side of the middleware context.
|
|
67
|
+
*
|
|
68
|
+
* All mutations are invisible to the sandbox agent — they only affect what
|
|
69
|
+
* goes on the wire. `raw` preserves the original unmodified request from
|
|
70
|
+
* the bridge at all times.
|
|
71
|
+
*/
|
|
73
72
|
interface FetchContextReq {
|
|
74
73
|
/**
|
|
75
|
-
|
|
76
|
-
|
|
74
|
+
* Current URL (starts as the agent's URL; updated by `setUrl`).
|
|
75
|
+
*/
|
|
77
76
|
readonly url: string;
|
|
78
77
|
/**
|
|
79
|
-
|
|
80
|
-
|
|
78
|
+
* HTTP method, uppercased.
|
|
79
|
+
*/
|
|
81
80
|
readonly method: string;
|
|
82
81
|
/**
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
82
|
+
* Route parameters extracted by the path pattern.
|
|
83
|
+
* e.g. `/users/:id` matching `/users/42` → `{ id: '42' }`.
|
|
84
|
+
*/
|
|
86
85
|
readonly params: Record<string, string>;
|
|
87
86
|
/**
|
|
88
|
-
|
|
89
|
-
|
|
87
|
+
* Redirect hop index — 0 for the initial request.
|
|
88
|
+
*/
|
|
90
89
|
readonly hop: number;
|
|
91
90
|
/**
|
|
92
|
-
|
|
93
|
-
|
|
91
|
+
* Original untouched request from the bridge.
|
|
92
|
+
*/
|
|
94
93
|
readonly raw: HostFetchRequest;
|
|
95
94
|
/**
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
95
|
+
* Outgoing headers. Mutate directly or use `header()` for automatic
|
|
96
|
+
* lowercasing. These replace whatever the agent sent.
|
|
97
|
+
*/
|
|
99
98
|
headers: Record<string, string>;
|
|
100
99
|
/**
|
|
101
|
-
|
|
102
|
-
|
|
100
|
+
* Outgoing body. Mutate directly or use `setBody()`.
|
|
101
|
+
*/
|
|
103
102
|
body: Uint8Array | string | null;
|
|
104
103
|
/**
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
104
|
+
* Set (or overwrite) a single outgoing header.
|
|
105
|
+
* The name is lowercased automatically.
|
|
106
|
+
*/
|
|
108
107
|
header: (name: string, value: string) => void;
|
|
109
108
|
/**
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
109
|
+
* Replace the outgoing URL. Trusted host operation: the new URL is **not**
|
|
110
|
+
* re-checked against the allow/deny + SSRF rules — those run once, on the
|
|
111
|
+
* agent's original URL, which also fixes the middleware pipeline and
|
|
112
|
+
* `params` for the request. Validate a URL derived from agent-influenced
|
|
113
|
+
* data before setting it. (Redirect hops, by contrast, are re-checked.)
|
|
114
|
+
*/
|
|
116
115
|
setUrl: (url: string) => void;
|
|
117
116
|
/**
|
|
118
|
-
|
|
119
|
-
|
|
117
|
+
* Replace the outgoing body.
|
|
118
|
+
*/
|
|
120
119
|
setBody: (body: Uint8Array | string | null) => void;
|
|
121
120
|
}
|
|
122
121
|
/**
|
|
123
|
-
* Context passed to every `FetchMiddleware`.
|
|
124
|
-
*
|
|
125
|
-
* `req` is the mutable outgoing request (mutate before `next()`).
|
|
126
|
-
* `res` is the response being built (`null` until `next()` completes or a
|
|
127
|
-
* middleware returns a response directly). Read and reassign after `next()`
|
|
128
|
-
* to inspect or replace the response.
|
|
129
|
-
*/
|
|
122
|
+
* Context passed to every `FetchMiddleware`.
|
|
123
|
+
*
|
|
124
|
+
* `req` is the mutable outgoing request (mutate before `next()`).
|
|
125
|
+
* `res` is the response being built (`null` until `next()` completes or a
|
|
126
|
+
* middleware returns a response directly). Read and reassign after `next()`
|
|
127
|
+
* to inspect or replace the response.
|
|
128
|
+
*/
|
|
130
129
|
interface FetchContext {
|
|
131
130
|
readonly req: FetchContextReq;
|
|
132
131
|
/**
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
132
|
+
* The response. `null` before `next()` is called.
|
|
133
|
+
* After `next()`, holds the response from downstream.
|
|
134
|
+
* Assign to replace it:
|
|
135
|
+
* ```ts
|
|
136
|
+
* await next()
|
|
137
|
+
* ctx.res = { ...ctx.res!, body: parsed }
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
141
140
|
res: HostFetchResponse | null;
|
|
142
141
|
}
|
|
143
142
|
/**
|
|
144
|
-
* A middleware function that runs after the allow/deny check and before the
|
|
145
|
-
* real HTTP call. Mutations to `ctx.req` are invisible to the agent but
|
|
146
|
-
* applied to every outgoing request that matches the level the middleware
|
|
147
|
-
* is attached to.
|
|
148
|
-
*
|
|
149
|
-
* Three levels of middleware are available — global (on `createSafeFetch`),
|
|
150
|
-
* origin (on `FetchOriginRule`), and route (on `FetchRouteRule`). They run
|
|
151
|
-
* in that order so more specific middleware runs last and can override
|
|
152
|
-
* broader changes.
|
|
153
|
-
*
|
|
154
|
-
* @example inject auth (covers every case: auth, logging, URL rewriting)
|
|
155
|
-
* ```ts
|
|
156
|
-
* async (ctx) => {
|
|
157
|
-
* ctx.req.header('authorization', `Bearer ${await vault.get('key')}`)
|
|
158
|
-
* console.log(`→ ${ctx.req.method} ${ctx.req.url}`)
|
|
159
|
-
* }
|
|
160
|
-
* ```
|
|
161
|
-
*/
|
|
143
|
+
* A middleware function that runs after the allow/deny check and before the
|
|
144
|
+
* real HTTP call. Mutations to `ctx.req` are invisible to the agent but
|
|
145
|
+
* applied to every outgoing request that matches the level the middleware
|
|
146
|
+
* is attached to.
|
|
147
|
+
*
|
|
148
|
+
* Three levels of middleware are available — global (on `createSafeFetch`),
|
|
149
|
+
* origin (on `FetchOriginRule`), and route (on `FetchRouteRule`). They run
|
|
150
|
+
* in that order so more specific middleware runs last and can override
|
|
151
|
+
* broader changes.
|
|
152
|
+
*
|
|
153
|
+
* @example inject auth (covers every case: auth, logging, URL rewriting)
|
|
154
|
+
* ```ts
|
|
155
|
+
* async (ctx) => {
|
|
156
|
+
* ctx.req.header('authorization', `Bearer ${await vault.get('key')}`)
|
|
157
|
+
* console.log(`→ ${ctx.req.method} ${ctx.req.url}`)
|
|
158
|
+
* }
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
162
161
|
/**
|
|
163
|
-
* Runs the downstream middleware chain and ultimately the real HTTP call.
|
|
164
|
-
* Sets `ctx.res` when it completes. Returns `void` — read `ctx.res` after
|
|
165
|
-
* awaiting to inspect the response.
|
|
166
|
-
*/
|
|
162
|
+
* Runs the downstream middleware chain and ultimately the real HTTP call.
|
|
163
|
+
* Sets `ctx.res` when it completes. Returns `void` — read `ctx.res` after
|
|
164
|
+
* awaiting to inspect the response.
|
|
165
|
+
*/
|
|
167
166
|
type Next = () => Promise<void>;
|
|
168
167
|
/**
|
|
169
|
-
* A middleware function in the `(ctx, next)` style.
|
|
170
|
-
*
|
|
171
|
-
* **Return value semantics:**
|
|
172
|
-
* - Return `void` / nothing — chain continues; `ctx.res` propagates as-is.
|
|
173
|
-
* - Return a `HostFetchResponse` — that response is set on `ctx.res` and
|
|
174
|
-
* returned to the agent immediately. Outer middleware still runs its
|
|
175
|
-
* after-`next()` code but the HTTP call is skipped.
|
|
176
|
-
* - `throw` — execution terminates; the sandbox `fetch()` call rejects.
|
|
177
|
-
* Use this to block a request with an error visible to the agent.
|
|
178
|
-
*
|
|
179
|
-
* **Pattern: mutate request (auth, URL rewrite)**
|
|
180
|
-
* ```ts
|
|
181
|
-
* async (ctx, next) => {
|
|
182
|
-
* ctx.req.header('authorization', `Bearer ${await vault.get('key')}`)
|
|
183
|
-
* await next()
|
|
184
|
-
* }
|
|
185
|
-
* ```
|
|
186
|
-
*
|
|
187
|
-
* **Pattern: inspect / rewrite response**
|
|
188
|
-
* ```ts
|
|
189
|
-
* async (ctx, next) => {
|
|
190
|
-
* await next()
|
|
191
|
-
* ctx.res = { ...ctx.res!, body: JSON.parse(new TextDecoder().decode(ctx.res!.body as Uint8Array)) }
|
|
192
|
-
* }
|
|
193
|
-
* ```
|
|
194
|
-
*
|
|
195
|
-
* **Pattern: log timing**
|
|
196
|
-
* ```ts
|
|
197
|
-
* async (ctx, next) => {
|
|
198
|
-
* const t = Date.now()
|
|
199
|
-
* await next()
|
|
200
|
-
* console.log(`${ctx.req.method} ${ctx.req.url} → ${ctx.res?.status} (${Date.now() - t}ms)`)
|
|
201
|
-
* }
|
|
202
|
-
* ```
|
|
203
|
-
*
|
|
204
|
-
* **Pattern: synthetic response (no HTTP)**
|
|
205
|
-
* ```ts
|
|
206
|
-
* async (ctx, _next) => ({
|
|
207
|
-
* status: 202,
|
|
208
|
-
* headers: { 'content-type': 'application/json' },
|
|
209
|
-
* body: { queued: true, id: ctx.req.params['id'] },
|
|
210
|
-
* })
|
|
211
|
-
* ```
|
|
212
|
-
*
|
|
213
|
-
* **Pattern: block with error**
|
|
214
|
-
* ```ts
|
|
215
|
-
* async (ctx, next) => {
|
|
216
|
-
* if (isSuspicious(ctx.req)) throw new Error('request blocked')
|
|
217
|
-
* await next()
|
|
218
|
-
* }
|
|
219
|
-
* ```
|
|
220
|
-
*/
|
|
168
|
+
* A middleware function in the `(ctx, next)` style.
|
|
169
|
+
*
|
|
170
|
+
* **Return value semantics:**
|
|
171
|
+
* - Return `void` / nothing — chain continues; `ctx.res` propagates as-is.
|
|
172
|
+
* - Return a `HostFetchResponse` — that response is set on `ctx.res` and
|
|
173
|
+
* returned to the agent immediately. Outer middleware still runs its
|
|
174
|
+
* after-`next()` code but the HTTP call is skipped.
|
|
175
|
+
* - `throw` — execution terminates; the sandbox `fetch()` call rejects.
|
|
176
|
+
* Use this to block a request with an error visible to the agent.
|
|
177
|
+
*
|
|
178
|
+
* **Pattern: mutate request (auth, URL rewrite)**
|
|
179
|
+
* ```ts
|
|
180
|
+
* async (ctx, next) => {
|
|
181
|
+
* ctx.req.header('authorization', `Bearer ${await vault.get('key')}`)
|
|
182
|
+
* await next()
|
|
183
|
+
* }
|
|
184
|
+
* ```
|
|
185
|
+
*
|
|
186
|
+
* **Pattern: inspect / rewrite response**
|
|
187
|
+
* ```ts
|
|
188
|
+
* async (ctx, next) => {
|
|
189
|
+
* await next()
|
|
190
|
+
* ctx.res = { ...ctx.res!, body: JSON.parse(new TextDecoder().decode(ctx.res!.body as Uint8Array)) }
|
|
191
|
+
* }
|
|
192
|
+
* ```
|
|
193
|
+
*
|
|
194
|
+
* **Pattern: log timing**
|
|
195
|
+
* ```ts
|
|
196
|
+
* async (ctx, next) => {
|
|
197
|
+
* const t = Date.now()
|
|
198
|
+
* await next()
|
|
199
|
+
* console.log(`${ctx.req.method} ${ctx.req.url} → ${ctx.res?.status} (${Date.now() - t}ms)`)
|
|
200
|
+
* }
|
|
201
|
+
* ```
|
|
202
|
+
*
|
|
203
|
+
* **Pattern: synthetic response (no HTTP)**
|
|
204
|
+
* ```ts
|
|
205
|
+
* async (ctx, _next) => ({
|
|
206
|
+
* status: 202,
|
|
207
|
+
* headers: { 'content-type': 'application/json' },
|
|
208
|
+
* body: { queued: true, id: ctx.req.params['id'] },
|
|
209
|
+
* })
|
|
210
|
+
* ```
|
|
211
|
+
*
|
|
212
|
+
* **Pattern: block with error**
|
|
213
|
+
* ```ts
|
|
214
|
+
* async (ctx, next) => {
|
|
215
|
+
* if (isSuspicious(ctx.req)) throw new Error('request blocked')
|
|
216
|
+
* await next()
|
|
217
|
+
* }
|
|
218
|
+
* ```
|
|
219
|
+
*/
|
|
221
220
|
type FetchMiddleware = (ctx: FetchContext, next: Next) => HostFetchResponse | void | Promise<HostFetchResponse | void>;
|
|
222
221
|
/**
|
|
223
|
-
* A single route entry within a `FetchOriginRule`.
|
|
224
|
-
*
|
|
225
|
-
* Path patterns use URLPattern/rou3 syntax:
|
|
226
|
-
* `/users/:id` — named parameter
|
|
227
|
-
* `/v2/events` — exact match
|
|
228
|
-
* `/reports/**` — zero-or-more sub-path segments
|
|
229
|
-
* `/files
|
|
230
|
-
|
|
222
|
+
* A single route entry within a `FetchOriginRule`.
|
|
223
|
+
*
|
|
224
|
+
* Path patterns use URLPattern/rou3 1.x syntax:
|
|
225
|
+
* `/users/:id` — named parameter, one segment
|
|
226
|
+
* `/v2/events` — exact match
|
|
227
|
+
* `/reports/**` — zero-or-more sub-path segments
|
|
228
|
+
* `/files/*` — catch-all; spans segments like `**`
|
|
229
|
+
* `/files/:ext(png|jpg)` — constrained parameter
|
|
230
|
+
* Invalid patterns throw when the rules are created.
|
|
231
|
+
*/
|
|
231
232
|
interface FetchRouteRule {
|
|
232
233
|
/**
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
234
|
+
* Path pattern. Must start with `/`.
|
|
235
|
+
* `/**` and `/prefix/**` both match the prefix itself (zero-segment wildcard).
|
|
236
|
+
*/
|
|
236
237
|
path: string;
|
|
237
238
|
/**
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
239
|
+
* Allowed HTTP method(s). Case-insensitive.
|
|
240
|
+
* A string, an array, `'*'`, or omitted all mean "any method".
|
|
241
|
+
*/
|
|
241
242
|
methods?: string | string[];
|
|
242
243
|
/**
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
244
|
+
* Middleware that runs for requests matching this specific route,
|
|
245
|
+
* after global and origin middleware. Route middleware runs last so it
|
|
246
|
+
* can override anything set at broader levels.
|
|
247
|
+
*/
|
|
247
248
|
middleware?: FetchMiddleware;
|
|
248
249
|
}
|
|
249
250
|
/**
|
|
250
|
-
* Per-origin set of allowed routes.
|
|
251
|
-
*/
|
|
251
|
+
* Per-origin set of allowed routes.
|
|
252
|
+
*/
|
|
252
253
|
interface FetchOriginRule {
|
|
253
254
|
/**
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
255
|
+
* Hostname(s) to match.
|
|
256
|
+
* - Exact: `'api.example.com'`
|
|
257
|
+
* - Single-level subdomain wildcard: `'*.example.com'`
|
|
258
|
+
* (matches `sub.example.com`, not `a.b.example.com` or `example.com`)
|
|
259
|
+
* - Array for multiple hostnames under the same routes.
|
|
260
|
+
*/
|
|
260
261
|
host: string | string[];
|
|
261
262
|
/**
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
263
|
+
* Allowed port(s). When omitted, only the standard port for the protocol
|
|
264
|
+
* is allowed (443 for https, 80 for http).
|
|
265
|
+
*/
|
|
265
266
|
port?: number | number[];
|
|
266
267
|
/**
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
268
|
+
* Require HTTPS. Default `true`. Must be explicitly `false` to allow HTTP.
|
|
269
|
+
*
|
|
270
|
+
* @default true
|
|
271
|
+
*/
|
|
271
272
|
httpsOnly?: boolean;
|
|
272
273
|
/**
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
274
|
+
* Route rules for this origin. Method + path must match at least one entry.
|
|
275
|
+
* First match wins. An empty array denies all paths on this origin.
|
|
276
|
+
*/
|
|
276
277
|
routes: FetchRouteRule[];
|
|
277
278
|
/**
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
279
|
+
* Middleware that runs for every matched request on this origin, after
|
|
280
|
+
* global middleware and before route middleware.
|
|
281
|
+
*/
|
|
281
282
|
middleware?: FetchMiddleware;
|
|
282
283
|
}
|
|
283
284
|
interface SafeFetchRequest {
|
|
284
285
|
/**
|
|
285
|
-
|
|
286
|
-
|
|
286
|
+
* Full canonical URL string.
|
|
287
|
+
*/
|
|
287
288
|
url: string;
|
|
288
289
|
/**
|
|
289
|
-
|
|
290
|
-
|
|
290
|
+
* Protocol without trailing colon — always `'http'` or `'https'`.
|
|
291
|
+
*/
|
|
291
292
|
protocol: "http" | "https";
|
|
292
293
|
/**
|
|
293
|
-
|
|
294
|
-
|
|
294
|
+
* Hostname only, lowercased.
|
|
295
|
+
*/
|
|
295
296
|
host: string;
|
|
296
297
|
/**
|
|
297
|
-
|
|
298
|
-
|
|
298
|
+
* Effective port — 443 or 80 when not explicit in the URL.
|
|
299
|
+
*/
|
|
299
300
|
port: number;
|
|
300
301
|
/**
|
|
301
|
-
|
|
302
|
-
|
|
302
|
+
* Path plus query string, starting with `/`.
|
|
303
|
+
*/
|
|
303
304
|
path: string;
|
|
304
305
|
/**
|
|
305
|
-
|
|
306
|
-
|
|
306
|
+
* Uppercased HTTP method.
|
|
307
|
+
*/
|
|
307
308
|
method: string;
|
|
308
309
|
/**
|
|
309
|
-
|
|
310
|
-
|
|
310
|
+
* Request headers, names lowercased.
|
|
311
|
+
*/
|
|
311
312
|
headers: Record<string, string>;
|
|
312
313
|
/**
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
314
|
+
* Always `null`. DNS is resolved only at connection time — after the request
|
|
315
|
+
* is authorized — so no resolved address is available to a `policy` or
|
|
316
|
+
* `onDenied`. The private/reserved-IP block still runs at that point. Kept
|
|
317
|
+
* for backward compatibility; do not rely on it.
|
|
318
|
+
*/
|
|
318
319
|
resolvedIp: string | null;
|
|
319
320
|
/**
|
|
320
|
-
|
|
321
|
-
|
|
321
|
+
* `0` for the initial request, `1+` for redirect hops.
|
|
322
|
+
*/
|
|
322
323
|
hop: number;
|
|
323
324
|
}
|
|
324
325
|
/**
|
|
325
|
-
* Allow/deny predicate for a single request.
|
|
326
|
-
*
|
|
327
|
-
* - Return `true` to allow.
|
|
328
|
-
* - Return `false` to deny with a generic message.
|
|
329
|
-
* - `throw new Error('reason')` to deny with a custom message visible to
|
|
330
|
-
* sandbox code.
|
|
331
|
-
* - Async (returning a `Promise`) is supported.
|
|
332
|
-
*/
|
|
326
|
+
* Allow/deny predicate for a single request.
|
|
327
|
+
*
|
|
328
|
+
* - Return `true` to allow.
|
|
329
|
+
* - Return `false` to deny with a generic message.
|
|
330
|
+
* - `throw new Error('reason')` to deny with a custom message visible to
|
|
331
|
+
* sandbox code.
|
|
332
|
+
* - Async (returning a `Promise`) is supported.
|
|
333
|
+
*/
|
|
333
334
|
type SafeFetchPolicy = (request: SafeFetchRequest) => boolean | Promise<boolean>;
|
|
334
335
|
interface SafeFetchOptions {
|
|
335
336
|
/**
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
337
|
+
* Declarative origin + route allowlist. At least one of `rules` or
|
|
338
|
+
* `policy` is required.
|
|
339
|
+
*
|
|
340
|
+
* If an origin matches but no route does → DENY (does not fall through to
|
|
341
|
+
* `policy`). If no origin matches → falls through to `policy` if provided.
|
|
342
|
+
*/
|
|
342
343
|
rules?: FetchOriginRule | FetchOriginRule[];
|
|
343
344
|
/**
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
345
|
+
* Allow/deny callback — fallback for requests not matched by any rule, or
|
|
346
|
+
* the sole mechanism when `rules` is omitted.
|
|
347
|
+
*/
|
|
347
348
|
policy?: SafeFetchPolicy;
|
|
348
349
|
/**
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
350
|
+
* Global middleware that runs for every allowed request, before origin and
|
|
351
|
+
* route middleware.
|
|
352
|
+
*/
|
|
352
353
|
middleware?: FetchMiddleware;
|
|
353
354
|
/**
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
355
|
+
* Resolve DNS and pin the connection to the resolved IP, refusing any
|
|
356
|
+
* private/reserved address. Prevents SSRF and DNS rebinding. Resolution
|
|
357
|
+
* happens at connection time, only for a request that already passed the
|
|
358
|
+
* allow/deny check, so a denied host is never looked up.
|
|
359
|
+
*
|
|
360
|
+
* Both address families are used, so a host that resolves to IPv6 only is
|
|
361
|
+
* reachable; every resolved address is checked against the private and
|
|
362
|
+
* reserved ranges of its own family before anything connects.
|
|
363
|
+
*
|
|
364
|
+
* @default true
|
|
365
|
+
*/
|
|
365
366
|
pinDns?: boolean;
|
|
366
367
|
/**
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
368
|
+
* Auto-follow redirects up to this many hops. The allow/deny policy is
|
|
369
|
+
* re-checked on every hop. On a cross-origin hop `authorization`, `cookie`
|
|
370
|
+
* and `proxy-authorization` are dropped, and on a method-changing hop (303,
|
|
371
|
+
* or POST to GET on 301/302) `content-*` headers are dropped — matching
|
|
372
|
+
* undici. Middleware runs once around the whole request, not per hop. `0`
|
|
373
|
+
* passes 3xx responses through.
|
|
374
|
+
*
|
|
375
|
+
* @default 0
|
|
376
|
+
*/
|
|
376
377
|
maxRedirects?: number;
|
|
377
378
|
/**
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
379
|
+
* Per-request timeout in milliseconds.
|
|
380
|
+
*
|
|
381
|
+
* @default 30_000
|
|
382
|
+
*/
|
|
382
383
|
timeoutMs?: number;
|
|
383
384
|
/**
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
385
|
+
* Maximum response body size in bytes (streaming, enforced before the
|
|
386
|
+
* response reaches any caller).
|
|
387
|
+
*
|
|
388
|
+
* @default 16 * 1024 * 1024
|
|
389
|
+
*/
|
|
389
390
|
maxBodyBytes?: number;
|
|
390
391
|
/**
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
392
|
+
* Allow compressed responses. When `false`, `Accept-Encoding: identity`
|
|
393
|
+
* is sent to prevent response-amplification attacks.
|
|
394
|
+
*
|
|
395
|
+
* @default false
|
|
396
|
+
*/
|
|
396
397
|
allowCompressedResponses?: boolean;
|
|
397
398
|
/**
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
399
|
+
* Alert hook — called on every denial. Errors thrown here are ignored.
|
|
400
|
+
* For request logging use middleware with `next()`.
|
|
401
|
+
*/
|
|
401
402
|
onDenied?: (request: SafeFetchRequest, reason: string) => void | Promise<void>;
|
|
402
403
|
}
|
|
403
|
-
//#endregion
|
|
404
|
-
//#region src/index.d.ts
|
|
405
404
|
/**
|
|
406
|
-
* Build a `BridgeWithShim` global that the sandbox layer wires into the
|
|
407
|
-
* prefix as both a secure bridge handler and a sandbox-side response wrapper.
|
|
408
|
-
*
|
|
409
|
-
* Pass directly as a global value:
|
|
410
|
-
* ```ts
|
|
411
|
-
* await sandbox.precompile({
|
|
412
|
-
* code: prefixSource,
|
|
413
|
-
* globals: { fetch: createSafeFetch({ rules: [...] }) },
|
|
414
|
-
* })
|
|
415
|
-
* ```
|
|
416
|
-
*
|
|
417
|
-
* Inside the sandbox the agent calls `fetch(url, init)` and gets back a
|
|
418
|
-
* response object with `.ok`, `.json()`, `.text()`, and `.bytes()`.
|
|
419
|
-
* @param options
|
|
420
|
-
*/
|
|
421
|
-
declare function createSafeFetch(options: SafeFetchOptions): SafeFetchGlobal;
|
|
405
|
+
* Build a `BridgeWithShim` global that the sandbox layer wires into the
|
|
406
|
+
* prefix as both a secure bridge handler and a sandbox-side response wrapper.
|
|
407
|
+
*
|
|
408
|
+
* Pass directly as a global value:
|
|
409
|
+
* ```ts
|
|
410
|
+
* await sandbox.precompile({
|
|
411
|
+
* code: prefixSource,
|
|
412
|
+
* globals: { fetch: createSafeFetch({ rules: [...] }) },
|
|
413
|
+
* })
|
|
414
|
+
* ```
|
|
415
|
+
*
|
|
416
|
+
* Inside the sandbox the agent calls `fetch(url, init)` and gets back a
|
|
417
|
+
* response object with `.ok`, `.json()`, `.text()`, and `.bytes()`.
|
|
418
|
+
* @param options
|
|
419
|
+
*/
|
|
420
|
+
export declare function createSafeFetch(options: SafeFetchOptions): SafeFetchGlobal;
|
|
422
421
|
/**
|
|
423
|
-
* Build a `fetch`-compatible function that runs the same safe pipeline as
|
|
424
|
-
* `createSafeFetch` directly in host code, with its own connection pool.
|
|
425
|
-
*
|
|
426
|
-
* ```ts
|
|
427
|
-
* const safeFetch = createSafeFetcher({ rules: [...] })
|
|
428
|
-
* const users = await (await safeFetch('https://api.example.com/v1/users')).json()
|
|
429
|
-
* ```
|
|
430
|
-
*
|
|
431
|
-
* `redirect`, `credentials` and the other transport options in `init` are
|
|
432
|
-
* ignored; `maxRedirects` decides. A middleware body that is not bytes or text
|
|
433
|
-
* is JSON-encoded.
|
|
434
|
-
* @param options
|
|
435
|
-
*/
|
|
436
|
-
declare function createSafeFetcher(options: SafeFetchOptions): SafeFetcher;
|
|
437
|
-
|
|
438
|
-
export { type FetchContext, type FetchContextReq, type FetchMiddleware, type FetchOriginRule, type FetchRouteRule, type HostFetchRequest, type HostFetchResponse, type Next, type SafeFetchFn, type SafeFetchGlobal, type SafeFetchOptions, type SafeFetchPolicy, type SafeFetchRequest, type SafeFetcher, createSafeFetch, createSafeFetcher };
|
|
422
|
+
* Build a `fetch`-compatible function that runs the same safe pipeline as
|
|
423
|
+
* `createSafeFetch` directly in host code, with its own connection pool.
|
|
424
|
+
*
|
|
425
|
+
* ```ts
|
|
426
|
+
* const safeFetch = createSafeFetcher({ rules: [...] })
|
|
427
|
+
* const users = await (await safeFetch('https://api.example.com/v1/users')).json()
|
|
428
|
+
* ```
|
|
429
|
+
*
|
|
430
|
+
* `redirect`, `credentials` and the other transport options in `init` are
|
|
431
|
+
* ignored; `maxRedirects` decides. A middleware body that is not bytes or text
|
|
432
|
+
* is JSON-encoded.
|
|
433
|
+
* @param options
|
|
434
|
+
*/
|
|
435
|
+
export declare function createSafeFetcher(options: SafeFetchOptions): SafeFetcher;
|
|
436
|
+
export type { FetchContext, FetchContextReq, FetchMiddleware, FetchOriginRule, FetchRouteRule, HostFetchRequest, HostFetchResponse, Next, SafeFetchFn, SafeFetchGlobal, SafeFetchOptions, SafeFetchPolicy, SafeFetchRequest, SafeFetcher };
|
package/dist/index.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { addRoute, createRouter, findRoute } from "rou3";
|
|
|
2
2
|
import { Agent, buildConnector, fetch, interceptors } from "undici";
|
|
3
3
|
import { lookup } from "node:dns";
|
|
4
4
|
import { isIPv6 } from "node:net";
|
|
5
|
-
|
|
5
|
+
// src/dns.ts
|
|
6
6
|
/**
|
|
7
7
|
* DNS for the connection-time pinning interceptor, plus the private/reserved-IP
|
|
8
8
|
* block that runs before undici connects.
|
|
@@ -111,8 +111,7 @@ function makeGuardedConnector() {
|
|
|
111
111
|
});
|
|
112
112
|
};
|
|
113
113
|
}
|
|
114
|
-
|
|
115
|
-
//#region src/index.ts
|
|
114
|
+
// src/index.ts
|
|
116
115
|
/**
|
|
117
116
|
* \@iso4/fetch — public entry point.
|
|
118
117
|
* See `./types.ts` for the full option surface.
|
|
@@ -235,7 +234,7 @@ async function readBody(body, maxBytes) {
|
|
|
235
234
|
}
|
|
236
235
|
return result;
|
|
237
236
|
}
|
|
238
|
-
const REDIRECT_STATUSES = new Set([
|
|
237
|
+
const REDIRECT_STATUSES = /* @__PURE__ */ new Set([
|
|
239
238
|
301,
|
|
240
239
|
302,
|
|
241
240
|
303,
|
|
@@ -417,7 +416,7 @@ function buildSafeFetchHandler(options) {
|
|
|
417
416
|
const doPinDns = options.pinDns !== false;
|
|
418
417
|
const maxRedirects = options.maxRedirects ?? 0;
|
|
419
418
|
const timeoutMs = options.timeoutMs ?? 3e4;
|
|
420
|
-
const maxBodyBytes = options.maxBodyBytes ??
|
|
419
|
+
const maxBodyBytes = options.maxBodyBytes ?? 16777216;
|
|
421
420
|
const allowCompressed = options.allowCompressedResponses ?? false;
|
|
422
421
|
const agent = doPinDns ? new Agent({ connect: makeGuardedConnector() }).compose(interceptors.dns({
|
|
423
422
|
lookup: makeDnsLookupFn(),
|
|
@@ -570,5 +569,4 @@ function buildSafeFetchHandler(options) {
|
|
|
570
569
|
return runMiddlewareChain(middlewares, ctx, finalNext);
|
|
571
570
|
};
|
|
572
571
|
}
|
|
573
|
-
//#endregion
|
|
574
572
|
export { createSafeFetch, createSafeFetcher };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@iso4/fetch",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Hardened FetchHandler for the @iso4/sandbox runtime: DNS pinning, host allowlist, private-IP blocking, no auto-redirect",
|
|
6
6
|
"keywords": [
|
|
@@ -37,14 +37,14 @@
|
|
|
37
37
|
"dist"
|
|
38
38
|
],
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"rou3": "^0.
|
|
40
|
+
"rou3": "^1.0.0",
|
|
41
41
|
"undici": "^6.29.1"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"@changesets/cli": "^2.31.1",
|
|
45
|
-
"@schplitt/eslint-config": "^1.
|
|
46
|
-
"eslint": "^10.
|
|
47
|
-
"tsdown": "^0.
|
|
45
|
+
"@schplitt/eslint-config": "^1.6.0",
|
|
46
|
+
"eslint": "^10.16.0",
|
|
47
|
+
"tsdown": "^0.23.7",
|
|
48
48
|
"tsnapi": "^1.6.1",
|
|
49
49
|
"typescript": "^6.0.3",
|
|
50
50
|
"vitest": "^4.1.12"
|