@benchcutlogic/edge-kit 0.0.0-stage → 0.2.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 +201 -0
- package/README.md +172 -2
- package/dist/analytics.d.ts +41 -0
- package/dist/analytics.js +212 -0
- package/dist/body.d.ts +55 -0
- package/dist/body.js +177 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/scrub.d.ts +128 -0
- package/dist/scrub.js +636 -0
- package/dist/ssrf.d.ts +165 -0
- package/dist/ssrf.js +643 -0
- package/dist/sveltekit.d.ts +60 -0
- package/dist/sveltekit.js +149 -0
- package/dist/tenant.d.ts +44 -0
- package/dist/tenant.js +43 -0
- package/package.json +87 -3
package/dist/ssrf.js
ADDED
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
import * as Data from 'effect/Data';
|
|
2
|
+
import * as Effect from 'effect/Effect';
|
|
3
|
+
import ipaddr from 'ipaddr.js';
|
|
4
|
+
import { BodyReadError, BodyTooLargeError, readCappedBytes } from './body.js';
|
|
5
|
+
export { BodyReadError, BodyTooLargeError };
|
|
6
|
+
export class SsrfBlockedError extends Data.TaggedError('SsrfBlockedError') {
|
|
7
|
+
get message() {
|
|
8
|
+
const addr = this.address ? ` (${this.address})` : '';
|
|
9
|
+
return `SSRF blocked request to ${this.url}${addr}: ${this.reason}`;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export class InvalidUrlError extends Data.TaggedError('InvalidUrlError') {
|
|
13
|
+
get message() {
|
|
14
|
+
return `Invalid URL "${this.url}": ${this.reason}`;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export class DeadlineExceededError extends Data.TaggedError('DeadlineExceededError') {
|
|
18
|
+
get message() {
|
|
19
|
+
return `Request to ${this.url} exceeded total deadline of ${this.timeoutMs}ms`;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export class NetworkError extends Data.TaggedError('NetworkError') {
|
|
23
|
+
get message() {
|
|
24
|
+
const detail = this.cause instanceof Error ? this.cause.message : String(this.cause);
|
|
25
|
+
return `Network error fetching ${this.url}: ${detail}`;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const DEFAULT_MAX_REDIRECTS = 3;
|
|
29
|
+
const DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
|
|
30
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
31
|
+
const CROSS_ORIGIN_SENSITIVE_HEADERS = ['authorization', 'cookie', 'proxy-authorization'];
|
|
32
|
+
const EXTRA_BLOCKED_IPV4_CIDRS = [
|
|
33
|
+
ipaddr.IPv4.parseCIDR('198.18.0.0/15'), // RFC 2544 benchmarking
|
|
34
|
+
ipaddr.IPv4.parseCIDR('192.0.0.0/24'), // RFC 6890 IETF protocol assignments
|
|
35
|
+
ipaddr.IPv4.parseCIDR('192.0.2.0/24'), // TEST-NET-1
|
|
36
|
+
ipaddr.IPv4.parseCIDR('198.51.100.0/24'), // TEST-NET-2
|
|
37
|
+
ipaddr.IPv4.parseCIDR('203.0.113.0/24') // TEST-NET-3
|
|
38
|
+
];
|
|
39
|
+
const EXTRA_BLOCKED_IPV6_CIDRS = [
|
|
40
|
+
ipaddr.IPv6.parseCIDR('::/96'), // Deprecated IPv4-compatible IPv6
|
|
41
|
+
ipaddr.IPv6.parseCIDR('64:ff9b:1::/48'), // RFC 8215 local-use NAT64
|
|
42
|
+
ipaddr.IPv6.parseCIDR('100::/64'), // RFC 6666 discard-only
|
|
43
|
+
ipaddr.IPv6.parseCIDR('2001:2::/48'), // RFC 5180 benchmarking
|
|
44
|
+
ipaddr.IPv6.parseCIDR('2001:db8::/32') // RFC 3849 documentation
|
|
45
|
+
];
|
|
46
|
+
function stripBrackets(host) {
|
|
47
|
+
return host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
|
|
48
|
+
}
|
|
49
|
+
function stripZoneId(ip) {
|
|
50
|
+
const idx = ip.indexOf('%');
|
|
51
|
+
if (idx === -1)
|
|
52
|
+
return { address: ip, hasZone: false };
|
|
53
|
+
return { address: ip.slice(0, idx), hasZone: true };
|
|
54
|
+
}
|
|
55
|
+
function isBlockedIpv4(addr) {
|
|
56
|
+
if (addr.range() !== 'unicast') {
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
for (const cidr of EXTRA_BLOCKED_IPV4_CIDRS) {
|
|
60
|
+
if (addr.match(cidr)) {
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
function isBlockedIpv6(addr) {
|
|
67
|
+
if (addr.isIPv4MappedAddress()) {
|
|
68
|
+
return isBlockedIpv4(addr.toIPv4Address());
|
|
69
|
+
}
|
|
70
|
+
if (addr.range() !== 'unicast') {
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
for (const cidr of EXTRA_BLOCKED_IPV6_CIDRS) {
|
|
74
|
+
if (addr.match(cidr)) {
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
function isIpLiteral(candidate) {
|
|
81
|
+
const cleaned = stripZoneId(stripBrackets(candidate.trim())).address;
|
|
82
|
+
return ipaddr.isValid(cleaned);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Returns `true` if `ip` is a private, loopback, link-local, unique-local,
|
|
86
|
+
* carrier-grade NAT, multicast, broadcast, unspecified, benchmark, documentation,
|
|
87
|
+
* reserved, or IPv4-mapped private IPv6 address.
|
|
88
|
+
*
|
|
89
|
+
* Uses `ipaddr.js` exclusively (no hand-rolled bitmasks).
|
|
90
|
+
*/
|
|
91
|
+
export function isPrivateOrReservedIp(ip) {
|
|
92
|
+
const unbracketed = stripBrackets(ip.trim());
|
|
93
|
+
if (unbracketed.length === 0)
|
|
94
|
+
return false;
|
|
95
|
+
const { address, hasZone } = stripZoneId(unbracketed);
|
|
96
|
+
if (!ipaddr.isValid(address)) {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
// Any scoped IPv6 address with a zone identifier is non-global (e.g. link-local)
|
|
100
|
+
if (hasZone) {
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
const parsed = ipaddr.parse(address);
|
|
104
|
+
if (parsed.kind() === 'ipv4') {
|
|
105
|
+
return isBlockedIpv4(parsed);
|
|
106
|
+
}
|
|
107
|
+
return isBlockedIpv6(parsed);
|
|
108
|
+
}
|
|
109
|
+
function normalizeHostname(hostname) {
|
|
110
|
+
return hostname.trim().toLowerCase().replace(/\.+$/, '');
|
|
111
|
+
}
|
|
112
|
+
function isBlockedHostname(normalizedHost) {
|
|
113
|
+
return (normalizedHost === 'localhost' ||
|
|
114
|
+
normalizedHost === 'local' ||
|
|
115
|
+
normalizedHost === 'internal' ||
|
|
116
|
+
normalizedHost.endsWith('.localhost') ||
|
|
117
|
+
normalizedHost.endsWith('.local') ||
|
|
118
|
+
normalizedHost.endsWith('.internal'));
|
|
119
|
+
}
|
|
120
|
+
function matchesAllowedHosts(normalizedHost, allowedHosts) {
|
|
121
|
+
for (const rawPattern of allowedHosts) {
|
|
122
|
+
const pattern = normalizeHostname(rawPattern);
|
|
123
|
+
if (pattern.length === 0)
|
|
124
|
+
continue;
|
|
125
|
+
if (pattern.startsWith('*.')) {
|
|
126
|
+
const suffix = pattern.slice(1); // '.example.com'
|
|
127
|
+
if (normalizedHost.endsWith(suffix) && normalizedHost.length > suffix.length) {
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
else if (normalizedHost === pattern) {
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
async function loadNodeDnsPromises() {
|
|
138
|
+
const proc = globalThis.process;
|
|
139
|
+
if (typeof proc?.getBuiltinModule === 'function') {
|
|
140
|
+
try {
|
|
141
|
+
const builtin = proc.getBuiltinModule('node:dns/promises');
|
|
142
|
+
if (builtin !== undefined && typeof builtin.lookup === 'function') {
|
|
143
|
+
return builtin;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
// Fall through to dynamic import check
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
const specifier = ['node', 'dns/promises'].join(':');
|
|
152
|
+
const mod = (await import(/* @vite-ignore */ specifier));
|
|
153
|
+
return typeof mod?.lookup === 'function' ? mod : null;
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Builds a default DNS resolver backed by `node:dns/promises` (`lookup` with
|
|
161
|
+
* `all: true, verbatim: true`). Fails closed with an error when no DNS resolver
|
|
162
|
+
* is available in the current runtime (e.g. non-Node edge isolates).
|
|
163
|
+
*/
|
|
164
|
+
export function createNodeDnsResolver(loadDns = loadNodeDnsPromises) {
|
|
165
|
+
return async (hostname) => {
|
|
166
|
+
const dnsMod = await loadDns();
|
|
167
|
+
if (dnsMod === null || typeof dnsMod.lookup !== 'function') {
|
|
168
|
+
throw new Error(`No DNS resolver available to validate hostname "${hostname}"; supply dnsResolve explicitly`);
|
|
169
|
+
}
|
|
170
|
+
const entries = await dnsMod.lookup(hostname, { all: true, verbatim: true });
|
|
171
|
+
return entries.map((entry) => entry.address);
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
const DEFAULT_DNS_RESOLVER = createNodeDnsResolver();
|
|
175
|
+
const NULL_BODY_STATUSES = new Set([204, 205, 304]);
|
|
176
|
+
async function loadNodeHttpModules() {
|
|
177
|
+
const proc = globalThis.process;
|
|
178
|
+
if (typeof proc?.getBuiltinModule === 'function') {
|
|
179
|
+
try {
|
|
180
|
+
const httpMod = proc.getBuiltinModule('node:http');
|
|
181
|
+
const httpsMod = proc.getBuiltinModule('node:https');
|
|
182
|
+
const zlibMod = proc.getBuiltinModule('node:zlib');
|
|
183
|
+
if (httpMod !== undefined &&
|
|
184
|
+
httpsMod !== undefined &&
|
|
185
|
+
typeof httpMod.request === 'function' &&
|
|
186
|
+
typeof httpsMod.request === 'function') {
|
|
187
|
+
return { http: httpMod, https: httpsMod, zlib: zlibMod };
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
// Fall through to dynamic import check
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
const httpSpec = ['node', 'http'].join(':');
|
|
196
|
+
const httpsSpec = ['node', 'https'].join(':');
|
|
197
|
+
const zlibSpec = ['node', 'zlib'].join(':');
|
|
198
|
+
const [httpMod, httpsMod, zlibMod] = (await Promise.all([
|
|
199
|
+
import(/* @vite-ignore */ httpSpec),
|
|
200
|
+
import(/* @vite-ignore */ httpsSpec),
|
|
201
|
+
import(/* @vite-ignore */ zlibSpec).catch(() => undefined)
|
|
202
|
+
]));
|
|
203
|
+
if (typeof httpMod?.request === 'function' && typeof httpsMod?.request === 'function') {
|
|
204
|
+
return { http: httpMod, https: httpsMod, zlib: zlibMod };
|
|
205
|
+
}
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
function buildDecompressionChain(res, responseHeaders, zlibMod) {
|
|
213
|
+
const rawEncoding = responseHeaders.get('content-encoding');
|
|
214
|
+
if (rawEncoding === null || zlibMod === undefined) {
|
|
215
|
+
return { output: res, streamsToDestroy: [res] };
|
|
216
|
+
}
|
|
217
|
+
const encodings = rawEncoding
|
|
218
|
+
.split(',')
|
|
219
|
+
.map((part) => part.trim().toLowerCase())
|
|
220
|
+
.filter((part) => part.length > 0 && part !== 'identity');
|
|
221
|
+
if (encodings.length === 0) {
|
|
222
|
+
return { output: res, streamsToDestroy: [res] };
|
|
223
|
+
}
|
|
224
|
+
const decoders = [];
|
|
225
|
+
for (let i = encodings.length - 1; i >= 0; i -= 1) {
|
|
226
|
+
const enc = encodings[i];
|
|
227
|
+
if (enc === 'gzip' || enc === 'x-gzip') {
|
|
228
|
+
decoders.push(zlibMod.createGunzip());
|
|
229
|
+
}
|
|
230
|
+
else if (enc === 'deflate') {
|
|
231
|
+
decoders.push(zlibMod.createInflate());
|
|
232
|
+
}
|
|
233
|
+
else if (enc === 'br') {
|
|
234
|
+
decoders.push(zlibMod.createBrotliDecompress());
|
|
235
|
+
}
|
|
236
|
+
else if (enc === 'zstd' && typeof zlibMod.createZstdDecompress === 'function') {
|
|
237
|
+
decoders.push(zlibMod.createZstdDecompress());
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
// Unknown encoding: leave body untouched rather than corrupting data
|
|
241
|
+
for (const d of decoders) {
|
|
242
|
+
d.destroy();
|
|
243
|
+
}
|
|
244
|
+
return { output: res, streamsToDestroy: [res] };
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
let current = res;
|
|
248
|
+
for (const decoder of decoders) {
|
|
249
|
+
current = current.pipe(decoder);
|
|
250
|
+
}
|
|
251
|
+
responseHeaders.delete('content-encoding');
|
|
252
|
+
responseHeaders.delete('content-length');
|
|
253
|
+
return { output: current, streamsToDestroy: [res, ...decoders] };
|
|
254
|
+
}
|
|
255
|
+
function createPinnedLookup(validatedAddresses) {
|
|
256
|
+
const entries = validatedAddresses.map((rawAddress) => {
|
|
257
|
+
const cleaned = stripZoneId(stripBrackets(rawAddress.trim())).address;
|
|
258
|
+
const family = ipaddr.parse(cleaned).kind() === 'ipv6' ? 6 : 4;
|
|
259
|
+
return { address: cleaned, family };
|
|
260
|
+
});
|
|
261
|
+
return (_hostname, lookupOpts, callback) => {
|
|
262
|
+
if (entries.length === 0) {
|
|
263
|
+
callback(new Error('No validated IP addresses available for pinned lookup'), '');
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
const opts = typeof lookupOpts === 'number'
|
|
267
|
+
? { family: lookupOpts, all: false }
|
|
268
|
+
: (lookupOpts ?? { all: false });
|
|
269
|
+
if (opts.all === true) {
|
|
270
|
+
const filtered = opts.family === 4 || opts.family === 6
|
|
271
|
+
? entries.filter((e) => e.family === opts.family)
|
|
272
|
+
: entries;
|
|
273
|
+
callback(null, filtered.length > 0 ? filtered : entries);
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
const preferred = opts.family === 4 || opts.family === 6
|
|
277
|
+
? (entries.find((e) => e.family === opts.family) ?? entries[0])
|
|
278
|
+
: entries[0];
|
|
279
|
+
callback(null, preferred.address, preferred.family);
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Builds a Node `http`/`https` transport that pins TCP/TLS connections directly to
|
|
284
|
+
* `init.resolvedAddresses` while preserving the original `Host` header and TLS SNI
|
|
285
|
+
* (`servername`). Fails closed with `SsrfBlockedError` when no pinned transport is
|
|
286
|
+
* available in the current runtime for hostname destinations.
|
|
287
|
+
*/
|
|
288
|
+
export function createPinnedNodeFetch(loadModules = loadNodeHttpModules) {
|
|
289
|
+
return async (input, init) => {
|
|
290
|
+
const url = typeof input === 'string' ? new URL(input) : new URL(input.toString());
|
|
291
|
+
const validatedAddresses = init?.resolvedAddresses;
|
|
292
|
+
const hostIsIp = isIpLiteral(stripBrackets(normalizeHostname(url.hostname)));
|
|
293
|
+
const modules = await loadModules();
|
|
294
|
+
if (modules === null) {
|
|
295
|
+
if (hostIsIp) {
|
|
296
|
+
return globalThis.fetch(url.toString(), init);
|
|
297
|
+
}
|
|
298
|
+
throw new SsrfBlockedError({
|
|
299
|
+
url: url.toString(),
|
|
300
|
+
reason: 'Default fetch cannot pin validated DNS addresses in this runtime; supply a pinned fetch transport'
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
if (!hostIsIp && (validatedAddresses === undefined || validatedAddresses.length === 0)) {
|
|
304
|
+
throw new SsrfBlockedError({
|
|
305
|
+
url: url.toString(),
|
|
306
|
+
reason: 'Missing validated IP addresses for pinned hostname request'
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
const headers = new Headers(init?.headers);
|
|
310
|
+
let bodyBytes;
|
|
311
|
+
if (init?.body !== undefined && init.body !== null) {
|
|
312
|
+
const serializedResponse = new Response(init.body);
|
|
313
|
+
if (!headers.has('content-type')) {
|
|
314
|
+
const inferredContentType = serializedResponse.headers.get('content-type');
|
|
315
|
+
if (inferredContentType !== null) {
|
|
316
|
+
headers.set('content-type', inferredContentType);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const ab = await serializedResponse.arrayBuffer();
|
|
320
|
+
bodyBytes = new Uint8Array(ab);
|
|
321
|
+
}
|
|
322
|
+
const headerRecord = {};
|
|
323
|
+
headers.forEach((value, key) => {
|
|
324
|
+
headerRecord[key] = value;
|
|
325
|
+
});
|
|
326
|
+
const method = (init?.method ?? 'GET').toUpperCase();
|
|
327
|
+
const transport = url.protocol === 'https:' ? modules.https : modules.http;
|
|
328
|
+
const pinnedAddresses = validatedAddresses !== undefined && validatedAddresses.length > 0
|
|
329
|
+
? validatedAddresses
|
|
330
|
+
: [stripBrackets(normalizeHostname(url.hostname))];
|
|
331
|
+
const reqOptions = {
|
|
332
|
+
method,
|
|
333
|
+
headers: headerRecord,
|
|
334
|
+
agent: false,
|
|
335
|
+
signal: init?.signal ?? undefined,
|
|
336
|
+
lookup: createPinnedLookup(pinnedAddresses),
|
|
337
|
+
servername: url.protocol === 'https:' && !hostIsIp ? url.hostname : undefined
|
|
338
|
+
};
|
|
339
|
+
return new Promise((resolve, reject) => {
|
|
340
|
+
const req = transport.request(url, reqOptions, (res) => {
|
|
341
|
+
try {
|
|
342
|
+
const status = res.statusCode ?? 200;
|
|
343
|
+
if (!Number.isInteger(status) || status < 200 || status > 599) {
|
|
344
|
+
res.destroy();
|
|
345
|
+
reject(new RangeError(`Invalid upstream HTTP status code: ${String(status)}`));
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
const statusText = res.statusMessage ?? '';
|
|
349
|
+
const responseHeaders = new Headers();
|
|
350
|
+
const rawHeaders = res.rawHeaders ?? [];
|
|
351
|
+
for (let i = 0; i + 1 < rawHeaders.length; i += 2) {
|
|
352
|
+
const name = rawHeaders[i];
|
|
353
|
+
const val = rawHeaders[i + 1];
|
|
354
|
+
if (name !== undefined && val !== undefined) {
|
|
355
|
+
responseHeaders.append(name, val);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
if (method === 'HEAD' || NULL_BODY_STATUSES.has(status)) {
|
|
359
|
+
res.resume();
|
|
360
|
+
resolve(new Response(null, { status, statusText, headers: responseHeaders }));
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
const { output: bodyStream, streamsToDestroy } = buildDecompressionChain(res, responseHeaders, modules.zlib);
|
|
364
|
+
let finished = false;
|
|
365
|
+
const destroyAll = () => {
|
|
366
|
+
for (const s of streamsToDestroy) {
|
|
367
|
+
s.destroy();
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
const stream = new ReadableStream({
|
|
371
|
+
start(controller) {
|
|
372
|
+
const failStream = (err) => {
|
|
373
|
+
if (!finished) {
|
|
374
|
+
finished = true;
|
|
375
|
+
destroyAll();
|
|
376
|
+
controller.error(err);
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
for (const s of streamsToDestroy) {
|
|
380
|
+
s.on('error', failStream);
|
|
381
|
+
}
|
|
382
|
+
bodyStream.on('data', (chunk) => {
|
|
383
|
+
if (!finished) {
|
|
384
|
+
controller.enqueue(new Uint8Array(chunk));
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
bodyStream.on('end', () => {
|
|
388
|
+
if (!finished) {
|
|
389
|
+
finished = true;
|
|
390
|
+
controller.close();
|
|
391
|
+
}
|
|
392
|
+
});
|
|
393
|
+
bodyStream.on('close', () => {
|
|
394
|
+
if (!finished) {
|
|
395
|
+
finished = true;
|
|
396
|
+
destroyAll();
|
|
397
|
+
controller.error(new Error('Response stream closed prematurely'));
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
},
|
|
401
|
+
cancel() {
|
|
402
|
+
finished = true;
|
|
403
|
+
destroyAll();
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
resolve(new Response(stream, { status, statusText, headers: responseHeaders }));
|
|
407
|
+
}
|
|
408
|
+
catch (err) {
|
|
409
|
+
res.destroy();
|
|
410
|
+
reject(err);
|
|
411
|
+
}
|
|
412
|
+
});
|
|
413
|
+
req.on('error', (err) => {
|
|
414
|
+
reject(err);
|
|
415
|
+
});
|
|
416
|
+
req.end(bodyBytes);
|
|
417
|
+
});
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
const DEFAULT_PINNED_FETCH = createPinnedNodeFetch();
|
|
421
|
+
function resolveDns(resolver, hostname, urlString) {
|
|
422
|
+
return Effect.gen(function* () {
|
|
423
|
+
const result = yield* Effect.try({
|
|
424
|
+
try: () => resolver(hostname),
|
|
425
|
+
catch: (cause) => new SsrfBlockedError({
|
|
426
|
+
url: urlString,
|
|
427
|
+
reason: `DNS resolution failed: ${cause instanceof Error ? cause.message : String(cause)}`
|
|
428
|
+
})
|
|
429
|
+
});
|
|
430
|
+
if (Effect.isEffect(result)) {
|
|
431
|
+
return yield* result.pipe(Effect.mapError((cause) => new SsrfBlockedError({
|
|
432
|
+
url: urlString,
|
|
433
|
+
reason: `DNS resolution failed: ${cause instanceof Error ? cause.message : String(cause)}`
|
|
434
|
+
})));
|
|
435
|
+
}
|
|
436
|
+
return yield* Effect.tryPromise({
|
|
437
|
+
try: () => result,
|
|
438
|
+
catch: (cause) => new SsrfBlockedError({
|
|
439
|
+
url: urlString,
|
|
440
|
+
reason: `DNS resolution failed: ${cause instanceof Error ? cause.message : String(cause)}`
|
|
441
|
+
})
|
|
442
|
+
});
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
function validatePublicHttpTarget(rawUrl, options) {
|
|
446
|
+
return Effect.gen(function* () {
|
|
447
|
+
const urlString = typeof rawUrl === 'string' ? rawUrl : rawUrl.toString();
|
|
448
|
+
const url = yield* Effect.try({
|
|
449
|
+
try: () => (typeof rawUrl === 'string' ? new URL(rawUrl) : new URL(rawUrl.toString())),
|
|
450
|
+
catch: (cause) => new InvalidUrlError({
|
|
451
|
+
url: urlString,
|
|
452
|
+
reason: cause instanceof Error ? cause.message : String(cause)
|
|
453
|
+
})
|
|
454
|
+
});
|
|
455
|
+
const allowHttp = options?.allowHttp === true;
|
|
456
|
+
if (url.protocol !== 'https:' && !(allowHttp && url.protocol === 'http:')) {
|
|
457
|
+
return yield* new SsrfBlockedError({
|
|
458
|
+
url: url.toString(),
|
|
459
|
+
reason: `Disallowed URL scheme "${url.protocol}"`
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
if (url.username !== '' || url.password !== '') {
|
|
463
|
+
return yield* new SsrfBlockedError({
|
|
464
|
+
url: url.toString(),
|
|
465
|
+
reason: 'Embedded credentials in URL are not allowed'
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
const normalizedHost = normalizeHostname(url.hostname);
|
|
469
|
+
if (normalizedHost.length === 0) {
|
|
470
|
+
return yield* new InvalidUrlError({
|
|
471
|
+
url: url.toString(),
|
|
472
|
+
reason: 'Empty hostname'
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
if (isBlockedHostname(normalizedHost)) {
|
|
476
|
+
return yield* new SsrfBlockedError({
|
|
477
|
+
url: url.toString(),
|
|
478
|
+
reason: `Blocked internal hostname "${normalizedHost}"`
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
if (options?.allowedHosts !== undefined &&
|
|
482
|
+
!matchesAllowedHosts(normalizedHost, options.allowedHosts)) {
|
|
483
|
+
return yield* new SsrfBlockedError({
|
|
484
|
+
url: url.toString(),
|
|
485
|
+
reason: `Hostname "${normalizedHost}" is not in allowedHosts`
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
const ipCandidate = stripBrackets(normalizedHost);
|
|
489
|
+
let validatedAddresses;
|
|
490
|
+
if (isIpLiteral(ipCandidate)) {
|
|
491
|
+
if (isPrivateOrReservedIp(ipCandidate)) {
|
|
492
|
+
return yield* new SsrfBlockedError({
|
|
493
|
+
url: url.toString(),
|
|
494
|
+
reason: 'IP address is private or reserved',
|
|
495
|
+
address: ipCandidate
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
validatedAddresses = [ipCandidate];
|
|
499
|
+
}
|
|
500
|
+
else {
|
|
501
|
+
const resolver = options?.dnsResolve ?? DEFAULT_DNS_RESOLVER;
|
|
502
|
+
const addresses = yield* resolveDns(resolver, normalizedHost, url.toString());
|
|
503
|
+
if (addresses.length === 0) {
|
|
504
|
+
return yield* new SsrfBlockedError({
|
|
505
|
+
url: url.toString(),
|
|
506
|
+
reason: `DNS resolution returned no addresses for "${normalizedHost}"`
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
for (const address of addresses) {
|
|
510
|
+
if (!isIpLiteral(address) || isPrivateOrReservedIp(address)) {
|
|
511
|
+
return yield* new SsrfBlockedError({
|
|
512
|
+
url: url.toString(),
|
|
513
|
+
reason: 'Resolved IP address is private or reserved',
|
|
514
|
+
address
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
validatedAddresses = addresses;
|
|
519
|
+
}
|
|
520
|
+
// Canonicalize trailing dots on the returned URL object
|
|
521
|
+
if (url.hostname !== normalizedHost) {
|
|
522
|
+
url.hostname = normalizedHost;
|
|
523
|
+
}
|
|
524
|
+
return { url, addresses: validatedAddresses };
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Validates that a URL is a public HTTP(S) target safe against SSRF.
|
|
529
|
+
*
|
|
530
|
+
* - Default HTTPS-only unless `allowHttp: true`.
|
|
531
|
+
* - Rejects embedded userinfo credentials.
|
|
532
|
+
* - Normalizes trailing dots on hostnames (`example.com.` -> `example.com`).
|
|
533
|
+
* - Blocks `localhost`, `*.localhost`, `*.local`, `*.internal`.
|
|
534
|
+
* - Enforces optional `allowedHosts` allowlist.
|
|
535
|
+
* - Blocks private/reserved IPv4, IPv6, and IPv4-mapped IPv6 literals and resolved IPs.
|
|
536
|
+
* - Resolves non-IP hostnames via `options.dnsResolve` or the default Node DNS resolver,
|
|
537
|
+
* failing closed with `SsrfBlockedError` if no resolver is available or resolution fails.
|
|
538
|
+
*/
|
|
539
|
+
export function assertPublicHttpUrl(rawUrl, options) {
|
|
540
|
+
return Effect.map(validatePublicHttpTarget(rawUrl, options), (target) => target.url);
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Fetches an external HTTP(S) URL with SSRF protection, DNS-pinned connections,
|
|
544
|
+
* manual redirect validation, cross-origin credential header stripping, a mandatory
|
|
545
|
+
* outer deadline across all hops + body read, and a streaming response body byte cap.
|
|
546
|
+
*/
|
|
547
|
+
export function ssrfFetch(inputUrl, options) {
|
|
548
|
+
const initialUrlString = typeof inputUrl === 'string' ? inputUrl : inputUrl.toString();
|
|
549
|
+
if (!Number.isFinite(options.totalTimeoutMs) || options.totalTimeoutMs <= 0) {
|
|
550
|
+
return Effect.fail(new DeadlineExceededError({
|
|
551
|
+
url: initialUrlString,
|
|
552
|
+
timeoutMs: options.totalTimeoutMs
|
|
553
|
+
}));
|
|
554
|
+
}
|
|
555
|
+
const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
|
|
556
|
+
const maxResponseBytes = options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
|
|
557
|
+
const fetchImpl = options.fetch ?? DEFAULT_PINNED_FETCH;
|
|
558
|
+
const urlOptions = {
|
|
559
|
+
allowHttp: options.allowHttp,
|
|
560
|
+
allowedHosts: options.allowedHosts,
|
|
561
|
+
dnsResolve: options.dnsResolve
|
|
562
|
+
};
|
|
563
|
+
const runFetch = Effect.gen(function* () {
|
|
564
|
+
let currentTarget = yield* validatePublicHttpTarget(inputUrl, urlOptions);
|
|
565
|
+
const currentHeaders = new Headers(options.headers);
|
|
566
|
+
let currentMethod = (options.method ?? 'GET').toUpperCase();
|
|
567
|
+
let currentBody = options.body;
|
|
568
|
+
let redirectCount = 0;
|
|
569
|
+
while (true) {
|
|
570
|
+
const targetUrl = currentTarget.url.toString();
|
|
571
|
+
const response = yield* Effect.tryPromise({
|
|
572
|
+
try: (signal) => fetchImpl(targetUrl, {
|
|
573
|
+
method: currentMethod,
|
|
574
|
+
headers: new Headers(currentHeaders),
|
|
575
|
+
body: currentBody,
|
|
576
|
+
redirect: 'manual',
|
|
577
|
+
signal,
|
|
578
|
+
resolvedAddresses: currentTarget.addresses
|
|
579
|
+
}),
|
|
580
|
+
catch: (cause) => cause instanceof SsrfBlockedError ? cause : new NetworkError({ url: targetUrl, cause })
|
|
581
|
+
});
|
|
582
|
+
const location = response.headers.get('location');
|
|
583
|
+
if (REDIRECT_STATUSES.has(response.status) && location !== null) {
|
|
584
|
+
yield* Effect.ignore(Effect.tryPromise({
|
|
585
|
+
try: () => response.body?.cancel() ?? Promise.resolve(),
|
|
586
|
+
catch: () => undefined
|
|
587
|
+
}));
|
|
588
|
+
if (redirectCount >= maxRedirects) {
|
|
589
|
+
return yield* new SsrfBlockedError({
|
|
590
|
+
url: targetUrl,
|
|
591
|
+
reason: `Exceeded maximum redirects (${maxRedirects})`
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
const resolvedNext = yield* Effect.try({
|
|
595
|
+
try: () => new URL(location, currentTarget.url),
|
|
596
|
+
catch: (cause) => new InvalidUrlError({
|
|
597
|
+
url: location,
|
|
598
|
+
reason: cause instanceof Error ? cause.message : String(cause)
|
|
599
|
+
})
|
|
600
|
+
});
|
|
601
|
+
const validatedNext = yield* validatePublicHttpTarget(resolvedNext, urlOptions);
|
|
602
|
+
if (validatedNext.url.origin !== currentTarget.url.origin) {
|
|
603
|
+
for (const sensitiveHeader of CROSS_ORIGIN_SENSITIVE_HEADERS) {
|
|
604
|
+
currentHeaders.delete(sensitiveHeader);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
if (response.status === 303 ||
|
|
608
|
+
((response.status === 301 || response.status === 302) && currentMethod === 'POST')) {
|
|
609
|
+
currentMethod = 'GET';
|
|
610
|
+
currentBody = undefined;
|
|
611
|
+
currentHeaders.delete('content-length');
|
|
612
|
+
currentHeaders.delete('content-type');
|
|
613
|
+
}
|
|
614
|
+
currentTarget = validatedNext;
|
|
615
|
+
redirectCount += 1;
|
|
616
|
+
continue;
|
|
617
|
+
}
|
|
618
|
+
const body = yield* readCappedBytes(response, maxResponseBytes);
|
|
619
|
+
const cappedResponse = {
|
|
620
|
+
url: targetUrl,
|
|
621
|
+
status: response.status,
|
|
622
|
+
statusText: response.statusText,
|
|
623
|
+
headers: response.headers,
|
|
624
|
+
body,
|
|
625
|
+
redirectCount,
|
|
626
|
+
text() {
|
|
627
|
+
return new TextDecoder('utf-8').decode(body);
|
|
628
|
+
},
|
|
629
|
+
json() {
|
|
630
|
+
return JSON.parse(new TextDecoder('utf-8').decode(body));
|
|
631
|
+
}
|
|
632
|
+
};
|
|
633
|
+
return cappedResponse;
|
|
634
|
+
}
|
|
635
|
+
});
|
|
636
|
+
return Effect.timeoutOrElse(runFetch, {
|
|
637
|
+
duration: options.totalTimeoutMs,
|
|
638
|
+
orElse: () => Effect.fail(new DeadlineExceededError({
|
|
639
|
+
url: initialUrlString,
|
|
640
|
+
timeoutMs: options.totalTimeoutMs
|
|
641
|
+
}))
|
|
642
|
+
});
|
|
643
|
+
}
|