@goosetools/goose-tools 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +98 -2
- package/bin/goose-tools.js +61 -0
- package/lib/check/src/agent.js +90 -0
- package/lib/check/src/analyze.js +311 -0
- package/lib/check/src/client.js +136 -0
- package/lib/check/src/copy.js +355 -0
- package/lib/check/src/fixes.js +153 -0
- package/lib/check/src/frame.js +92 -0
- package/lib/check/src/guard.js +441 -0
- package/lib/check/src/index.js +18 -0
- package/lib/check/src/mcp-http.js +169 -0
- package/lib/check/src/mcp.js +153 -0
- package/lib/check/src/scan.js +55 -0
- package/lib/check/src/stack.js +61 -0
- package/lib/check/src/tlds.js +3 -0
- package/lib/check/src/view.js +130 -0
- package/lib/check/src/worker.js +257 -0
- package/lib/engine/src/bots.js +146 -0
- package/lib/engine/src/directives.js +131 -0
- package/lib/engine/src/exposure.js +70 -0
- package/lib/engine/src/frontend.js +157 -0
- package/lib/engine/src/headers.js +76 -0
- package/lib/engine/src/hidden-text.js +425 -0
- package/lib/engine/src/html.js +794 -0
- package/lib/engine/src/index.js +20 -0
- package/lib/engine/src/php.js +316 -0
- package/lib/engine/src/policies.js +234 -0
- package/lib/engine/src/reach.js +199 -0
- package/lib/engine/src/robots.js +275 -0
- package/lib/engine/src/secrets.js +142 -0
- package/lib/engine/src/signals.js +144 -0
- package/lib/rules/data/bots.json.js +1 -0
- package/lib/rules/data/exposure.json.js +1 -0
- package/lib/rules/data/frontend.json.js +1 -0
- package/lib/rules/data/headers.json.js +1 -0
- package/lib/rules/data/secrets.json.js +1 -0
- package/lib/ui/LICENSE-Inter.txt +93 -0
- package/lib/ui/assets.js +5 -0
- package/package.json +37 -4
- package/src/local.js +61 -0
- package/src/mcp.js +61 -0
- package/src/setup.js +395 -0
- package/src/site/auth.js +287 -0
- package/src/site/beacon.js +462 -0
- package/src/site/collect.js +484 -0
- package/src/site/handler.js +405 -0
- package/src/site/index.js +88 -0
- package/src/site/limits.js +48 -0
- package/src/site/pages.js +75 -0
- package/src/site/qr.js +318 -0
- package/src/site/reports.js +1117 -0
- package/src/site/source.js +68 -0
- package/src/site/store-pg.js +225 -0
- package/src/site/store.js +249 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The wire format between the check Worker and the check page.
|
|
3
|
+
*
|
|
4
|
+
* The Workers Free plan allows 10 ms of CPU a request. Decoding a 2 MB page and writing it into
|
|
5
|
+
* JSON would use most of that, so the Worker sends the bytes as fetched:
|
|
6
|
+
*
|
|
7
|
+
* 4 bytes length of the header, big-endian
|
|
8
|
+
* header UTF-8 JSON: { v: 1, parts: [Part, ...] }
|
|
9
|
+
* bodies each part's body, in the order of `parts`, `size` bytes each
|
|
10
|
+
*
|
|
11
|
+
* A Part is { name, url, status, headers: [[name, value], ...], size, truncated, redirects }
|
|
12
|
+
* or { name, url, error: { code, reason } } when it could not be fetched.
|
|
13
|
+
*
|
|
14
|
+
* Plain JavaScript, no dependencies. Runs in the Worker and in the browser.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export const VERSION = 1;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {object} PartHead
|
|
21
|
+
* @property {string} name page, robots, sitemap, llms, or script.
|
|
22
|
+
* @property {string} url The URL asked for, or the final URL after redirects.
|
|
23
|
+
* @property {number} [status]
|
|
24
|
+
* @property {[string, string][]} [headers]
|
|
25
|
+
* @property {number} [size] Body bytes that follow in the frame.
|
|
26
|
+
* @property {boolean} [truncated]
|
|
27
|
+
* @property {string[]} [redirects]
|
|
28
|
+
* @property {{code: string, reason: string}} [error]
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Build a frame.
|
|
33
|
+
* @param {{head: PartHead, body?: Uint8Array}[]} parts
|
|
34
|
+
* @returns {Uint8Array}
|
|
35
|
+
*/
|
|
36
|
+
export function frame(parts) {
|
|
37
|
+
const heads = parts.map(({ head, body }) => (head.error ? head : { ...head, size: body ? body.byteLength : 0 }));
|
|
38
|
+
const header = new TextEncoder().encode(JSON.stringify({ v: VERSION, parts: heads }));
|
|
39
|
+
const total = 4 + header.byteLength + parts.reduce((n, p) => n + (p.head.error || !p.body ? 0 : p.body.byteLength), 0);
|
|
40
|
+
const out = new Uint8Array(total);
|
|
41
|
+
new DataView(out.buffer).setUint32(0, header.byteLength);
|
|
42
|
+
out.set(header, 4);
|
|
43
|
+
let at = 4 + header.byteLength;
|
|
44
|
+
for (const p of parts) {
|
|
45
|
+
if (p.head.error || !p.body) continue;
|
|
46
|
+
out.set(p.body, at);
|
|
47
|
+
at += p.body.byteLength;
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @typedef {PartHead & {bytes: Uint8Array | null}} Part
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Read a frame. Throws on anything malformed.
|
|
58
|
+
* @param {ArrayBuffer | Uint8Array} input
|
|
59
|
+
* @returns {Part[]}
|
|
60
|
+
*/
|
|
61
|
+
export function unframe(input) {
|
|
62
|
+
const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
|
|
63
|
+
if (bytes.byteLength < 4) throw new Error('frame: too short');
|
|
64
|
+
const len = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0);
|
|
65
|
+
if (4 + len > bytes.byteLength) throw new Error('frame: header runs past the end');
|
|
66
|
+
const head = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(4, 4 + len)));
|
|
67
|
+
if (!head || head.v !== VERSION || !Array.isArray(head.parts)) throw new Error('frame: unknown version');
|
|
68
|
+
let at = 4 + len;
|
|
69
|
+
/** @type {Part[]} */
|
|
70
|
+
const out = [];
|
|
71
|
+
for (const p of head.parts) {
|
|
72
|
+
if (p.error) {
|
|
73
|
+
out.push({ ...p, bytes: null });
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const size = Number(p.size);
|
|
77
|
+
if (!Number.isInteger(size) || size < 0 || at + size > bytes.byteLength) throw new Error('frame: body runs past the end');
|
|
78
|
+
out.push({ ...p, bytes: bytes.subarray(at, at + size) });
|
|
79
|
+
at += size;
|
|
80
|
+
}
|
|
81
|
+
if (at !== bytes.byteLength) throw new Error('frame: extra bytes at the end');
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* A part's body as text. Invalid UTF-8 becomes U+FFFD, as a browser shows it.
|
|
87
|
+
* @param {Part} part
|
|
88
|
+
* @returns {string}
|
|
89
|
+
*/
|
|
90
|
+
export function text(part) {
|
|
91
|
+
return part.bytes ? new TextDecoder('utf-8').decode(part.bytes) : '';
|
|
92
|
+
}
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guards for the check Worker's `POST /fetch`: refuse server-side request forgery and stay
|
|
3
|
+
* inside the Workers Free plan limits.
|
|
4
|
+
*
|
|
5
|
+
* Rules (spec/standalone.md section 3):
|
|
6
|
+
* - http and https only, ports 80 and 443 only, no user name or password in the URL.
|
|
7
|
+
* - No IP literal in a private, loopback, link-local, CGNAT, multicast or reserved range,
|
|
8
|
+
* for IPv4 and IPv6. Public IP literals are allowed.
|
|
9
|
+
* - Hostnames must look like public DNS names. Names that are local by definition are refused.
|
|
10
|
+
* - Redirects are followed by hand, at most 5, and every hop is checked again.
|
|
11
|
+
* - Only the first 2 MB of a body is read. Past that, the stream is cut and the result is marked
|
|
12
|
+
* `truncated`, so a large page is still checked (Googlebot also reads a capped prefix). With
|
|
13
|
+
* `overflow: 'refuse'` it is refused instead. The whole fetch has 10 seconds.
|
|
14
|
+
*
|
|
15
|
+
* Hostnames that resolve to private addresses:
|
|
16
|
+
* A Worker cannot see the address a hostname resolves to, so this module cannot check it.
|
|
17
|
+
* Cloudflare's Workers security model says every outbound request from a Worker goes through a
|
|
18
|
+
* local proxy that "verifies that the request is either addressed to a public Internet service
|
|
19
|
+
* or to the Worker's zone's own origin server, not to internal services that might be visible
|
|
20
|
+
* on the local machine or network."
|
|
21
|
+
* Source: https://developers.cloudflare.com/workers/reference/security-model/
|
|
22
|
+
* So a public name that points at 10.0.0.1 or 127.0.0.1 (including DNS rebinding) is stopped by
|
|
23
|
+
* the platform, not by this file. What this file does about it:
|
|
24
|
+
* - It refuses names that are private by construction (localhost, .local, .internal,
|
|
25
|
+
* .home.arpa and other special-use names, single-label names, numeric last labels).
|
|
26
|
+
* - It checks every redirect hop, so a public page cannot hand the Worker a private literal.
|
|
27
|
+
* - It does not look names up over DNS-over-HTTPS. A lookup would not match the address the
|
|
28
|
+
* platform connects to (rebinding wins that race), and it would cost subrequests from the
|
|
29
|
+
* Free plan's 50 per request.
|
|
30
|
+
* - The check Worker should run on a zone with no origin server, so "the Worker's zone's own
|
|
31
|
+
* origin" has nothing behind it.
|
|
32
|
+
* Confirmed on the deployed Worker 2026-11-20 (check/dev/risk3.mjs): public names that point at
|
|
33
|
+
* 127.0.0.1, 10.0.0.1 and 169.254.169.254, and a rebinding name, all got Cloudflare error 1016.
|
|
34
|
+
*
|
|
35
|
+
* Plain JavaScript, no dependencies. Written for the Workers runtime; tests run it in Node.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
import { TLDS } from './tlds.js';
|
|
39
|
+
|
|
40
|
+
export const MAX_REDIRECTS = 5;
|
|
41
|
+
export const MAX_BODY_BYTES = 2 * 1024 * 1024;
|
|
42
|
+
export const TIMEOUT_MS = 10_000;
|
|
43
|
+
export const MAX_URL_LENGTH = 2048;
|
|
44
|
+
|
|
45
|
+
const ALLOWED_PORTS = new Set(['', '80', '443']);
|
|
46
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Special-use and private-use names (RFC 6761, RFC 6762, RFC 8375, RFC 7686, and the
|
|
50
|
+
* ICANN reservation of .internal). Matched as the whole name or as its last labels.
|
|
51
|
+
*/
|
|
52
|
+
const BLOCKED_SUFFIXES = [
|
|
53
|
+
'localhost',
|
|
54
|
+
'local',
|
|
55
|
+
'localdomain',
|
|
56
|
+
'internal',
|
|
57
|
+
'intranet',
|
|
58
|
+
'lan',
|
|
59
|
+
'home',
|
|
60
|
+
'corp',
|
|
61
|
+
'home.arpa',
|
|
62
|
+
'test',
|
|
63
|
+
'example',
|
|
64
|
+
'invalid',
|
|
65
|
+
'onion',
|
|
66
|
+
'arpa',
|
|
67
|
+
];
|
|
68
|
+
|
|
69
|
+
/** A refusal with a stable machine-readable code. */
|
|
70
|
+
export class GuardError extends Error {
|
|
71
|
+
/**
|
|
72
|
+
* @param {string} code Short code, for example `private_address`.
|
|
73
|
+
* @param {string} message Plain-language reason.
|
|
74
|
+
*/
|
|
75
|
+
constructor(code, message) {
|
|
76
|
+
super(message);
|
|
77
|
+
this.name = 'GuardError';
|
|
78
|
+
this.code = code;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Parse a dotted-quad IPv4 string into a 32-bit unsigned number.
|
|
84
|
+
* The URL parser has already turned forms like 0x7f.1 or 2130706433 into a dotted quad.
|
|
85
|
+
* @param {string} s
|
|
86
|
+
* @returns {number | null}
|
|
87
|
+
*/
|
|
88
|
+
function parseIPv4(s) {
|
|
89
|
+
const parts = s.split('.');
|
|
90
|
+
if (parts.length !== 4) return null;
|
|
91
|
+
let n = 0;
|
|
92
|
+
for (const p of parts) {
|
|
93
|
+
if (!/^\d{1,3}$/.test(p)) return null;
|
|
94
|
+
const v = Number(p);
|
|
95
|
+
if (v > 255) return null;
|
|
96
|
+
n = n * 256 + v;
|
|
97
|
+
}
|
|
98
|
+
return n;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* IPv4 ranges that are not public (IANA IPv4 Special-Purpose Address Registry, plus multicast
|
|
103
|
+
* and the reserved 240.0.0.0/4 block). Each entry is [network, prefix length].
|
|
104
|
+
* @type {[string, number][]}
|
|
105
|
+
*/
|
|
106
|
+
const IPV4_BLOCKED = [
|
|
107
|
+
['0.0.0.0', 8], // "this network"
|
|
108
|
+
['10.0.0.0', 8], // private
|
|
109
|
+
['100.64.0.0', 10], // CGNAT shared address space
|
|
110
|
+
['127.0.0.0', 8], // loopback
|
|
111
|
+
['169.254.0.0', 16], // link-local, includes cloud metadata 169.254.169.254
|
|
112
|
+
['172.16.0.0', 12], // private
|
|
113
|
+
['192.0.0.0', 24], // IETF protocol assignments
|
|
114
|
+
['192.0.2.0', 24], // documentation
|
|
115
|
+
['192.88.99.0', 24], // 6to4 relay anycast, deprecated
|
|
116
|
+
['192.168.0.0', 16], // private
|
|
117
|
+
['198.18.0.0', 15], // benchmarking
|
|
118
|
+
['198.51.100.0', 24], // documentation
|
|
119
|
+
['203.0.113.0', 24], // documentation
|
|
120
|
+
['224.0.0.0', 4], // multicast
|
|
121
|
+
['240.0.0.0', 4], // reserved, includes broadcast 255.255.255.255
|
|
122
|
+
];
|
|
123
|
+
|
|
124
|
+
const IPV4_BLOCKED_NUMERIC = IPV4_BLOCKED.map(([net, len]) => {
|
|
125
|
+
const n = /** @type {number} */ (parseIPv4(net));
|
|
126
|
+
const size = 2 ** (32 - len);
|
|
127
|
+
return { start: n, end: n + size - 1 };
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* @param {string} ip Dotted-quad IPv4 address.
|
|
132
|
+
* @returns {boolean} True when the address is not a public unicast address.
|
|
133
|
+
*/
|
|
134
|
+
export function isBlockedIPv4(ip) {
|
|
135
|
+
const n = parseIPv4(ip);
|
|
136
|
+
if (n === null) return true;
|
|
137
|
+
return IPV4_BLOCKED_NUMERIC.some((r) => n >= r.start && n <= r.end);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Expand an IPv6 address (without brackets) into 8 numbers of 16 bits.
|
|
142
|
+
* Accepts an embedded IPv4 tail such as ::ffff:1.2.3.4.
|
|
143
|
+
* @param {string} s
|
|
144
|
+
* @returns {number[] | null}
|
|
145
|
+
*/
|
|
146
|
+
function parseIPv6(s) {
|
|
147
|
+
let text = s.toLowerCase();
|
|
148
|
+
if (text.includes('%')) return null; // zone ids never appear in URLs we accept
|
|
149
|
+
const lastColon = text.lastIndexOf(':');
|
|
150
|
+
const tail = text.slice(lastColon + 1);
|
|
151
|
+
if (tail.includes('.')) {
|
|
152
|
+
const v4 = parseIPv4(tail);
|
|
153
|
+
if (v4 === null) return null;
|
|
154
|
+
text = `${text.slice(0, lastColon + 1)}${Math.floor(v4 / 65536).toString(16)}:${(v4 % 65536).toString(16)}`;
|
|
155
|
+
}
|
|
156
|
+
const halves = text.split('::');
|
|
157
|
+
if (halves.length > 2) return null;
|
|
158
|
+
/** @param {string} h */
|
|
159
|
+
const groups = (h) => (h === '' ? [] : h.split(':'));
|
|
160
|
+
/** @param {string[]} g */
|
|
161
|
+
const nums = (g) => g.map((x) => (/^[0-9a-f]{1,4}$/.test(x) ? parseInt(x, 16) : NaN));
|
|
162
|
+
const a = nums(groups(halves[0]));
|
|
163
|
+
const b = halves.length === 2 ? nums(groups(halves[1])) : [];
|
|
164
|
+
if ([...a, ...b].some(Number.isNaN)) return null;
|
|
165
|
+
const total = a.length + b.length;
|
|
166
|
+
if (halves.length === 1) return total === 8 ? a : null;
|
|
167
|
+
if (total > 7) return null;
|
|
168
|
+
return [...a, ...new Array(8 - total).fill(0), ...b];
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* IPv6 is public only inside 2000::/3 (global unicast). Inside that block, these are refused:
|
|
173
|
+
* 2001::/23 (IETF protocol assignments, includes Teredo 2001::/32), 2001:db8::/32 and
|
|
174
|
+
* 3fff::/20 (documentation), and 2002::/16 when its embedded IPv4 address is not public (6to4).
|
|
175
|
+
* Everything outside 2000::/3 is refused, which covers ::, ::1, IPv4-mapped ::ffff:0:0/96,
|
|
176
|
+
* NAT64 64:ff9b::/96, discard 100::/64, unique local fc00::/7, link-local fe80::/10,
|
|
177
|
+
* site-local fec0::/10, multicast ff00::/8 and SRv6 5f00::/16.
|
|
178
|
+
* @param {string} ip IPv6 address without brackets.
|
|
179
|
+
* @returns {boolean} True when the address is not a public unicast address.
|
|
180
|
+
*/
|
|
181
|
+
export function isBlockedIPv6(ip) {
|
|
182
|
+
const g = parseIPv6(ip);
|
|
183
|
+
if (!g) return true;
|
|
184
|
+
if ((g[0] & 0xe000) !== 0x2000) return true; // outside 2000::/3
|
|
185
|
+
if (g[0] === 0x2001 && g[1] < 0x0200) return true; // 2001::/23
|
|
186
|
+
if (g[0] === 0x2001 && g[1] === 0x0db8) return true; // 2001:db8::/32
|
|
187
|
+
if (g[0] === 0x3fff && g[1] < 0x1000) return true; // 3fff::/20
|
|
188
|
+
if (g[0] === 0x2002) {
|
|
189
|
+
const v4 = `${g[1] >> 8}.${g[1] & 255}.${g[2] >> 8}.${g[2] & 255}`;
|
|
190
|
+
return isBlockedIPv4(v4);
|
|
191
|
+
}
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* @param {string} host Hostname as the URL parser returns it (lowercase, punycode).
|
|
197
|
+
* @returns {string | null} Refusal code, or null when the name looks like a public DNS name.
|
|
198
|
+
*/
|
|
199
|
+
function hostnameProblem(host) {
|
|
200
|
+
if (host.length === 0 || host.length > 253) return 'bad_hostname';
|
|
201
|
+
if (host.endsWith('.')) return 'bad_hostname';
|
|
202
|
+
const labels = host.split('.');
|
|
203
|
+
if (labels.length < 2) return 'blocked_host';
|
|
204
|
+
for (const label of labels) {
|
|
205
|
+
if (label.length < 1 || label.length > 63) return 'bad_hostname';
|
|
206
|
+
if (!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label)) return 'bad_hostname';
|
|
207
|
+
}
|
|
208
|
+
const tld = labels[labels.length - 1];
|
|
209
|
+
if (/^\d+$/.test(tld)) return 'bad_hostname';
|
|
210
|
+
for (const suffix of BLOCKED_SUFFIXES) {
|
|
211
|
+
if (host === suffix || host.endsWith('.' + suffix)) return 'blocked_host';
|
|
212
|
+
}
|
|
213
|
+
// The last label must be a real top-level domain (IANA's list, check/src/tlds.js).
|
|
214
|
+
if (!TLDS.has(tld)) return 'bad_hostname';
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* @typedef {object} TargetOk
|
|
220
|
+
* @property {true} ok
|
|
221
|
+
* @property {URL} url Normalized URL, fragment removed.
|
|
222
|
+
*
|
|
223
|
+
* @typedef {object} TargetRefused
|
|
224
|
+
* @property {false} ok
|
|
225
|
+
* @property {string} code
|
|
226
|
+
* @property {string} reason
|
|
227
|
+
*/
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Check one URL against the rules. Pure: no network, no DNS.
|
|
231
|
+
* @param {string | URL} input
|
|
232
|
+
* @returns {TargetOk | TargetRefused}
|
|
233
|
+
*/
|
|
234
|
+
export function validateTarget(input) {
|
|
235
|
+
const raw = String(input);
|
|
236
|
+
if (raw.length > MAX_URL_LENGTH) return refuse('bad_url', 'The address is too long.');
|
|
237
|
+
/** @type {URL} */
|
|
238
|
+
let url;
|
|
239
|
+
try {
|
|
240
|
+
url = new URL(raw);
|
|
241
|
+
} catch {
|
|
242
|
+
return refuse('bad_url', 'The address is not a valid URL.');
|
|
243
|
+
}
|
|
244
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
245
|
+
return refuse('bad_scheme', 'Only http and https addresses can be checked.');
|
|
246
|
+
}
|
|
247
|
+
if (url.username !== '' || url.password !== '') {
|
|
248
|
+
return refuse('credentials', 'Addresses with a user name or password are not fetched.');
|
|
249
|
+
}
|
|
250
|
+
if (!ALLOWED_PORTS.has(url.port)) {
|
|
251
|
+
return refuse('bad_port', 'Only ports 80 and 443 can be checked.');
|
|
252
|
+
}
|
|
253
|
+
const host = url.hostname;
|
|
254
|
+
if (host.startsWith('[')) {
|
|
255
|
+
if (isBlockedIPv6(host.slice(1, -1))) {
|
|
256
|
+
return refuse('private_address', 'The address points to a private or reserved network.');
|
|
257
|
+
}
|
|
258
|
+
} else if (parseIPv4(host) !== null) {
|
|
259
|
+
if (isBlockedIPv4(host)) {
|
|
260
|
+
return refuse('private_address', 'The address points to a private or reserved network.');
|
|
261
|
+
}
|
|
262
|
+
} else {
|
|
263
|
+
const problem = hostnameProblem(host);
|
|
264
|
+
if (problem === 'blocked_host') return refuse(problem, 'The name is for local or private networks.');
|
|
265
|
+
if (problem) return refuse(problem, 'The name is not a valid public hostname.');
|
|
266
|
+
}
|
|
267
|
+
url.hash = '';
|
|
268
|
+
return { ok: true, url };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* @param {string} code
|
|
273
|
+
* @param {string} reason
|
|
274
|
+
* @returns {TargetRefused}
|
|
275
|
+
*/
|
|
276
|
+
function refuse(code, reason) {
|
|
277
|
+
return { ok: false, code, reason };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* @typedef {object} GuardedResponse
|
|
282
|
+
* @property {string} url Final URL after redirects.
|
|
283
|
+
* @property {number} status
|
|
284
|
+
* @property {Headers} headers
|
|
285
|
+
* @property {Uint8Array} body At most MAX_BODY_BYTES.
|
|
286
|
+
* @property {boolean} truncated True when the body was longer than the limit and was cut.
|
|
287
|
+
* @property {string[]} redirects Every URL that answered with a redirect, in order.
|
|
288
|
+
*/
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* @typedef {object} GuardedFetchOptions
|
|
292
|
+
* @property {HeadersInit} [headers] Request headers, for example a User-Agent.
|
|
293
|
+
* @property {typeof fetch} [fetchImpl] Defaults to the global fetch.
|
|
294
|
+
* @property {(url: string | URL) => TargetOk | TargetRefused} [validate] Defaults to validateTarget.
|
|
295
|
+
* Tests swap it to reach a local server. Production code must not pass it.
|
|
296
|
+
* @property {number} [timeoutMs] Overall limit for every hop and the body. Default 10 seconds.
|
|
297
|
+
* @property {number} [maxBytes] Body limit. Default 2 MB.
|
|
298
|
+
* @property {'truncate' | 'refuse'} [overflow] What to do past the limit. Default 'truncate'.
|
|
299
|
+
* @property {number} [maxRedirects] Default 5.
|
|
300
|
+
*/
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* GET a URL under the guard rules. Throws GuardError on any refusal.
|
|
304
|
+
* @param {string | URL} target
|
|
305
|
+
* @param {GuardedFetchOptions} [options]
|
|
306
|
+
* @returns {Promise<GuardedResponse>}
|
|
307
|
+
*/
|
|
308
|
+
export async function guardedFetch(target, options = {}) {
|
|
309
|
+
const {
|
|
310
|
+
headers,
|
|
311
|
+
fetchImpl = globalThis.fetch,
|
|
312
|
+
validate = validateTarget,
|
|
313
|
+
timeoutMs = TIMEOUT_MS,
|
|
314
|
+
maxBytes = MAX_BODY_BYTES,
|
|
315
|
+
maxRedirects = MAX_REDIRECTS,
|
|
316
|
+
overflow = 'truncate',
|
|
317
|
+
} = options;
|
|
318
|
+
|
|
319
|
+
const controller = new AbortController();
|
|
320
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
321
|
+
let timer;
|
|
322
|
+
const timedOut = new Promise((_, reject) => {
|
|
323
|
+
timer = setTimeout(() => {
|
|
324
|
+
controller.abort();
|
|
325
|
+
reject(new GuardError('timeout', `No complete answer within ${timeoutMs / 1000} seconds.`));
|
|
326
|
+
}, timeoutMs);
|
|
327
|
+
});
|
|
328
|
+
timedOut.catch(() => {}); // handled through the race below
|
|
329
|
+
|
|
330
|
+
try {
|
|
331
|
+
return await Promise.race([run(), timedOut]);
|
|
332
|
+
} finally {
|
|
333
|
+
clearTimeout(timer);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
async function run() {
|
|
337
|
+
/** @type {string[]} */
|
|
338
|
+
const redirects = [];
|
|
339
|
+
let current = String(target);
|
|
340
|
+
for (let hop = 0; ; hop++) {
|
|
341
|
+
const check = validate(current);
|
|
342
|
+
if (!check.ok) throw new GuardError(check.code, check.reason);
|
|
343
|
+
const url = check.url;
|
|
344
|
+
|
|
345
|
+
/** @type {Response} */
|
|
346
|
+
let res;
|
|
347
|
+
try {
|
|
348
|
+
res = await fetchImpl(url.href, {
|
|
349
|
+
method: 'GET',
|
|
350
|
+
headers,
|
|
351
|
+
redirect: 'manual',
|
|
352
|
+
signal: controller.signal,
|
|
353
|
+
});
|
|
354
|
+
} catch {
|
|
355
|
+
if (controller.signal.aborted) throw new GuardError('timeout', 'The site took too long to answer.');
|
|
356
|
+
throw new GuardError('fetch_failed', 'The site could not be reached.');
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const location = res.headers.get('location');
|
|
360
|
+
if (REDIRECT_STATUSES.has(res.status) && location) {
|
|
361
|
+
await discard(res);
|
|
362
|
+
if (hop >= maxRedirects) {
|
|
363
|
+
throw new GuardError('too_many_redirects', `More than ${maxRedirects} redirects.`);
|
|
364
|
+
}
|
|
365
|
+
redirects.push(url.href);
|
|
366
|
+
try {
|
|
367
|
+
current = new URL(location, url).href;
|
|
368
|
+
} catch {
|
|
369
|
+
throw new GuardError('bad_redirect', 'A redirect pointed to an invalid address.');
|
|
370
|
+
}
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const declared = Number(res.headers.get('content-length'));
|
|
375
|
+
if (overflow === 'refuse' && Number.isFinite(declared) && declared > maxBytes) {
|
|
376
|
+
await discard(res);
|
|
377
|
+
throw new GuardError('too_large', `The response is larger than ${maxBytes / 1024 / 1024} MB.`);
|
|
378
|
+
}
|
|
379
|
+
const { body, truncated } = await readCapped(res, maxBytes, overflow, controller.signal);
|
|
380
|
+
return { url: url.href, status: res.status, headers: res.headers, body, truncated, redirects };
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Read a body into memory, stopping as soon as it passes the limit.
|
|
387
|
+
* @param {Response} res
|
|
388
|
+
* @param {number} maxBytes
|
|
389
|
+
* @param {'truncate' | 'refuse'} overflow
|
|
390
|
+
* @param {AbortSignal} signal
|
|
391
|
+
* @returns {Promise<{ body: Uint8Array, truncated: boolean }>}
|
|
392
|
+
*/
|
|
393
|
+
async function readCapped(res, maxBytes, overflow, signal) {
|
|
394
|
+
if (!res.body) return { body: new Uint8Array(0), truncated: false };
|
|
395
|
+
const reader = res.body.getReader();
|
|
396
|
+
/** @type {Uint8Array[]} */
|
|
397
|
+
const chunks = [];
|
|
398
|
+
let size = 0;
|
|
399
|
+
let truncated = false;
|
|
400
|
+
try {
|
|
401
|
+
for (;;) {
|
|
402
|
+
const { done, value } = await reader.read();
|
|
403
|
+
if (done) break;
|
|
404
|
+
if (size + value.byteLength > maxBytes) {
|
|
405
|
+
await reader.cancel().catch(() => {});
|
|
406
|
+
if (overflow === 'refuse') {
|
|
407
|
+
throw new GuardError('too_large', `The response is larger than ${maxBytes / 1024 / 1024} MB.`);
|
|
408
|
+
}
|
|
409
|
+
chunks.push(value.subarray(0, maxBytes - size));
|
|
410
|
+
size = maxBytes;
|
|
411
|
+
truncated = true;
|
|
412
|
+
break;
|
|
413
|
+
}
|
|
414
|
+
size += value.byteLength;
|
|
415
|
+
chunks.push(value);
|
|
416
|
+
}
|
|
417
|
+
} catch (err) {
|
|
418
|
+
if (err instanceof GuardError) throw err;
|
|
419
|
+
if (signal.aborted) throw new GuardError('timeout', 'The site took too long to answer.');
|
|
420
|
+
throw new GuardError('fetch_failed', 'The response was cut off.');
|
|
421
|
+
}
|
|
422
|
+
const out = new Uint8Array(size);
|
|
423
|
+
let offset = 0;
|
|
424
|
+
for (const c of chunks) {
|
|
425
|
+
out.set(c, offset);
|
|
426
|
+
offset += c.byteLength;
|
|
427
|
+
}
|
|
428
|
+
return { body: out, truncated };
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Drop a response body without reading it, so the connection is freed.
|
|
433
|
+
* @param {Response} res
|
|
434
|
+
*/
|
|
435
|
+
async function discard(res) {
|
|
436
|
+
try {
|
|
437
|
+
await res.body?.cancel();
|
|
438
|
+
} catch {
|
|
439
|
+
// nothing to free
|
|
440
|
+
}
|
|
441
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Worker's entry: /mcp is the chat-app MCP server (mcp-http.js); everything else is the check's
|
|
3
|
+
* fetch endpoint (worker.js). The check page's static files are served by Workers assets before this runs.
|
|
4
|
+
*/
|
|
5
|
+
import { handle } from './worker.js';
|
|
6
|
+
import { handleMcp, MCP_PATH } from './mcp-http.js';
|
|
7
|
+
|
|
8
|
+
export default {
|
|
9
|
+
/**
|
|
10
|
+
* @param {Request} request
|
|
11
|
+
* @param {any} env
|
|
12
|
+
* @param {{waitUntil?: (p: Promise<unknown>) => void}} [ctx]
|
|
13
|
+
*/
|
|
14
|
+
fetch(request, env, ctx) {
|
|
15
|
+
if (new URL(request.url).pathname === MCP_PATH) return handleMcp(request, env);
|
|
16
|
+
return handle(request, env, ctx);
|
|
17
|
+
},
|
|
18
|
+
};
|