submitnow-mcp 0.0.0-stage → 2.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.
@@ -0,0 +1,397 @@
1
+ import dns from 'node:dns';
2
+ import http from 'node:http';
3
+ import https from 'node:https';
4
+ import net from 'node:net';
5
+ export class SafeFetchError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message ?? code);
9
+ this.name = 'SafeFetchError';
10
+ this.code = code;
11
+ }
12
+ }
13
+ const BLOCKED_HOSTNAMES = new Set([
14
+ 'localhost',
15
+ 'localhost.localdomain',
16
+ 'metadata.google.internal',
17
+ 'metadata.goog',
18
+ 'metadata',
19
+ 'instance-data',
20
+ ]);
21
+ const BLOCKED_SUFFIXES = [
22
+ '.localhost',
23
+ '.local',
24
+ '.internal',
25
+ '.home.arpa',
26
+ ];
27
+ const ALLOWED_PORTS = new Set(['', '80', '443']);
28
+ function parseIpv4ToInt(ip) {
29
+ const parts = ip.split('.');
30
+ if (parts.length !== 4)
31
+ return null;
32
+ let value = 0;
33
+ for (const part of parts) {
34
+ if (!/^\d{1,3}$/.test(part))
35
+ return null;
36
+ const octet = Number(part);
37
+ if (octet < 0 || octet > 255)
38
+ return null;
39
+ value = value * 256 + octet;
40
+ }
41
+ return value >>> 0;
42
+ }
43
+ function ipv4InCidr(ipInt, baseIp, prefixLen) {
44
+ const baseInt = parseIpv4ToInt(baseIp);
45
+ if (baseInt === null)
46
+ return false;
47
+ const mask = prefixLen === 0 ? 0 : (~0 << (32 - prefixLen)) >>> 0;
48
+ return (ipInt & mask) === (baseInt & mask);
49
+ }
50
+ const RESERVED_IPV4_CIDRS = [
51
+ ['0.0.0.0', 8], // "This" network (RFC 1122)
52
+ ['10.0.0.0', 8], // Private-Use (RFC 1918)
53
+ ['100.64.0.0', 10], // Shared Address Space / CGNAT (RFC 6598)
54
+ ['127.0.0.0', 8], // Loopback (RFC 1122)
55
+ ['169.254.0.0', 16], // Link-Local & Cloud Metadata (RFC 3927)
56
+ ['172.16.0.0', 12], // Private-Use (RFC 1918)
57
+ ['192.0.0.0', 24], // IETF Protocol Assignments
58
+ ['192.0.2.0', 24], // TEST-NET-1
59
+ ['192.88.99.0', 24], // 6to4 Relay Anycast
60
+ ['192.168.0.0', 16], // Private-Use (RFC 1918)
61
+ ['198.18.0.0', 15], // Benchmarking
62
+ ['198.51.100.0', 24], // TEST-NET-2
63
+ ['203.0.113.0', 24], // TEST-NET-3
64
+ ['224.0.0.0', 4], // Multicast
65
+ ['240.0.0.0', 4], // Reserved / Broadcast
66
+ ];
67
+ function expandIpv6(ip) {
68
+ const cleaned = ip.toLowerCase().split('%')[0];
69
+ // Handle IPv4-embedded IPv6 such as ::ffff:127.0.0.1
70
+ const lastColon = cleaned.lastIndexOf(':');
71
+ let normalized = cleaned;
72
+ if (lastColon !== -1 && cleaned.slice(lastColon + 1).includes('.')) {
73
+ const ipv4 = parseIpv4ToInt(cleaned.slice(lastColon + 1));
74
+ if (ipv4 === null)
75
+ return null;
76
+ const hi = ((ipv4 >>> 16) & 0xffff).toString(16);
77
+ const lo = (ipv4 & 0xffff).toString(16);
78
+ normalized = `${cleaned.slice(0, lastColon)}:${hi}:${lo}`;
79
+ }
80
+ const halves = normalized.split('::');
81
+ if (halves.length > 2)
82
+ return null;
83
+ const parseGroups = (segment) => {
84
+ if (!segment)
85
+ return [];
86
+ const groups = segment.split(':');
87
+ const values = [];
88
+ for (const group of groups) {
89
+ if (!/^[0-9a-f]{1,4}$/.test(group))
90
+ return null;
91
+ values.push(parseInt(group, 16));
92
+ }
93
+ return values;
94
+ };
95
+ const left = parseGroups(halves[0]);
96
+ const right = halves.length === 2 ? parseGroups(halves[1]) : [];
97
+ if (!left || !right)
98
+ return null;
99
+ if (halves.length === 1) {
100
+ return left.length === 8 ? left : null;
101
+ }
102
+ const missing = 8 - (left.length + right.length);
103
+ if (missing < 1)
104
+ return null;
105
+ return [...left, ...new Array(missing).fill(0), ...right];
106
+ }
107
+ export function isPrivateOrReservedIp(rawIp) {
108
+ const ip = rawIp.trim().replace(/^\[|\]$/g, '');
109
+ const version = net.isIP(ip);
110
+ if (version === 4) {
111
+ const ipInt = parseIpv4ToInt(ip);
112
+ if (ipInt === null)
113
+ return true;
114
+ return RESERVED_IPV4_CIDRS.some(([base, prefix]) => ipv4InCidr(ipInt, base, prefix));
115
+ }
116
+ if (version === 6) {
117
+ const groups = expandIpv6(ip);
118
+ if (!groups)
119
+ return true;
120
+ const isAllZero = groups.every((g) => g === 0);
121
+ if (isAllZero)
122
+ return true; // ::
123
+ const isLoopback = groups.slice(0, 7).every((g) => g === 0) && groups[7] === 1;
124
+ if (isLoopback)
125
+ return true; // ::1
126
+ // IPv4-mapped (::ffff:0:0/96) or NAT64 well-known prefix (64:ff9b::/96)
127
+ const isIpv4Mapped = groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff;
128
+ const isNat64 = groups[0] === 0x0064 &&
129
+ groups[1] === 0xff9b &&
130
+ groups.slice(2, 6).every((g) => g === 0);
131
+ if (isIpv4Mapped || isNat64) {
132
+ const ipv4Int = ((groups[6] << 16) | groups[7]) >>> 0;
133
+ return RESERVED_IPV4_CIDRS.some(([base, prefix]) => ipv4InCidr(ipv4Int, base, prefix));
134
+ }
135
+ // Unique local fc00::/7 (fc00..fdff)
136
+ if ((groups[0] & 0xfe00) === 0xfc00)
137
+ return true;
138
+ // Link-local fe80::/10 (fe80..febf)
139
+ if ((groups[0] & 0xffc0) === 0xfe80)
140
+ return true;
141
+ // Deprecated site-local fec0::/10
142
+ if ((groups[0] & 0xffc0) === 0xfec0)
143
+ return true;
144
+ // Multicast ff00::/8
145
+ if ((groups[0] & 0xff00) === 0xff00)
146
+ return true;
147
+ // Documentation 2001:db8::/32
148
+ if (groups[0] === 0x2001 && groups[1] === 0x0db8)
149
+ return true;
150
+ // Discard-only 100::/64
151
+ if (groups[0] === 0x0100 && groups.slice(1, 4).every((g) => g === 0)) {
152
+ return true;
153
+ }
154
+ return false;
155
+ }
156
+ return true;
157
+ }
158
+ export function isBlockedHostname(rawHostname) {
159
+ const hostname = rawHostname.trim().toLowerCase().replace(/\.+$/, '');
160
+ if (!hostname)
161
+ return true;
162
+ if (BLOCKED_HOSTNAMES.has(hostname))
163
+ return true;
164
+ if (BLOCKED_SUFFIXES.some((suffix) => hostname.endsWith(suffix))) {
165
+ return true;
166
+ }
167
+ // Strip IPv6 brackets when testing raw IP literals
168
+ const unbracketed = hostname.replace(/^\[|\]$/g, '');
169
+ if (net.isIP(unbracketed) !== 0) {
170
+ return isPrivateOrReservedIp(unbracketed);
171
+ }
172
+ // Single-label hostnames (no dot) cannot be public internet domains
173
+ if (!hostname.includes('.'))
174
+ return true;
175
+ return false;
176
+ }
177
+ export function validatePublicHttpUrlSyntax(url) {
178
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
179
+ return false;
180
+ if (url.username || url.password)
181
+ return false;
182
+ if (!ALLOWED_PORTS.has(url.port))
183
+ return false;
184
+ if (isBlockedHostname(url.hostname))
185
+ return false;
186
+ return true;
187
+ }
188
+ /**
189
+ * Custom DNS lookup passed straight into Node's http/https socket creation.
190
+ * Resolving and validating inside the single connect-time lookup eliminates
191
+ * DNS rebinding TOCTOU between a pre-check and the actual TCP connection while
192
+ * keeping TLS SNI and certificate verification bound to the original hostname.
193
+ */
194
+ export function safeDnsLookup(hostname, options, maybeCallback) {
195
+ const opts = typeof options === 'function' ? {} : options ?? {};
196
+ const callback = typeof options === 'function' ? options : maybeCallback;
197
+ const unbracketed = hostname.replace(/^\[|\]$/g, '');
198
+ const ipVersion = net.isIP(unbracketed);
199
+ if (ipVersion !== 0) {
200
+ if (isPrivateOrReservedIp(unbracketed)) {
201
+ callback(new SafeFetchError('blocked_url', 'Target IP address is private or reserved.'), '');
202
+ return;
203
+ }
204
+ if (opts.all) {
205
+ callback(null, [{ address: unbracketed, family: ipVersion }]);
206
+ }
207
+ else {
208
+ callback(null, unbracketed, ipVersion);
209
+ }
210
+ return;
211
+ }
212
+ dns.lookup(unbracketed, { family: opts.family ?? 0, hints: opts.hints, all: true, verbatim: true }, (err, addresses) => {
213
+ if (err || !addresses || addresses.length === 0) {
214
+ callback(new SafeFetchError('fetch_failed', 'DNS lookup failed for target host.'), '');
215
+ return;
216
+ }
217
+ for (const record of addresses) {
218
+ if (isPrivateOrReservedIp(record.address)) {
219
+ callback(new SafeFetchError('blocked_url', 'Target host resolves to a private or reserved IP address.'), '');
220
+ return;
221
+ }
222
+ }
223
+ if (opts.all) {
224
+ callback(null, addresses);
225
+ }
226
+ else {
227
+ callback(null, addresses[0].address, addresses[0].family);
228
+ }
229
+ });
230
+ }
231
+ function toWebHeaders(rawHeaders) {
232
+ const headers = new Headers();
233
+ for (const [key, value] of Object.entries(rawHeaders)) {
234
+ if (value === undefined)
235
+ continue;
236
+ if (Array.isArray(value)) {
237
+ for (const item of value)
238
+ headers.append(key, item);
239
+ }
240
+ else {
241
+ headers.set(key, value);
242
+ }
243
+ }
244
+ return headers;
245
+ }
246
+ function fetchSingleHop(url, options, signal) {
247
+ return new Promise((resolve, reject) => {
248
+ if (!validatePublicHttpUrlSyntax(url)) {
249
+ reject(new SafeFetchError('blocked_url', 'Target URL is not a permitted public HTTP(S) address.'));
250
+ return;
251
+ }
252
+ const transport = url.protocol === 'https:' ? https : http;
253
+ let settled = false;
254
+ const finishReject = (err) => {
255
+ if (settled)
256
+ return;
257
+ settled = true;
258
+ reject(err);
259
+ };
260
+ const finishResolve = (value) => {
261
+ if (settled)
262
+ return;
263
+ settled = true;
264
+ resolve(value);
265
+ };
266
+ const req = transport.request(url, {
267
+ method: 'GET',
268
+ signal,
269
+ lookup: safeDnsLookup,
270
+ headers: {
271
+ Accept: options.accept ?? '*/*',
272
+ 'Accept-Encoding': 'identity',
273
+ 'User-Agent': options.userAgent ?? 'submitnow-bot/1.0 (+https://submitnow.dev)',
274
+ },
275
+ }, (res) => {
276
+ const status = res.statusCode ?? 0;
277
+ const headers = toWebHeaders(res.headers);
278
+ const location = headers.get('location');
279
+ if (status >= 300 && status < 400 && location) {
280
+ res.resume();
281
+ finishResolve({ kind: 'redirect', location });
282
+ return;
283
+ }
284
+ const chunks = [];
285
+ let total = 0;
286
+ let truncated = false;
287
+ res.on('data', (chunk) => {
288
+ if (settled)
289
+ return;
290
+ if (total + chunk.byteLength > options.maxBytes) {
291
+ if (!options.allowTruncate) {
292
+ res.destroy();
293
+ finishReject(new SafeFetchError('response_too_large'));
294
+ return;
295
+ }
296
+ const remaining = options.maxBytes - total;
297
+ if (remaining > 0) {
298
+ chunks.push(chunk.subarray(0, remaining));
299
+ total += remaining;
300
+ }
301
+ truncated = true;
302
+ res.destroy();
303
+ finishResolve({
304
+ kind: 'response',
305
+ status,
306
+ headers,
307
+ bytes: new Uint8Array(Buffer.concat(chunks, total)),
308
+ truncated: true,
309
+ });
310
+ return;
311
+ }
312
+ chunks.push(chunk);
313
+ total += chunk.byteLength;
314
+ });
315
+ res.on('end', () => {
316
+ finishResolve({
317
+ kind: 'response',
318
+ status,
319
+ headers,
320
+ bytes: new Uint8Array(Buffer.concat(chunks, total)),
321
+ truncated,
322
+ });
323
+ });
324
+ res.on('error', (err) => {
325
+ if (signal.aborted) {
326
+ finishReject(new SafeFetchError('timeout'));
327
+ return;
328
+ }
329
+ if (err instanceof SafeFetchError) {
330
+ finishReject(err);
331
+ return;
332
+ }
333
+ finishReject(new SafeFetchError('fetch_failed'));
334
+ });
335
+ });
336
+ req.on('error', (err) => {
337
+ if (signal.aborted) {
338
+ finishReject(new SafeFetchError('timeout'));
339
+ return;
340
+ }
341
+ if (err instanceof SafeFetchError) {
342
+ finishReject(err);
343
+ return;
344
+ }
345
+ finishReject(new SafeFetchError('fetch_failed'));
346
+ });
347
+ req.end();
348
+ });
349
+ }
350
+ /**
351
+ * Fetches a public HTTP(S) resource with connect-time DNS validation (immune
352
+ * to DNS rebinding TOCTOU), per-hop redirect validation, bounded streaming
353
+ * response reading, and an overall timeout.
354
+ */
355
+ export async function safeFetch(initialUrl, options) {
356
+ const maxRedirects = options.maxRedirects ?? 5;
357
+ const controller = new AbortController();
358
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs);
359
+ let currentUrl = new URL(initialUrl.toString());
360
+ try {
361
+ for (let hop = 0; hop <= maxRedirects; hop += 1) {
362
+ const outcome = await fetchSingleHop(currentUrl, options, controller.signal);
363
+ if (outcome.kind === 'redirect') {
364
+ if (hop === maxRedirects) {
365
+ throw new SafeFetchError('too_many_redirects');
366
+ }
367
+ try {
368
+ currentUrl = new URL(outcome.location, currentUrl);
369
+ }
370
+ catch {
371
+ throw new SafeFetchError('blocked_url');
372
+ }
373
+ continue;
374
+ }
375
+ return {
376
+ status: outcome.status,
377
+ ok: outcome.status >= 200 && outcome.status < 300,
378
+ headers: outcome.headers,
379
+ finalUrl: currentUrl.toString(),
380
+ bytes: outcome.bytes,
381
+ truncated: outcome.truncated,
382
+ };
383
+ }
384
+ throw new SafeFetchError('too_many_redirects');
385
+ }
386
+ catch (error) {
387
+ if (error instanceof SafeFetchError)
388
+ throw error;
389
+ if (error instanceof Error && error.name === 'AbortError') {
390
+ throw new SafeFetchError('timeout');
391
+ }
392
+ throw new SafeFetchError('fetch_failed');
393
+ }
394
+ finally {
395
+ clearTimeout(timer);
396
+ }
397
+ }