@memberjunction/code-execution 6.3.0-edge.1 → 6.3.0-edge.3
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/.turbo/turbo-build.log +2 -2
- package/CHANGELOG.md +60 -0
- package/README.md +5 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/networkFetch.d.ts +53 -0
- package/dist/networkFetch.d.ts.map +1 -0
- package/dist/networkFetch.js +412 -0
- package/dist/networkFetch.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types/index.d.ts +16 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/worker.js +71 -7
- package/dist/worker.js.map +1 -1
- package/package.json +4 -3
- package/src/__tests__/RuntimeActionExecutor.test.ts +59 -0
- package/src/__tests__/bridge.test.ts +22 -0
- package/src/__tests__/networkFetch.test.ts +298 -0
- package/src/index.ts +1 -0
- package/src/networkFetch.ts +514 -0
- package/src/types/index.ts +18 -1
- package/src/worker.ts +75 -7
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
import { promises as dns } from 'node:dns';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import https from 'node:https';
|
|
4
|
+
import { isIP } from 'node:net';
|
|
5
|
+
import { AssertPublicUrl, IsBlockedIPAddress, SSRFError } from '@memberjunction/network-utils';
|
|
6
|
+
|
|
7
|
+
const MAX_SANDBOX_REDIRECTS = 5; // Cap HTTP redirect hops to prevent redirect loops and match SafeFetch defaults
|
|
8
|
+
/**
|
|
9
|
+
* Maximum HTTP response body size buffered from a sandboxed `fetch()` call (5 MiB).
|
|
10
|
+
* Prevents untrusted remote servers from exhausting host memory via unbounded response streams.
|
|
11
|
+
*/
|
|
12
|
+
export const MAX_SANDBOX_RESPONSE_BYTES = 5 * 1024 * 1024;
|
|
13
|
+
|
|
14
|
+
const PRIVATE_HOSTNAME_SUFFIXES: readonly string[] = [
|
|
15
|
+
'.localhost',
|
|
16
|
+
'.localdomain',
|
|
17
|
+
'.internal',
|
|
18
|
+
'.local',
|
|
19
|
+
'.lan',
|
|
20
|
+
'.corp',
|
|
21
|
+
'.home',
|
|
22
|
+
'.home.arpa',
|
|
23
|
+
'.intranet',
|
|
24
|
+
'.private',
|
|
25
|
+
'.svc'
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
const BLOCKED_EXACT_HOSTNAMES = new Set<string>([
|
|
29
|
+
'localhost',
|
|
30
|
+
'metadata.google.internal',
|
|
31
|
+
'metadata.goog',
|
|
32
|
+
'host.docker.internal',
|
|
33
|
+
'gateway.docker.internal'
|
|
34
|
+
]);
|
|
35
|
+
|
|
36
|
+
const REDIRECT_STATUS_CODES = new Set<number>([301, 302, 303, 307, 308]);
|
|
37
|
+
const METHOD_DOWNGRADE_REDIRECT_CODES = new Set<number>([301, 302, 303]);
|
|
38
|
+
|
|
39
|
+
const SENSITIVE_REDIRECT_HEADERS: readonly string[] = [
|
|
40
|
+
'authorization',
|
|
41
|
+
'cookie',
|
|
42
|
+
'proxy-authorization',
|
|
43
|
+
'x-api-key'
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
const BODY_HEADERS: readonly string[] = [
|
|
47
|
+
'content-length',
|
|
48
|
+
'content-type',
|
|
49
|
+
'content-encoding',
|
|
50
|
+
'transfer-encoding'
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Options controlling host-mediated `fetch()` execution for sandboxed code.
|
|
55
|
+
*/
|
|
56
|
+
export interface SandboxFetchOptions {
|
|
57
|
+
/** Execution timeout in milliseconds applied to each request hop. */
|
|
58
|
+
TimeoutMs: number;
|
|
59
|
+
/** Optional destination host allowlist (exact hostnames or `*.domain` wildcards). */
|
|
60
|
+
AllowedNetworkHosts?: readonly string[];
|
|
61
|
+
/**
|
|
62
|
+
* When `true`, refuses all outbound requests unless `AllowedNetworkHosts` contains at least
|
|
63
|
+
* one non-empty entry.
|
|
64
|
+
*/
|
|
65
|
+
RequireAllowlist?: boolean;
|
|
66
|
+
/** Maximum response body size in bytes (defaults to {@link MAX_SANDBOX_RESPONSE_BYTES}). */
|
|
67
|
+
MaxResponseBytes?: number;
|
|
68
|
+
/** Optional fetch implementation override for deterministic testing. */
|
|
69
|
+
FetchImpl?: typeof globalThis.fetch;
|
|
70
|
+
/** Optional URL/DNS SSRF validator override for deterministic testing. */
|
|
71
|
+
AssertPublicUrlImpl?: typeof AssertPublicUrl;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Serialized HTTP response envelope returned across the isolate boundary.
|
|
76
|
+
*/
|
|
77
|
+
export interface SandboxFetchResponse {
|
|
78
|
+
Ok: boolean;
|
|
79
|
+
Status: number;
|
|
80
|
+
StatusText: string;
|
|
81
|
+
Headers: Record<string, string>;
|
|
82
|
+
BodyText: string;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface CheckedAddress {
|
|
86
|
+
address: string;
|
|
87
|
+
family: 4 | 6;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function normalizeHostname(hostname: string): string {
|
|
91
|
+
return hostname.trim().toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Checks whether a hostname targets localhost, a dotless internal host, a private/internal
|
|
96
|
+
* DNS suffix (e.g. `.internal`, `.local`, `.svc`), or a blocked private/reserved IP literal.
|
|
97
|
+
*/
|
|
98
|
+
export function IsBlockedSandboxHostname(hostname: string): boolean {
|
|
99
|
+
const normalized = normalizeHostname(hostname);
|
|
100
|
+
if (!normalized) {
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// IP literals (v4 or v6) are checked directly against private/reserved CIDR ranges.
|
|
105
|
+
if (normalized.includes(':') || /^\d+\.\d+\.\d+\.\d+$/.test(normalized)) {
|
|
106
|
+
return IsBlockedIPAddress(normalized);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (BLOCKED_EXACT_HOSTNAMES.has(normalized)) {
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (!normalized.includes('.')) {
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return PRIVATE_HOSTNAME_SUFFIXES.some((suffix) => normalized.endsWith(suffix));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function matchesAllowedNetworkHost(hostname: string, allowlist: readonly string[]): boolean {
|
|
121
|
+
const normalized = normalizeHostname(hostname);
|
|
122
|
+
for (const rawPattern of allowlist) {
|
|
123
|
+
const pattern = normalizeHostname(rawPattern);
|
|
124
|
+
if (!pattern) {
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (pattern === '*') {
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
if (pattern.startsWith('*.')) {
|
|
131
|
+
const suffix = pattern.slice(1);
|
|
132
|
+
const bareDomain = pattern.slice(2);
|
|
133
|
+
if (normalized === bareDomain || normalized.endsWith(suffix)) {
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (normalized === pattern) {
|
|
139
|
+
return true;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Validates that a sandbox `fetch()` URL uses `http(s)`, does not target internal/private
|
|
147
|
+
* hostnames or IP ranges (including DNS-resolved addresses), and satisfies any allowlist.
|
|
148
|
+
*/
|
|
149
|
+
export async function ValidateSandboxFetchUrl(
|
|
150
|
+
rawUrl: string,
|
|
151
|
+
allowedNetworkHosts?: readonly string[],
|
|
152
|
+
assertPublicUrlImpl: typeof AssertPublicUrl = AssertPublicUrl,
|
|
153
|
+
requireAllowlist = false
|
|
154
|
+
): Promise<URL> {
|
|
155
|
+
let parsed: URL;
|
|
156
|
+
try {
|
|
157
|
+
parsed = new URL(rawUrl);
|
|
158
|
+
} catch {
|
|
159
|
+
throw new Error(`Security Error: Invalid URL '${rawUrl}'`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
163
|
+
throw new Error(`Security Error: Unsupported URL scheme '${parsed.protocol}' — only http and https are allowed`);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (IsBlockedSandboxHostname(parsed.hostname)) {
|
|
167
|
+
throw new Error(`Security Error: Destination host '${parsed.hostname}' is blocked for sandboxed network access`);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const effectiveAllowlist = (allowedNetworkHosts ?? []).filter((h) => h.trim().length > 0);
|
|
171
|
+
if (requireAllowlist && effectiveAllowlist.length === 0) {
|
|
172
|
+
throw new Error('Security Error: Outbound network access requires a non-empty allowedNetworkHosts allowlist');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (effectiveAllowlist.length > 0) {
|
|
176
|
+
if (!matchesAllowedNetworkHost(parsed.hostname, effectiveAllowlist)) {
|
|
177
|
+
throw new Error(`Security Error: Destination host '${parsed.hostname}' is not in the allowed network hosts list`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
try {
|
|
182
|
+
return await assertPublicUrlImpl(parsed.href);
|
|
183
|
+
} catch (err) {
|
|
184
|
+
if (err instanceof SSRFError) {
|
|
185
|
+
throw new Error(`Security Error: ${err.message}`);
|
|
186
|
+
}
|
|
187
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
188
|
+
if (message.startsWith('Security Error:')) {
|
|
189
|
+
throw new Error(message);
|
|
190
|
+
}
|
|
191
|
+
throw new Error(`Security Error: ${message}`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function resolveAndVerifyPublicAddress(hostname: string): Promise<CheckedAddress> {
|
|
196
|
+
const bareHost = hostname.replace(/^\[|\]$/g, '');
|
|
197
|
+
const literalFamily = isIP(bareHost);
|
|
198
|
+
if (literalFamily === 4 || literalFamily === 6) {
|
|
199
|
+
if (IsBlockedIPAddress(bareHost)) {
|
|
200
|
+
throw new Error('Security Error: URL resolves to a private or reserved address and was blocked');
|
|
201
|
+
}
|
|
202
|
+
return { address: bareHost, family: literalFamily };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const records = await dns.lookup(bareHost, { all: true });
|
|
206
|
+
if (records.length === 0) {
|
|
207
|
+
throw new Error(`Security Error: Hostname '${bareHost}' did not resolve to any address`);
|
|
208
|
+
}
|
|
209
|
+
for (const record of records) {
|
|
210
|
+
if (IsBlockedIPAddress(record.address)) {
|
|
211
|
+
throw new Error('Security Error: URL resolves to a private or reserved address and was blocked');
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const chosen = records[0];
|
|
215
|
+
return {
|
|
216
|
+
address: chosen.address,
|
|
217
|
+
family: chosen.family === 6 ? 6 : 4
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function copyResponseHeaders(headers: Headers): Record<string, string> {
|
|
222
|
+
const copied: Record<string, string> = {};
|
|
223
|
+
headers.forEach((value, key) => {
|
|
224
|
+
copied[key] = value;
|
|
225
|
+
});
|
|
226
|
+
return copied;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function stripHeaders(headersInit: RequestInit['headers'], namesToRemove: readonly string[]): Headers | undefined {
|
|
230
|
+
if (!headersInit) {
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
const headers = new Headers(headersInit);
|
|
234
|
+
for (const headerName of namesToRemove) {
|
|
235
|
+
headers.delete(headerName);
|
|
236
|
+
}
|
|
237
|
+
return headers;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function readResponseTextCapped(response: Response, maxBytes: number): Promise<string> {
|
|
241
|
+
const contentLengthHeader = response.headers.get('content-length');
|
|
242
|
+
if (contentLengthHeader) {
|
|
243
|
+
const declaredBytes = Number(contentLengthHeader);
|
|
244
|
+
if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
|
|
245
|
+
void response.body?.cancel();
|
|
246
|
+
throw new Error(`Security Error: Response body exceeds maximum allowed size of ${maxBytes} bytes`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (!response.body) {
|
|
251
|
+
const text = await response.text();
|
|
252
|
+
if (Buffer.byteLength(text, 'utf8') > maxBytes) {
|
|
253
|
+
throw new Error(`Security Error: Response body exceeds maximum allowed size of ${maxBytes} bytes`);
|
|
254
|
+
}
|
|
255
|
+
return text;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const reader = response.body.getReader();
|
|
259
|
+
const chunks: Uint8Array[] = [];
|
|
260
|
+
let totalBytes = 0;
|
|
261
|
+
try {
|
|
262
|
+
while (true) {
|
|
263
|
+
const { done, value } = await reader.read();
|
|
264
|
+
if (done) {
|
|
265
|
+
break;
|
|
266
|
+
}
|
|
267
|
+
if (value) {
|
|
268
|
+
totalBytes += value.byteLength;
|
|
269
|
+
if (totalBytes > maxBytes) {
|
|
270
|
+
await reader.cancel();
|
|
271
|
+
throw new Error(`Security Error: Response body exceeds maximum allowed size of ${maxBytes} bytes`);
|
|
272
|
+
}
|
|
273
|
+
chunks.push(value);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
} finally {
|
|
277
|
+
reader.releaseLock();
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
return Buffer.concat(chunks, totalBytes).toString('utf8');
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Executes a single HTTP(S) hop pinned directly to the validated IP address via Node's native
|
|
285
|
+
* `http`/`https` `lookup` hook, eliminating the TOCTOU DNS-rebinding window while preserving
|
|
286
|
+
* TLS SNI and certificate hostname verification.
|
|
287
|
+
*/
|
|
288
|
+
async function executePinnedNodeRequest(
|
|
289
|
+
url: URL,
|
|
290
|
+
checked: CheckedAddress,
|
|
291
|
+
method: string | undefined,
|
|
292
|
+
headersInit: RequestInit['headers'],
|
|
293
|
+
body: RequestInit['body'],
|
|
294
|
+
timeoutMs: number,
|
|
295
|
+
maxBytes: number
|
|
296
|
+
): Promise<{ status: number; statusText: string; headers: Headers; bodyText: string; isRedirect: boolean }> {
|
|
297
|
+
const transport = url.protocol === 'https:' ? https : http;
|
|
298
|
+
const rawHeaders: Record<string, string> = {};
|
|
299
|
+
if (headersInit) {
|
|
300
|
+
new Headers(headersInit).forEach((value, key) => {
|
|
301
|
+
rawHeaders[key] = value;
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
if (!Object.keys(rawHeaders).some((k) => k.toLowerCase() === 'host')) {
|
|
305
|
+
rawHeaders['Host'] = url.host;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
let bodyBuffer: Buffer | undefined;
|
|
309
|
+
if (body != null) {
|
|
310
|
+
if (typeof body === 'string') {
|
|
311
|
+
bodyBuffer = Buffer.from(body, 'utf8');
|
|
312
|
+
} else if (body instanceof Uint8Array) {
|
|
313
|
+
bodyBuffer = Buffer.from(body);
|
|
314
|
+
} else if (body instanceof ArrayBuffer) {
|
|
315
|
+
bodyBuffer = Buffer.from(body);
|
|
316
|
+
} else {
|
|
317
|
+
bodyBuffer = Buffer.from(String(body), 'utf8');
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return new Promise((resolve, reject) => {
|
|
322
|
+
const reqOptions: https.RequestOptions = {
|
|
323
|
+
protocol: url.protocol,
|
|
324
|
+
hostname: url.hostname,
|
|
325
|
+
port: url.port ? Number(url.port) : url.protocol === 'https:' ? 443 : 80,
|
|
326
|
+
path: `${url.pathname}${url.search}`,
|
|
327
|
+
method: method || 'GET',
|
|
328
|
+
headers: rawHeaders,
|
|
329
|
+
timeout: timeoutMs,
|
|
330
|
+
servername: url.protocol === 'https:' ? url.hostname : undefined,
|
|
331
|
+
lookup: (_host, opts, cb) => {
|
|
332
|
+
if (typeof opts === 'object' && opts !== null && opts.all) {
|
|
333
|
+
cb(null, [{ address: checked.address, family: checked.family }]);
|
|
334
|
+
} else {
|
|
335
|
+
cb(null, checked.address, checked.family);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
const req = transport.request(reqOptions, (res) => {
|
|
341
|
+
const status = res.statusCode ?? 0;
|
|
342
|
+
const statusText = res.statusMessage ?? '';
|
|
343
|
+
const headers = new Headers();
|
|
344
|
+
for (const [k, v] of Object.entries(res.headers)) {
|
|
345
|
+
if (Array.isArray(v)) {
|
|
346
|
+
headers.set(k, v.join(', '));
|
|
347
|
+
} else if (v !== undefined) {
|
|
348
|
+
headers.set(k, v);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const location = headers.get('location');
|
|
353
|
+
if (REDIRECT_STATUS_CODES.has(status) && location) {
|
|
354
|
+
res.resume();
|
|
355
|
+
resolve({ status, statusText, headers, bodyText: '', isRedirect: true });
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const declaredLength = Number(headers.get('content-length'));
|
|
360
|
+
if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
|
|
361
|
+
res.destroy();
|
|
362
|
+
reject(new Error(`Security Error: Response body exceeds maximum allowed size of ${maxBytes} bytes`));
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const chunks: Buffer[] = [];
|
|
367
|
+
let totalBytes = 0;
|
|
368
|
+
res.on('data', (chunk: Buffer) => {
|
|
369
|
+
totalBytes += chunk.byteLength;
|
|
370
|
+
if (totalBytes > maxBytes) {
|
|
371
|
+
res.destroy();
|
|
372
|
+
reject(new Error(`Security Error: Response body exceeds maximum allowed size of ${maxBytes} bytes`));
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
chunks.push(chunk);
|
|
376
|
+
});
|
|
377
|
+
res.on('end', () => {
|
|
378
|
+
resolve({
|
|
379
|
+
status,
|
|
380
|
+
statusText,
|
|
381
|
+
headers,
|
|
382
|
+
bodyText: Buffer.concat(chunks, totalBytes).toString('utf8'),
|
|
383
|
+
isRedirect: false
|
|
384
|
+
});
|
|
385
|
+
});
|
|
386
|
+
res.on('error', reject);
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
req.on('timeout', () => {
|
|
390
|
+
req.destroy(new Error(`Request timed out after ${timeoutMs}ms`));
|
|
391
|
+
});
|
|
392
|
+
req.on('error', reject);
|
|
393
|
+
|
|
394
|
+
if (bodyBuffer) {
|
|
395
|
+
req.write(bodyBuffer);
|
|
396
|
+
}
|
|
397
|
+
req.end();
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Executes a host-mediated `fetch()` for sandboxed code with SSRF validation, DNS-pinned
|
|
403
|
+
* connection handling, internal hostname blocking, optional/required host allowlisting,
|
|
404
|
+
* capped response size, and manual per-hop redirect validation.
|
|
405
|
+
*/
|
|
406
|
+
export async function ExecuteSandboxFetch(
|
|
407
|
+
rawUrl: string,
|
|
408
|
+
init: RequestInit | undefined,
|
|
409
|
+
options: SandboxFetchOptions
|
|
410
|
+
): Promise<SandboxFetchResponse> {
|
|
411
|
+
const assertPublicUrlImpl = options.AssertPublicUrlImpl ?? AssertPublicUrl;
|
|
412
|
+
const maxBytes = options.MaxResponseBytes ?? MAX_SANDBOX_RESPONSE_BYTES;
|
|
413
|
+
|
|
414
|
+
let currentUrl = rawUrl;
|
|
415
|
+
let redirectCount = 0;
|
|
416
|
+
let originalOrigin: string | null = null;
|
|
417
|
+
let currentMethod = init?.method;
|
|
418
|
+
let currentHeaders = init?.headers;
|
|
419
|
+
let currentBody = init?.body;
|
|
420
|
+
|
|
421
|
+
while (true) {
|
|
422
|
+
const validated = await ValidateSandboxFetchUrl(
|
|
423
|
+
currentUrl,
|
|
424
|
+
options.AllowedNetworkHosts,
|
|
425
|
+
assertPublicUrlImpl,
|
|
426
|
+
options.RequireAllowlist === true
|
|
427
|
+
);
|
|
428
|
+
originalOrigin ??= validated.origin;
|
|
429
|
+
const isCrossOrigin = validated.origin !== originalOrigin;
|
|
430
|
+
if (isCrossOrigin) {
|
|
431
|
+
currentHeaders = stripHeaders(currentHeaders, SENSITIVE_REDIRECT_HEADERS);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
let status: number;
|
|
435
|
+
let statusText: string;
|
|
436
|
+
let headers: Headers;
|
|
437
|
+
let bodyText: string;
|
|
438
|
+
let isRedirect: boolean;
|
|
439
|
+
|
|
440
|
+
if (options.FetchImpl) {
|
|
441
|
+
const response = await options.FetchImpl(validated.href, {
|
|
442
|
+
method: currentMethod,
|
|
443
|
+
headers: currentHeaders,
|
|
444
|
+
body: currentBody,
|
|
445
|
+
redirect: 'manual',
|
|
446
|
+
signal: AbortSignal.timeout(options.TimeoutMs)
|
|
447
|
+
});
|
|
448
|
+
status = response.status;
|
|
449
|
+
statusText = response.statusText;
|
|
450
|
+
headers = response.headers;
|
|
451
|
+
isRedirect = REDIRECT_STATUS_CODES.has(status) && Boolean(headers.get('location'));
|
|
452
|
+
if (isRedirect) {
|
|
453
|
+
void response.body?.cancel();
|
|
454
|
+
bodyText = '';
|
|
455
|
+
} else {
|
|
456
|
+
bodyText = await readResponseTextCapped(response, maxBytes);
|
|
457
|
+
}
|
|
458
|
+
} else {
|
|
459
|
+
const checkedAddress = await resolveAndVerifyPublicAddress(validated.hostname);
|
|
460
|
+
const hopResult = await executePinnedNodeRequest(
|
|
461
|
+
validated,
|
|
462
|
+
checkedAddress,
|
|
463
|
+
currentMethod,
|
|
464
|
+
currentHeaders,
|
|
465
|
+
currentBody,
|
|
466
|
+
options.TimeoutMs,
|
|
467
|
+
maxBytes
|
|
468
|
+
);
|
|
469
|
+
status = hopResult.status;
|
|
470
|
+
statusText = hopResult.statusText;
|
|
471
|
+
headers = hopResult.headers;
|
|
472
|
+
bodyText = hopResult.bodyText;
|
|
473
|
+
isRedirect = hopResult.isRedirect;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
const location = headers.get('location');
|
|
477
|
+
if (!isRedirect || !location) {
|
|
478
|
+
return {
|
|
479
|
+
Ok: status >= 200 && status < 300,
|
|
480
|
+
Status: status,
|
|
481
|
+
StatusText: statusText,
|
|
482
|
+
Headers: copyResponseHeaders(headers),
|
|
483
|
+
BodyText: bodyText
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
if (redirectCount >= MAX_SANDBOX_REDIRECTS) {
|
|
488
|
+
throw new Error(`Security Error: Exceeded maximum of ${MAX_SANDBOX_REDIRECTS} redirects`);
|
|
489
|
+
}
|
|
490
|
+
redirectCount++;
|
|
491
|
+
const nextUrl = new URL(location, validated);
|
|
492
|
+
const nextIsCrossOrigin = nextUrl.origin !== originalOrigin;
|
|
493
|
+
|
|
494
|
+
// Per Fetch / RFC 9110: 303 always switches non-GET/HEAD to GET without body;
|
|
495
|
+
// 301/302 downgrade POST to GET; and on any cross-origin redirect (including 307/308),
|
|
496
|
+
// never resend a request body or non-GET/HEAD method to another origin.
|
|
497
|
+
const upperMethod = (currentMethod ?? 'GET').toUpperCase();
|
|
498
|
+
const shouldDowngradeToGet =
|
|
499
|
+
(status === 303 && upperMethod !== 'GET' && upperMethod !== 'HEAD') ||
|
|
500
|
+
(METHOD_DOWNGRADE_REDIRECT_CODES.has(status) && upperMethod === 'POST') ||
|
|
501
|
+
(nextIsCrossOrigin && upperMethod !== 'GET' && upperMethod !== 'HEAD');
|
|
502
|
+
|
|
503
|
+
if (shouldDowngradeToGet) {
|
|
504
|
+
currentMethod = 'GET';
|
|
505
|
+
currentBody = undefined;
|
|
506
|
+
currentHeaders = stripHeaders(currentHeaders, BODY_HEADERS);
|
|
507
|
+
} else if (nextIsCrossOrigin && currentBody !== undefined) {
|
|
508
|
+
currentBody = undefined;
|
|
509
|
+
currentHeaders = stripHeaders(currentHeaders, BODY_HEADERS);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
currentUrl = nextUrl.href;
|
|
513
|
+
}
|
|
514
|
+
}
|
package/src/types/index.ts
CHANGED
|
@@ -52,10 +52,27 @@ export interface CodeExecutionParams {
|
|
|
52
52
|
|
|
53
53
|
/**
|
|
54
54
|
* Memory limit in MB (default: 128)
|
|
55
|
-
*
|
|
55
|
+
* Enforced on each V8 isolate created inside the worker.
|
|
56
56
|
*/
|
|
57
57
|
memoryLimitMB?: number;
|
|
58
58
|
|
|
59
|
+
/**
|
|
60
|
+
* Whether outbound network access via `fetch()` is permitted inside the sandbox
|
|
61
|
+
* (default: `false` — fail-closed). When enabled, `globalThis.fetch` inside the
|
|
62
|
+
* isolate delegates through an SSRF-guarded host bridge with private/internal
|
|
63
|
+
* destination blocking, per-hop redirect validation, and execution-timeout
|
|
64
|
+
* enforcement; direct Node sockets remain blocked.
|
|
65
|
+
*/
|
|
66
|
+
networkAccess?: boolean;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Optional hostname/domain allowlist enforced when `networkAccess` is `true`.
|
|
70
|
+
* Supports exact hostnames (e.g. `'api.example.com'`) and wildcard subdomains
|
|
71
|
+
* (e.g. `'*.example.com'`). Private, loopback, link-local, metadata, and internal
|
|
72
|
+
* destinations are always blocked regardless of this list.
|
|
73
|
+
*/
|
|
74
|
+
allowedNetworkHosts?: string[];
|
|
75
|
+
|
|
59
76
|
/**
|
|
60
77
|
* Optional map of bridge handlers to expose to sandbox code as
|
|
61
78
|
* `__bridgeCall(name, args)`. When present, the sandbox can make async
|
package/src/worker.ts
CHANGED
|
@@ -44,6 +44,7 @@
|
|
|
44
44
|
import ivm from 'isolated-vm';
|
|
45
45
|
import { CodeExecutionParams, CodeExecutionResult } from './types';
|
|
46
46
|
import { GetLibrarySource, IsModuleAllowed, GetAllowedModuleNames } from './libraries';
|
|
47
|
+
import { ExecuteSandboxFetch } from './networkFetch';
|
|
47
48
|
|
|
48
49
|
/**
|
|
49
50
|
* Message types for IPC communication with parent process
|
|
@@ -204,13 +205,80 @@ async function executeInIsolate(
|
|
|
204
205
|
globalThis.SyntaxError = SyntaxError;
|
|
205
206
|
`);
|
|
206
207
|
|
|
207
|
-
// SECURITY:
|
|
208
|
-
//
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
208
|
+
// SECURITY: Network access is disabled by default (`networkAccess !== true`).
|
|
209
|
+
// Only when `params.networkAccess === true` do we expose an SSRF-guarded,
|
|
210
|
+
// host-mediated `fetch()` wrapper bounded by `timeoutMs` (blocking private/loopback/
|
|
211
|
+
// metadata/internal targets and re-validating redirects); otherwise `globalThis.fetch`
|
|
212
|
+
// throws a Security Error synchronously.
|
|
213
|
+
if (params.networkAccess === true) {
|
|
214
|
+
const hostFetchRef = new ivm.Reference(
|
|
215
|
+
async (url: string, initJson?: string): Promise<string> => {
|
|
216
|
+
try {
|
|
217
|
+
let parsedInit: RequestInit | undefined;
|
|
218
|
+
if (initJson) {
|
|
219
|
+
const rawInit = JSON.parse(initJson) as {
|
|
220
|
+
method?: string;
|
|
221
|
+
headers?: Record<string, string>;
|
|
222
|
+
body?: string;
|
|
223
|
+
};
|
|
224
|
+
parsedInit = {
|
|
225
|
+
method: rawInit.method,
|
|
226
|
+
headers: rawInit.headers,
|
|
227
|
+
body: rawInit.body
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
const response = await ExecuteSandboxFetch(url, parsedInit, {
|
|
231
|
+
TimeoutMs: timeoutMs,
|
|
232
|
+
AllowedNetworkHosts: params.allowedNetworkHosts,
|
|
233
|
+
RequireAllowlist: true
|
|
234
|
+
});
|
|
235
|
+
return JSON.stringify({
|
|
236
|
+
ok: response.Ok,
|
|
237
|
+
status: response.Status,
|
|
238
|
+
statusText: response.StatusText,
|
|
239
|
+
headers: response.Headers,
|
|
240
|
+
bodyText: response.BodyText
|
|
241
|
+
});
|
|
242
|
+
} catch (err) {
|
|
243
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
244
|
+
return JSON.stringify({ __fetchError: message });
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
);
|
|
248
|
+
await jail.set('_hostFetch', hostFetchRef);
|
|
249
|
+
await context.eval(`
|
|
250
|
+
globalThis.fetch = async (url, init) => {
|
|
251
|
+
const serializedInit = init ? JSON.stringify({
|
|
252
|
+
method: init.method,
|
|
253
|
+
headers: init.headers,
|
|
254
|
+
body: init.body
|
|
255
|
+
}) : undefined;
|
|
256
|
+
const envelope = await _hostFetch.apply(
|
|
257
|
+
undefined,
|
|
258
|
+
[String(url), serializedInit],
|
|
259
|
+
{ result: { promise: true } }
|
|
260
|
+
);
|
|
261
|
+
const res = envelope ? JSON.parse(envelope) : null;
|
|
262
|
+
if (!res || res.__fetchError) {
|
|
263
|
+
throw new Error(res?.__fetchError || 'Network request failed');
|
|
264
|
+
}
|
|
265
|
+
return {
|
|
266
|
+
ok: res.ok,
|
|
267
|
+
status: res.status,
|
|
268
|
+
statusText: res.statusText,
|
|
269
|
+
headers: res.headers,
|
|
270
|
+
text: async () => res.bodyText,
|
|
271
|
+
json: async () => JSON.parse(res.bodyText)
|
|
272
|
+
};
|
|
273
|
+
};
|
|
274
|
+
`);
|
|
275
|
+
} else {
|
|
276
|
+
await context.eval(`
|
|
277
|
+
globalThis.fetch = () => {
|
|
278
|
+
throw new Error('Security Error: Network access via fetch() is not allowed in sandboxed code');
|
|
279
|
+
};
|
|
280
|
+
`);
|
|
281
|
+
}
|
|
214
282
|
|
|
215
283
|
// ===================================================================
|
|
216
284
|
// BRIDGE SETUP
|