@cobola/dsh-geo 0.0.0-stage → 0.3.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/.github/workflows/publish.yml +65 -0
- package/CHANGELOG.md +27 -0
- package/CONTRIBUTING.md +86 -0
- package/LICENSE +176 -0
- package/NOTICE +14 -0
- package/README.md +228 -2
- package/SECURITY.md +46 -0
- package/bin/dsh-geo.js +381 -0
- package/client.js +707 -0
- package/cordis.patch.yml +4 -0
- package/docs/.nojekyll +0 -0
- package/docs/CI.md +118 -0
- package/docs/GOOGLE.md +57 -0
- package/docs/NPM-TRUSTED-PUBLISHING.md +69 -0
- package/docs/PROFILES.md +51 -0
- package/docs/RULES.md +108 -0
- package/docs/icons/geo.svg +8 -0
- package/docs/index.json +41 -0
- package/icon.svg +8 -0
- package/index.js +381 -0
- package/lib/audit.js +62 -0
- package/lib/fetch.js +650 -0
- package/lib/html.js +651 -0
- package/lib/platforms/bing.js +95 -0
- package/lib/platforms/index.js +70 -0
- package/lib/profiles.js +62 -0
- package/lib/report.js +404 -0
- package/lib/robots.js +209 -0
- package/lib/rules.js +939 -0
- package/lib/scan.js +604 -0
- package/lib/score.js +145 -0
- package/lib/store.js +283 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +77 -4
package/lib/fetch.js
ADDED
|
@@ -0,0 +1,650 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guarded HTTP transport for GEO scans.
|
|
3
|
+
*
|
|
4
|
+
* DSH's own `ctx.web.fetch` deliberately no longer restricts destinations, so
|
|
5
|
+
* the plugin cannot delegate SSRF protection to it. This transport owns the
|
|
6
|
+
* policy instead:
|
|
7
|
+
*
|
|
8
|
+
* - HTTP(S) only, no embedded credentials, restricted ports unless the caller
|
|
9
|
+
* explicitly opts into private destinations (tests / local audits).
|
|
10
|
+
* - Hostnames are resolved once, every answer is checked against loopback,
|
|
11
|
+
* private, link-local, CGNAT, multicast, documentation and cloud-metadata
|
|
12
|
+
* ranges, and the connection is pinned to the validated address so DNS
|
|
13
|
+
* rebinding cannot slip a private target in after the check.
|
|
14
|
+
* - Every redirect hop is revalidated.
|
|
15
|
+
* - Response bodies are capped (both wire and decoded size), requests time
|
|
16
|
+
* out, and per-host requests are rate limited.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import dns from 'node:dns/promises';
|
|
20
|
+
import http from 'node:http';
|
|
21
|
+
import https from 'node:https';
|
|
22
|
+
import zlib from 'node:zlib';
|
|
23
|
+
|
|
24
|
+
export const DEFAULT_USER_AGENT = 'DSHGeoBot/0.1 (DeepSeek Harness GEO audit tool)';
|
|
25
|
+
export const DEFAULT_PORTS = new Set([80, 443, 8080, 8443]);
|
|
26
|
+
|
|
27
|
+
const IPV4_BLOCKED = [
|
|
28
|
+
['0.0.0.0', 8],
|
|
29
|
+
['10.0.0.0', 8],
|
|
30
|
+
['100.64.0.0', 10], // carrier-grade NAT; includes Alibaba metadata 100.100.100.200
|
|
31
|
+
['127.0.0.0', 8],
|
|
32
|
+
['169.254.0.0', 16], // link-local; includes AWS/GCP/Azure metadata
|
|
33
|
+
['172.16.0.0', 12],
|
|
34
|
+
['192.0.0.0', 24],
|
|
35
|
+
['192.0.2.0', 24],
|
|
36
|
+
['192.168.0.0', 16],
|
|
37
|
+
['198.18.0.0', 15],
|
|
38
|
+
['198.51.100.0', 24],
|
|
39
|
+
['203.0.113.0', 24],
|
|
40
|
+
['192.88.99.0', 24],
|
|
41
|
+
['224.0.0.0', 4],
|
|
42
|
+
['240.0.0.0', 4],
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
const BLOCKED_HOSTNAMES = new Set([
|
|
46
|
+
'localhost',
|
|
47
|
+
'localhost.localdomain',
|
|
48
|
+
'metadata',
|
|
49
|
+
'metadata.google.internal',
|
|
50
|
+
'instance-data',
|
|
51
|
+
'metadata.azure.internal',
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
// Cloud metadata endpoints stay blocked even when a caller opts into private
|
|
55
|
+
// targets: that opt-in is for local/staging audits, not for credential theft.
|
|
56
|
+
const METADATA_HOSTNAMES = new Set([
|
|
57
|
+
'metadata',
|
|
58
|
+
'metadata.google.internal',
|
|
59
|
+
'instance-data',
|
|
60
|
+
'metadata.azure.internal',
|
|
61
|
+
]);
|
|
62
|
+
const METADATA_ADDRESSES = new Set([
|
|
63
|
+
'169.254.169.254',
|
|
64
|
+
'100.100.100.200',
|
|
65
|
+
'fd00:ec2::254',
|
|
66
|
+
]);
|
|
67
|
+
|
|
68
|
+
// IPv6 destinations that must never be reached: unspecified/loopback,
|
|
69
|
+
// discard, documentation, Teredo, NAT64, 6to4, unique-local, link-local,
|
|
70
|
+
// site-local, and multicast.
|
|
71
|
+
const IPV6_BLOCKED_PREFIXES = [
|
|
72
|
+
['::', 128],
|
|
73
|
+
['::1', 128],
|
|
74
|
+
['100::', 64],
|
|
75
|
+
['2001:db8::', 32],
|
|
76
|
+
['2001::', 32],
|
|
77
|
+
['64:ff9b::', 96],
|
|
78
|
+
['2002::', 16],
|
|
79
|
+
['fc00::', 7],
|
|
80
|
+
['fe80::', 10],
|
|
81
|
+
['fec0::', 10],
|
|
82
|
+
['ff00::', 8],
|
|
83
|
+
];
|
|
84
|
+
|
|
85
|
+
export class FetchError extends Error {
|
|
86
|
+
/**
|
|
87
|
+
* @param {string} code Stable, branchable code.
|
|
88
|
+
* @param {string} message Human-readable detail.
|
|
89
|
+
* @param {{url?: string, cause?: Error}} [context]
|
|
90
|
+
*/
|
|
91
|
+
constructor(code, message, context = {}) {
|
|
92
|
+
super(message);
|
|
93
|
+
this.name = 'FetchError';
|
|
94
|
+
this.code = code;
|
|
95
|
+
this.url = context.url;
|
|
96
|
+
this.cause = context.cause;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function parseIpv6(value) {
|
|
101
|
+
let address = String(value).toLowerCase();
|
|
102
|
+
const zone = address.indexOf('%');
|
|
103
|
+
if (zone !== -1) address = address.slice(0, zone);
|
|
104
|
+
let tail = [];
|
|
105
|
+
const v4 = /(\d+\.\d+\.\d+\.\d+)$/.exec(address);
|
|
106
|
+
if (v4) {
|
|
107
|
+
const int = ipv4ToInt(v4[1]);
|
|
108
|
+
if (int === null) return null;
|
|
109
|
+
tail = [(int >>> 16) & 0xffff, int & 0xffff];
|
|
110
|
+
address = address.slice(0, -v4[1].length).replace(/:$/, '');
|
|
111
|
+
}
|
|
112
|
+
const compressed = address.includes('::');
|
|
113
|
+
const [head = '', rest = ''] = address.split('::');
|
|
114
|
+
const headParts = head ? head.split(':').filter(Boolean) : [];
|
|
115
|
+
const restParts = rest ? rest.split(':').filter(Boolean) : [];
|
|
116
|
+
let parts;
|
|
117
|
+
if (compressed) {
|
|
118
|
+
const fill = 8 - headParts.length - restParts.length - tail.length;
|
|
119
|
+
if (fill < 0) return null;
|
|
120
|
+
parts = [...headParts, ...Array(fill).fill('0'), ...restParts, ...tail.map((part) => part.toString(16))];
|
|
121
|
+
} else {
|
|
122
|
+
parts = [...headParts, ...tail.map((part) => part.toString(16))];
|
|
123
|
+
}
|
|
124
|
+
if (parts.length !== 8) return null;
|
|
125
|
+
const numbers = parts.map((part) => Number.parseInt(part, 16));
|
|
126
|
+
if (numbers.some((number) => !Number.isInteger(number) || number < 0 || number > 0xffff)) return null;
|
|
127
|
+
return numbers;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function matchesIpv6Prefix(address, prefix, bits) {
|
|
131
|
+
const candidate = parseIpv6(address);
|
|
132
|
+
const base = parseIpv6(prefix);
|
|
133
|
+
if (!candidate || !base) return false;
|
|
134
|
+
let remaining = bits;
|
|
135
|
+
for (let index = 0; index < 8 && remaining > 0; index += 1) {
|
|
136
|
+
const width = Math.min(16, remaining);
|
|
137
|
+
const mask = width === 16 ? 0xffff : (0xffff << (16 - width)) & 0xffff;
|
|
138
|
+
if ((candidate[index] & mask) !== (base[index] & mask)) return false;
|
|
139
|
+
remaining -= width;
|
|
140
|
+
}
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function ipv4ToInt(address) {
|
|
145
|
+
const parts = address.split('.').map(Number);
|
|
146
|
+
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return null;
|
|
147
|
+
return ((parts[0] << 24) >>> 0) + (parts[1] << 16) + (parts[2] << 8) + parts[3];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function isBlockedIpv4(address) {
|
|
151
|
+
const value = ipv4ToInt(address);
|
|
152
|
+
if (value === null) return true;
|
|
153
|
+
for (const [base, bits] of IPV4_BLOCKED) {
|
|
154
|
+
const baseValue = ipv4ToInt(base);
|
|
155
|
+
const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
|
|
156
|
+
if ((value & mask) >>> 0 === (baseValue & mask) >>> 0) return true;
|
|
157
|
+
}
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function normalizeIpv6(address) {
|
|
162
|
+
const lower = address.toLowerCase().replace(/%.+$/, '');
|
|
163
|
+
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
|
|
164
|
+
if (mapped) return { kind: 'v4', address: mapped[1] };
|
|
165
|
+
const hexMapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(lower);
|
|
166
|
+
if (hexMapped) {
|
|
167
|
+
const high = Number.parseInt(hexMapped[1], 16);
|
|
168
|
+
const low = Number.parseInt(hexMapped[2], 16);
|
|
169
|
+
const octets = [high >> 8, high & 0xff, low >> 8, low & 0xff];
|
|
170
|
+
return { kind: 'v4', address: octets.join('.') };
|
|
171
|
+
}
|
|
172
|
+
return { kind: 'v6', address: lower };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function isBlockedIpv6(address) {
|
|
176
|
+
const normalized = normalizeIpv6(address);
|
|
177
|
+
if (normalized.kind === 'v4') return isBlockedIpv4(normalized.address);
|
|
178
|
+
return IPV6_BLOCKED_PREFIXES.some(([prefix, bits]) => matchesIpv6Prefix(normalized.address, prefix, bits));
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* True for addresses a public audit must never touch.
|
|
183
|
+
* @param {string} address
|
|
184
|
+
*/
|
|
185
|
+
export function isBlockedAddress(address) {
|
|
186
|
+
if (typeof address !== 'string' || !address) return true;
|
|
187
|
+
if (address.includes(':')) return isBlockedIpv6(address);
|
|
188
|
+
return isBlockedIpv4(address);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function isIpLiteral(hostname) {
|
|
192
|
+
return /^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname) || hostname.includes(':');
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function assertHttpUrl(rawUrl) {
|
|
196
|
+
let url;
|
|
197
|
+
try {
|
|
198
|
+
url = new URL(rawUrl);
|
|
199
|
+
} catch {
|
|
200
|
+
throw new FetchError('FETCH_INVALID_URL', `Not a valid absolute URL: ${rawUrl}`, { url: rawUrl });
|
|
201
|
+
}
|
|
202
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
203
|
+
throw new FetchError('FETCH_INVALID_URL', `Only http(s) URLs are supported: ${url.protocol}//`, { url: url.href });
|
|
204
|
+
}
|
|
205
|
+
if (url.username || url.password) {
|
|
206
|
+
throw new FetchError('FETCH_INVALID_URL', 'URLs with embedded credentials are refused', { url: url.href });
|
|
207
|
+
}
|
|
208
|
+
if (url.hostname.includes('%')) {
|
|
209
|
+
throw new FetchError('FETCH_INVALID_URL', 'Percent-encoded hostnames are refused', { url: url.href });
|
|
210
|
+
}
|
|
211
|
+
return url;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Resolve and validate the destination of one URL.
|
|
216
|
+
* @param {string} rawUrl
|
|
217
|
+
* @param {{allowPrivate?: boolean, dnsLookup?: Function}} [options]
|
|
218
|
+
* @returns {Promise<{url: URL, address: string, family: number}>}
|
|
219
|
+
*/
|
|
220
|
+
export async function validateDestination(rawUrl, options = {}) {
|
|
221
|
+
const { allowPrivate = false, dnsLookup = dns.lookup } = options;
|
|
222
|
+
const url = assertHttpUrl(rawUrl);
|
|
223
|
+
const hostname = url.hostname.replace(/^\[|\]$/g, '').toLowerCase();
|
|
224
|
+
|
|
225
|
+
if (METADATA_HOSTNAMES.has(hostname)) {
|
|
226
|
+
throw new FetchError('FETCH_BLOCKED_METADATA', `Cloud metadata hostname refused: ${hostname}`, { url: url.href });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const port = url.port ? Number(url.port) : url.protocol === 'https:' ? 443 : 80;
|
|
230
|
+
if (!allowPrivate && !DEFAULT_PORTS.has(port)) {
|
|
231
|
+
throw new FetchError('FETCH_BLOCKED_PORT', `Port ${port} is not allowed for public scans`, { url: url.href });
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (!allowPrivate && (BLOCKED_HOSTNAMES.has(hostname) || hostname.endsWith('.localhost') || hostname.endsWith('.local') || hostname.endsWith('.internal'))) {
|
|
235
|
+
throw new FetchError('FETCH_BLOCKED_HOST', `Private hostname refused: ${hostname}`, { url: url.href });
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (isIpLiteral(hostname)) {
|
|
239
|
+
if (METADATA_ADDRESSES.has(hostname.toLowerCase())) {
|
|
240
|
+
throw new FetchError('FETCH_BLOCKED_METADATA', `Cloud metadata address refused: ${hostname}`, { url: url.href });
|
|
241
|
+
}
|
|
242
|
+
if (!allowPrivate && isBlockedAddress(hostname)) {
|
|
243
|
+
throw new FetchError('FETCH_BLOCKED_ADDRESS', `Private, loopback, or reserved address refused: ${hostname}`, { url: url.href });
|
|
244
|
+
}
|
|
245
|
+
const family = hostname.includes(':') ? 6 : 4;
|
|
246
|
+
return { url, address: hostname, family, addresses: [{ address: hostname, family }] };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
let answers;
|
|
250
|
+
try {
|
|
251
|
+
answers = await dnsLookup(hostname, { all: true, verbatim: true });
|
|
252
|
+
} catch (error) {
|
|
253
|
+
throw new FetchError('FETCH_DNS_ERROR', `Could not resolve ${hostname}: ${error?.code ?? error?.message}`, { url: url.href, cause: error });
|
|
254
|
+
}
|
|
255
|
+
const list = Array.isArray(answers) ? answers : answers ? [answers] : [];
|
|
256
|
+
if (list.length === 0) {
|
|
257
|
+
throw new FetchError('FETCH_DNS_ERROR', `No addresses for ${hostname}`, { url: url.href });
|
|
258
|
+
}
|
|
259
|
+
const metadataAnswer = list.find((answer) => METADATA_ADDRESSES.has(String(answer.address).toLowerCase()));
|
|
260
|
+
if (metadataAnswer) {
|
|
261
|
+
throw new FetchError('FETCH_BLOCKED_METADATA', `${hostname} resolves to a cloud metadata address: ${metadataAnswer.address}`, { url: url.href });
|
|
262
|
+
}
|
|
263
|
+
if (!allowPrivate) {
|
|
264
|
+
const bad = list.find((answer) => isBlockedAddress(answer.address));
|
|
265
|
+
if (bad) {
|
|
266
|
+
throw new FetchError('FETCH_BLOCKED_ADDRESS', `${hostname} resolves to a blocked address: ${bad.address}`, { url: url.href });
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
const addresses = list.map((answer) => ({
|
|
270
|
+
address: answer.address,
|
|
271
|
+
family: answer.family ?? (answer.address.includes(':') ? 6 : 4),
|
|
272
|
+
}));
|
|
273
|
+
return { url, address: addresses[0].address, family: addresses[0].family, addresses };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function decoderFor(encoding) {
|
|
277
|
+
if (encoding === 'gzip' || encoding === 'x-gzip') return zlib.createGunzip();
|
|
278
|
+
if (encoding === 'br') return zlib.createBrotliDecompress();
|
|
279
|
+
if (encoding === 'deflate') return zlib.createInflate();
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function sniffCharset(buffer, contentType) {
|
|
284
|
+
const header = /charset\s*=\s*"?([^";\s]+)"?/i.exec(contentType ?? '');
|
|
285
|
+
if (header) {
|
|
286
|
+
const value = header[1].toLowerCase();
|
|
287
|
+
return value === 'gb2312' ? 'gbk' : value;
|
|
288
|
+
}
|
|
289
|
+
if (buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf) return 'utf-8';
|
|
290
|
+
if (buffer.length >= 2 && buffer[0] === 0xff && buffer[1] === 0xfe) return 'utf-16le';
|
|
291
|
+
if (buffer.length >= 2 && buffer[0] === 0xfe && buffer[1] === 0xff) return 'utf-16be';
|
|
292
|
+
if (/html|xml/i.test(contentType ?? '')) {
|
|
293
|
+
// No header charset: browsers honour <meta charset> in the first 4 KB.
|
|
294
|
+
const head = buffer.subarray(0, 4096).toString('latin1');
|
|
295
|
+
const meta = /<meta[^>]+charset\s*=\s*["']?\s*([\w.-]+)/i.exec(head)
|
|
296
|
+
?? /<meta[^>]+content\s*=\s*["'][^"']*charset\s*=\s*([\w.-]+)/i.exec(head);
|
|
297
|
+
if (meta) {
|
|
298
|
+
const value = meta[1].toLowerCase();
|
|
299
|
+
return value === 'gb2312' ? 'gbk' : value;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return 'utf-8';
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Decode a response body using the header charset, a BOM, or (for HTML) the
|
|
307
|
+
* document's own <meta charset>. Export for tests.
|
|
308
|
+
*/
|
|
309
|
+
export function decodeBody(buffer, contentType) {
|
|
310
|
+
const charset = sniffCharset(buffer, contentType);
|
|
311
|
+
let bytes = buffer;
|
|
312
|
+
if (charset === 'utf-8' && bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
|
|
313
|
+
bytes = bytes.subarray(3);
|
|
314
|
+
} else if (charset === 'utf-16le' && bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) {
|
|
315
|
+
bytes = bytes.subarray(2);
|
|
316
|
+
} else if (charset === 'utf-16be' && bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) {
|
|
317
|
+
bytes = bytes.subarray(2);
|
|
318
|
+
}
|
|
319
|
+
try {
|
|
320
|
+
return new TextDecoder(charset).decode(bytes);
|
|
321
|
+
} catch {
|
|
322
|
+
return new TextDecoder('utf-8').decode(bytes);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function flattenHeaders(rawHeaders) {
|
|
327
|
+
const headers = {};
|
|
328
|
+
for (let i = 0; i + 1 < rawHeaders.length; i += 2) {
|
|
329
|
+
const key = rawHeaders[i].toLowerCase();
|
|
330
|
+
const value = rawHeaders[i + 1];
|
|
331
|
+
headers[key] = headers[key] ? `${headers[key]}, ${value}` : value;
|
|
332
|
+
}
|
|
333
|
+
return headers;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function readBody(stream, headers, maxBytes) {
|
|
337
|
+
return new Promise((resolve, reject) => {
|
|
338
|
+
const encodings = (headers['content-encoding'] ?? '')
|
|
339
|
+
.toLowerCase()
|
|
340
|
+
.split(',')
|
|
341
|
+
.map((value) => value.trim())
|
|
342
|
+
.filter((value) => value && value !== 'identity')
|
|
343
|
+
.reverse();
|
|
344
|
+
|
|
345
|
+
const layers = [];
|
|
346
|
+
let source = stream;
|
|
347
|
+
for (const encoding of encodings) {
|
|
348
|
+
const decoder = decoderFor(encoding);
|
|
349
|
+
if (!decoder) {
|
|
350
|
+
stream.destroy();
|
|
351
|
+
reject(new Error(`Unsupported content-encoding: ${encoding}`));
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
layers.push(decoder);
|
|
355
|
+
source = source.pipe(decoder);
|
|
356
|
+
}
|
|
357
|
+
const chunks = [];
|
|
358
|
+
let bytes = 0;
|
|
359
|
+
let truncated = false;
|
|
360
|
+
let ended = false;
|
|
361
|
+
let settled = false;
|
|
362
|
+
|
|
363
|
+
const done = (error) => {
|
|
364
|
+
if (settled) return;
|
|
365
|
+
settled = true;
|
|
366
|
+
if (error) reject(error);
|
|
367
|
+
else resolve({ buffer: Buffer.concat(chunks), truncated });
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
const stop = () => {
|
|
371
|
+
truncated = true;
|
|
372
|
+
for (const layer of layers) {
|
|
373
|
+
try { layer.destroy(); } catch { /* stream already closed */ }
|
|
374
|
+
}
|
|
375
|
+
try { source.destroy(); } catch { /* stream already closed */ }
|
|
376
|
+
try { stream.destroy(); } catch { /* stream already closed */ }
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
source.on('data', (chunk) => {
|
|
380
|
+
if (truncated) return;
|
|
381
|
+
const remaining = maxBytes - bytes;
|
|
382
|
+
if (remaining <= 0) {
|
|
383
|
+
stop();
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (chunk.length > remaining) {
|
|
387
|
+
chunks.push(chunk.subarray(0, remaining));
|
|
388
|
+
bytes = maxBytes;
|
|
389
|
+
stop();
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
chunks.push(chunk);
|
|
393
|
+
bytes += chunk.length;
|
|
394
|
+
});
|
|
395
|
+
source.on('end', () => {
|
|
396
|
+
ended = true;
|
|
397
|
+
done();
|
|
398
|
+
});
|
|
399
|
+
for (const layer of layers) {
|
|
400
|
+
layer.on('error', (error) => {
|
|
401
|
+
if (truncated) done();
|
|
402
|
+
else done(error);
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
source.on('error', (error) => {
|
|
406
|
+
if (truncated) done();
|
|
407
|
+
else done(error);
|
|
408
|
+
});
|
|
409
|
+
source.on('close', () => {
|
|
410
|
+
if (ended || settled) return;
|
|
411
|
+
if (truncated) done();
|
|
412
|
+
else done(new Error('response closed before the body ended'));
|
|
413
|
+
});
|
|
414
|
+
stream.on('error', (error) => {
|
|
415
|
+
if (truncated) done();
|
|
416
|
+
else done(error);
|
|
417
|
+
});
|
|
418
|
+
stream.on('aborted', () => {
|
|
419
|
+
if (truncated) done();
|
|
420
|
+
else done(new Error('response aborted'));
|
|
421
|
+
});
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Try each validated address in resolver order. Every attempt connects to an
|
|
427
|
+
* address that already passed the SSRF check (still pinned), so a broken IPv6
|
|
428
|
+
* record cannot silently turn into "site unreachable".
|
|
429
|
+
*/
|
|
430
|
+
async function requestWithFallback(target, options) {
|
|
431
|
+
const attempts = target.addresses?.length ? target.addresses : [{ address: target.address, family: target.family }];
|
|
432
|
+
let lastError = null;
|
|
433
|
+
for (const candidate of attempts) {
|
|
434
|
+
try {
|
|
435
|
+
return await requestOnce({ url: target.url, address: candidate.address, family: candidate.family }, options);
|
|
436
|
+
} catch (error) {
|
|
437
|
+
lastError = error;
|
|
438
|
+
const retryable = error.code === 'FETCH_NETWORK_ERROR' || error.code === 'FETCH_TIMEOUT';
|
|
439
|
+
if (!retryable) throw error;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
throw lastError;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function requestOnce(target, options) {
|
|
446
|
+
const { url, address, family } = target;
|
|
447
|
+
const isHttps = url.protocol === 'https:';
|
|
448
|
+
const transport = isHttps ? https : http;
|
|
449
|
+
const port = url.port ? Number(url.port) : isHttps ? 443 : 80;
|
|
450
|
+
|
|
451
|
+
const requestOptions = {
|
|
452
|
+
// Never let NODE_USE_ENV_PROXY / HTTP(S)_PROXY replace the pinned socket:
|
|
453
|
+
// a proxy would resolve and connect on our behalf, defeating the pin.
|
|
454
|
+
agent: false,
|
|
455
|
+
protocol: url.protocol,
|
|
456
|
+
hostname: url.hostname.replace(/^\[|\]$/g, ''),
|
|
457
|
+
port,
|
|
458
|
+
path: `${url.pathname}${url.search}`,
|
|
459
|
+
method: 'GET',
|
|
460
|
+
headers: {
|
|
461
|
+
'user-agent': options.userAgent,
|
|
462
|
+
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.5',
|
|
463
|
+
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
|
464
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
465
|
+
connection: 'close',
|
|
466
|
+
},
|
|
467
|
+
lookup: (hostname, lookupOptions, callback) => {
|
|
468
|
+
const options = typeof lookupOptions === 'function' ? {} : lookupOptions ?? {};
|
|
469
|
+
const done = typeof lookupOptions === 'function' ? lookupOptions : callback;
|
|
470
|
+
// Pinning to the validated address is what defeats DNS rebinding.
|
|
471
|
+
if (options.all === true) return done(null, [{ address, family }]);
|
|
472
|
+
return done(null, address, family);
|
|
473
|
+
},
|
|
474
|
+
rejectUnauthorized: options.insecureTls ? false : undefined,
|
|
475
|
+
timeout: options.timeoutMs,
|
|
476
|
+
servername: isHttps && !isIpLiteral(url.hostname) ? url.hostname : undefined,
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
return new Promise((resolve, reject) => {
|
|
480
|
+
let settled = false;
|
|
481
|
+
let deadline = null;
|
|
482
|
+
let request = null;
|
|
483
|
+
|
|
484
|
+
const settle = (payload) => {
|
|
485
|
+
if (settled) return;
|
|
486
|
+
settled = true;
|
|
487
|
+
if (deadline) clearTimeout(deadline);
|
|
488
|
+
resolve(payload);
|
|
489
|
+
};
|
|
490
|
+
const fail = (error) => {
|
|
491
|
+
if (settled) return;
|
|
492
|
+
settled = true;
|
|
493
|
+
if (deadline) clearTimeout(deadline);
|
|
494
|
+
reject(error);
|
|
495
|
+
};
|
|
496
|
+
|
|
497
|
+
try {
|
|
498
|
+
request = transport.request(requestOptions, (response) => {
|
|
499
|
+
const status = response.statusCode ?? 0;
|
|
500
|
+
const headers = flattenHeaders(response.rawHeaders);
|
|
501
|
+
|
|
502
|
+
if (status >= 300 && status < 400 && headers.location) {
|
|
503
|
+
response.resume();
|
|
504
|
+
settle({ status, headers, location: headers.location, buffer: Buffer.alloc(0), truncated: false, finalUrl: url.href });
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
readBody(response, headers, options.maxBytes).then(({ buffer, truncated }) => {
|
|
509
|
+
settle({ status, headers, buffer, truncated, finalUrl: url.href });
|
|
510
|
+
}).catch((error) => fail(new FetchError('FETCH_BODY_ERROR', `Could not decode body: ${error.message}`, { url: url.href, cause: error })));
|
|
511
|
+
});
|
|
512
|
+
} catch (error) {
|
|
513
|
+
fail(new FetchError('FETCH_INVALID_REQUEST', `Could not build request: ${error.message}`, { url: url.href, cause: error }));
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// A socket timeout only catches inactivity; the deadline bounds the whole
|
|
518
|
+
// request so a server trickling one byte at a time cannot hold us forever.
|
|
519
|
+
deadline = setTimeout(() => {
|
|
520
|
+
request?.destroy(new FetchError('FETCH_TIMEOUT', `Exceeded ${options.timeoutMs}ms total`, { url: url.href }));
|
|
521
|
+
}, options.timeoutMs);
|
|
522
|
+
deadline.unref?.();
|
|
523
|
+
|
|
524
|
+
request.on('timeout', () => {
|
|
525
|
+
request.destroy(new FetchError('FETCH_TIMEOUT', `Timed out after ${options.timeoutMs}ms`, { url: url.href }));
|
|
526
|
+
});
|
|
527
|
+
request.on('error', (error) => {
|
|
528
|
+
if (error instanceof FetchError) return fail(error);
|
|
529
|
+
fail(new FetchError('FETCH_NETWORK_ERROR', `${error.code ?? 'network error'}: ${error.message}`, { url: url.href, cause: error }));
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
if (options.signal) {
|
|
533
|
+
if (options.signal.aborted) {
|
|
534
|
+
request.destroy();
|
|
535
|
+
fail(new FetchError('FETCH_ABORTED', 'Fetch aborted', { url: url.href }));
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
options.signal.addEventListener('abort', () => {
|
|
539
|
+
request.destroy();
|
|
540
|
+
fail(new FetchError('FETCH_ABORTED', 'Fetch aborted', { url: url.href }));
|
|
541
|
+
}, { once: true });
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
request.end();
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Create a transport. The returned `fetch` never throws for non-2xx responses;
|
|
550
|
+
* HTTP status is part of the result. Transport failures throw FetchError.
|
|
551
|
+
*
|
|
552
|
+
* @param {object} [options]
|
|
553
|
+
* @param {boolean} [options.allowPrivate=false] Allow loopback/private targets (tests and explicit local audits only).
|
|
554
|
+
* @param {boolean} [options.insecureTls=false] Skip TLS verification (tests only).
|
|
555
|
+
* @param {string} [options.userAgent]
|
|
556
|
+
* @param {number} [options.timeoutMs=10000]
|
|
557
|
+
* @param {number} [options.maxBytes=1500000]
|
|
558
|
+
* @param {number} [options.rateLimitMs=250]
|
|
559
|
+
* @param {number} [options.maxRedirects=5]
|
|
560
|
+
* @param {Function} [options.dnsLookup] Injectable resolver, used by tests.
|
|
561
|
+
*/
|
|
562
|
+
export function createTransport(options = {}) {
|
|
563
|
+
const settings = {
|
|
564
|
+
allowPrivate: options.allowPrivate ?? false,
|
|
565
|
+
insecureTls: options.insecureTls ?? false,
|
|
566
|
+
userAgent: options.userAgent ?? DEFAULT_USER_AGENT,
|
|
567
|
+
timeoutMs: options.timeoutMs ?? 10_000,
|
|
568
|
+
maxBytes: options.maxBytes ?? 1_500_000,
|
|
569
|
+
rateLimitMs: options.rateLimitMs ?? 250,
|
|
570
|
+
maxRedirects: options.maxRedirects ?? 5,
|
|
571
|
+
dnsLookup: options.dnsLookup ?? dns.lookup,
|
|
572
|
+
};
|
|
573
|
+
|
|
574
|
+
const nextSlot = new Map();
|
|
575
|
+
|
|
576
|
+
async function waitForSlot(hostname) {
|
|
577
|
+
const now = Date.now();
|
|
578
|
+
const slot = nextSlot.get(hostname) ?? 0;
|
|
579
|
+
if (slot > now) await new Promise((resolve) => setTimeout(resolve, slot - now));
|
|
580
|
+
nextSlot.set(hostname, Date.now() + settings.rateLimitMs);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
async function fetch(url, overrides = {}) {
|
|
584
|
+
const maxBytes = overrides.maxBytes ?? settings.maxBytes;
|
|
585
|
+
const timeoutMs = overrides.timeoutMs ?? settings.timeoutMs;
|
|
586
|
+
const signal = overrides.signal;
|
|
587
|
+
const followRedirects = overrides.followRedirects ?? true;
|
|
588
|
+
let current = String(url);
|
|
589
|
+
const redirects = [];
|
|
590
|
+
|
|
591
|
+
for (let hop = 0; hop <= settings.maxRedirects; hop += 1) {
|
|
592
|
+
const target = await validateDestination(current, {
|
|
593
|
+
allowPrivate: settings.allowPrivate,
|
|
594
|
+
dnsLookup: settings.dnsLookup,
|
|
595
|
+
});
|
|
596
|
+
await waitForSlot(target.url.hostname);
|
|
597
|
+
const response = await requestWithFallback(target, {
|
|
598
|
+
userAgent: settings.userAgent,
|
|
599
|
+
timeoutMs,
|
|
600
|
+
maxBytes,
|
|
601
|
+
insecureTls: settings.insecureTls,
|
|
602
|
+
signal,
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
if (response.location) {
|
|
606
|
+
let nextUrl;
|
|
607
|
+
try {
|
|
608
|
+
nextUrl = new URL(response.location, current).href;
|
|
609
|
+
} catch {
|
|
610
|
+
throw new FetchError('FETCH_INVALID_REDIRECT', `Invalid Location header: ${String(response.location).slice(0, 200)}`, { url: current });
|
|
611
|
+
}
|
|
612
|
+
redirects.push({ from: current, to: nextUrl, status: response.status });
|
|
613
|
+
if (!followRedirects) {
|
|
614
|
+
return {
|
|
615
|
+
url: current,
|
|
616
|
+
status: response.status,
|
|
617
|
+
headers: response.headers,
|
|
618
|
+
contentType: response.headers['content-type'] ?? '',
|
|
619
|
+
body: '',
|
|
620
|
+
bytes: 0,
|
|
621
|
+
truncated: false,
|
|
622
|
+
redirects,
|
|
623
|
+
location: nextUrl,
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
if (hop === settings.maxRedirects) {
|
|
627
|
+
throw new FetchError('FETCH_TOO_MANY_REDIRECTS', `More than ${settings.maxRedirects} redirects`, { url: url });
|
|
628
|
+
}
|
|
629
|
+
current = nextUrl;
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
const contentType = response.headers['content-type'] ?? '';
|
|
634
|
+
return {
|
|
635
|
+
url: response.finalUrl,
|
|
636
|
+
status: response.status,
|
|
637
|
+
headers: response.headers,
|
|
638
|
+
contentType,
|
|
639
|
+
body: decodeBody(response.buffer, contentType),
|
|
640
|
+
bytes: response.buffer.length,
|
|
641
|
+
truncated: response.truncated || response.buffer.length >= maxBytes,
|
|
642
|
+
redirects,
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
throw new FetchError('FETCH_TOO_MANY_REDIRECTS', 'Redirect loop', { url: url });
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
return { fetch, settings };
|
|
650
|
+
}
|