Repository navigation
Expand file tree
/
Copy pathfetch.ts
More file actions
271 lines (251 loc) · 11.8 KB
/
Copy pathfetch.ts
File metadata and controls
271 lines (251 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
// impl/03 §6, impl/05 §4, TECH-SPEC GP5 (proxy env, SSRF per hop), DECISIONS-r3 Q19, DECISIONS-r4 A8/A52/B57,
// DEVIATIONS D-M2-T5-2. One path: resolve the connect target, check every address, connect to the
// checked address (no second DNS lookup), follow redirects as new hops.
import { readFileSync } from "node:fs";
import { lookup } from "node:dns/promises";
import http from "node:http";
import https from "node:https";
import { BlockList, isIP } from "node:net";
import type { Socket } from "node:net";
import { join } from "node:path";
import { connect as tlsConnect } from "node:tls";
import { D1_PACKAGE_FILE, FETCH_MAX_HOPS } from "../contracts/constants.ts";
import { CtxError } from "../contracts/errors.ts";
import { ownBundleDir } from "../ops/bundle-dir.ts";
// impl/03 §6 step 3 / "Constants used": fixed protocol data, not tunable, written inline.
const PRIVATE_RANGES: ReadonlyArray<readonly [string, number, "ipv4" | "ipv6"]> = [
["127.0.0.0", 8, "ipv4"],
["10.0.0.0", 8, "ipv4"],
["172.16.0.0", 12, "ipv4"],
["192.168.0.0", 16, "ipv4"],
["169.254.0.0", 16, "ipv4"],
["0.0.0.0", 8, "ipv4"], // D-SSRF-RANGES-1: "this network", not only 0.0.0.0
["100.64.0.0", 10, "ipv4"], // D-SSRF-RANGES-1: shared address space (RFC 6598), cloud metadata lives here
["198.18.0.0", 15, "ipv4"], // D-SSRF-RANGES-1: benchmark networks (RFC 2544)
["240.0.0.0", 4, "ipv4"], // D-SSRF-RANGES-1: reserved and broadcast
["::1", 128, "ipv6"],
["::", 128, "ipv6"],
["::", 96, "ipv6"], // D-SSRF-RANGES-1: IPv4-compatible (::a.b.c.d), deprecated, never a public origin
["64:ff9b:1::", 48, "ipv6"], // D-SSRF-RANGES-1: local-use NAT64 (RFC 8215)
["fc00::", 7, "ipv6"],
["fe80::", 10, "ipv6"],
["fec0::", 10, "ipv6"], // D-SSRF-RANGES-1: site-local (RFC 3879)
];
const BLOCKED = new BlockList();
for (const [net, prefix, type] of PRIVATE_RANGES) BLOCKED.addSubnet(net, prefix, type);
// RFC 9110 status classes (fixed protocol data, D-M2-T5-2).
const STATUS_OK_FIRST = 200;
const STATUS_OK_END = 300;
const STATUS_REDIRECT: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);
// D-1380-FETCH-UA-1 (#1380): every request names itself, as v1's undici fetch did (user-agent and accept). Some
// hosts (en.wikipedia.org) answer 403 to a request with no user-agent. The version comes once from the bundle's
// package.json; the dev tree has none, so it is "dev".
const UA_HOME = "https://github.com/mksglu/context-mode";
const UA_DEV_VERSION = "dev";
let namedHeaders: Readonly<Record<string, string>> | undefined;
function baseHeaders(): Readonly<Record<string, string>> {
if (namedHeaders === undefined) {
let version = UA_DEV_VERSION;
try {
const v: unknown = JSON.parse(readFileSync(join(ownBundleDir(), D1_PACKAGE_FILE), "utf8")).version;
if (typeof v === "string" && v !== "") version = v;
} catch {
// no package.json next to the bundle: the dev tree
}
namedHeaders = Object.freeze({ "user-agent": "context-mode/" + version + " (+" + UA_HOME + ")", accept: "*/*" });
}
return namedHeaders;
}
type Target = { host: string; port: number; address: string };
type Proxy = { url: URL; auth: string | undefined };
function fail(code: string | number): CtxError {
return new CtxError("FETCH_FAILED", { code });
}
// Low-level code only: never the message or the stack (#1135, #1172).
function causeCode(err: unknown): string {
if (err instanceof CtxError) return "";
const e = err as { code?: unknown; name?: unknown; errors?: unknown[] } | null;
if (e && typeof e.code === "string" && e.code !== "") return e.code;
if (e && Array.isArray(e.errors) && e.errors.length > 0) return causeCode(e.errors[0]);
if (e && typeof e.name === "string" && e.name !== "") return e.name;
return "UNKNOWN";
}
function bare(hostname: string): string {
return hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
}
// The scheme's default port comes from Node's own agents, not a literal (D-M2-T5-2).
function defaultPort(protocol: string): number {
const agent = (protocol === "https:" ? https.globalAgent : http.globalAgent) as http.Agent & { defaultPort: number };
return agent.defaultPort;
}
function parseUrl(raw: string): URL {
let u: URL;
try {
u = new URL(raw);
} catch (err) {
throw fail(causeCode(err));
}
if (u.protocol !== "http:" && u.protocol !== "https:") throw fail("ERR_INVALID_PROTOCOL");
return u;
}
function envValue(upper: string): string | undefined {
const v = process.env[upper] ?? process.env[upper.toLowerCase()];
return v === undefined || v.trim() === "" ? undefined : v.trim();
}
// Step 1: per-scheme proxy env, upper case first; NO_PROXY exact host or "."-suffix match.
function pickProxy(u: URL): Proxy | undefined {
const raw = envValue(u.protocol === "https:" ? "HTTPS_PROXY" : "HTTP_PROXY");
if (raw === undefined) return undefined;
const host = bare(u.hostname).toLowerCase();
for (const item of (envValue("NO_PROXY") ?? "").split(",")) {
let entry = item.trim().toLowerCase();
if (entry.startsWith(".")) entry = entry.slice(1);
if (entry !== "" && (host === entry || host.endsWith("." + entry))) return undefined;
}
const p = parseUrl(raw.includes("://") ? raw : "http://" + raw);
if (p.protocol !== "http:") throw fail("ERR_INVALID_PROTOCOL");
const auth = p.username === "" ? undefined
: "Basic " + Buffer.from(decodeURIComponent(p.username) + ":" + decodeURIComponent(p.password)).toString("base64");
return { url: p, auth };
}
// The eight 16-bit words of an IPv6 address (a zone id after "%" is dropped; a dotted tail gives two words).
function ipv6Words(address: string): number[] {
const zone = address.indexOf("%");
const a = zone < 0 ? address : address.slice(0, zone);
const words = (part: string): number[] => {
if (part === "") return [];
const out: number[] = [];
for (const w of part.split(":")) {
if (w.includes(".")) {
const q = w.split(".").map(Number) as [number, number, number, number];
out.push(q[0] * 256 + q[1], q[2] * 256 + q[3]);
} else out.push(parseInt(w, 16));
}
return out;
};
const gap = a.indexOf("::");
if (gap < 0) return words(a);
const head = words(a.slice(0, gap));
const tail = words(a.slice(gap + 2));
return [...head, ...new Array<number>(8 - head.length - tail.length).fill(0), ...tail];
}
function dotted(hi: number, lo: number): string {
return [hi >> 8, hi & 255, lo >> 8, lo & 255].join(".");
}
// D-SSRF-RANGES-1: the IPv4 address a NAT64 (64:ff9b::/96) or 6to4 (2002::/16) address carries, else undefined.
function embeddedIpv4(address: string): string | undefined {
const w = ipv6Words(address);
if (w[0] === 0x64 && w[1] === 0xff9b && w[2] === 0 && w[3] === 0 && w[4] === 0 && w[5] === 0) {
return dotted(w[6] as number, w[7] as number);
}
if (w[0] === 0x2002) return dotted(w[1] as number, w[2] as number);
return undefined;
}
function checkAddress(hostname: string, address: string): void {
const family = isIP(address);
const inner = family === 6 ? embeddedIpv4(address) : undefined;
if (family === 0 || BLOCKED.check(address, family === 4 ? "ipv4" : "ipv6") || (inner !== undefined && BLOCKED.check(inner, "ipv4"))) {
throw new CtxError("SSRF", { host: hostname });
}
}
// Steps 2-3: resolve in this process, reject if any address is private; return the checked address.
async function resolveTarget(u: URL, signal: AbortSignal): Promise<Target> {
const host = bare(u.hostname);
let addrs: { address: string }[];
try {
addrs = await lookup(host, { all: true });
} catch (err) {
throw fail(causeCode(err));
}
if (signal.aborted) throw fail("ABORT_ERR");
if (addrs.length === 0) throw fail("ENOTFOUND");
for (const a of addrs) checkAddress(host, a.address);
return { host, port: u.port === "" ? defaultPort(u.protocol) : Number(u.port), address: addrs[0].address };
}
function tlsName(host: string): string | undefined {
return isIP(host) === 0 ? host : undefined;
}
// Step 4: one request on the checked address; through the proxy when one was picked.
function request(u: URL, conn: Target, proxy: Proxy | undefined, signal: AbortSignal): Promise<http.IncomingMessage> {
const host = bare(u.hostname);
const port = u.port === "" ? defaultPort(u.protocol) : Number(u.port);
const path = u.pathname + u.search;
return new Promise((resolve, reject) => {
const onErr = (err: unknown) => reject(fail(causeCode(err)));
if (proxy === undefined) {
const mod = u.protocol === "https:" ? https : http;
const req = mod.request({ host: conn.address, port, path, signal, servername: tlsName(host), headers: { ...baseHeaders(), host: u.host } });
req.on("response", resolve).on("error", onErr).end();
return;
}
const proxyHeaders: Record<string, string> = proxy.auth === undefined ? { ...baseHeaders() }
: { ...baseHeaders(), "proxy-authorization": proxy.auth };
if (u.protocol === "http:") {
const req = http.request({ host: conn.address, port: conn.port, path: u.href, signal, headers: { host: u.host, ...proxyHeaders } });
req.on("response", resolve).on("error", onErr).end();
return;
}
const authority = (isIP(host) === 6 ? "[" + host + "]" : host) + ":" + port;
const tunnel = http.request({ host: conn.address, port: conn.port, method: "CONNECT", path: authority, signal, headers: { host: authority, ...proxyHeaders } });
tunnel.on("error", onErr);
tunnel.on("connect", (res: http.IncomingMessage, socket: Socket) => {
if (res.statusCode !== STATUS_OK_FIRST) {
socket.destroy();
reject(fail(res.statusCode ?? "ERR_PROXY_CONNECT"));
return;
}
const req = https.request({
host, port, path, signal, headers: { ...baseHeaders(), host: u.host },
createConnection: () => tlsConnect({ socket, host, servername: tlsName(host) }),
});
req.on("response", resolve).on("error", onErr).end();
});
tunnel.end();
});
}
function readBody(res: http.IncomingMessage): Promise<Buffer> {
return new Promise((resolve, reject) => {
const parts: Buffer[] = [];
res.on("data", (b: Buffer) => parts.push(b));
res.on("end", () => resolve(Buffer.concat(parts)));
res.on("error", (err) => reject(fail(causeCode(err))));
res.on("aborted", () => reject(fail("ECONNRESET")));
});
}
export async function safeFetch(url: string, signal: AbortSignal): Promise<{ body: Buffer; contentType: string; finalUrl: string }> {
let current = parseUrl(url);
for (let hop = 0; ; hop += 1) {
if (signal.aborted) throw fail("ABORT_ERR");
const proxy = pickProxy(current);
// D-M2-T5-2: through a proxy the proxy resolves the origin name; an IP-literal origin is still checked here.
const origin = bare(current.hostname);
if (proxy !== undefined && isIP(origin) !== 0) checkAddress(origin, origin);
const conn = await resolveTarget(proxy === undefined ? current : proxy.url, signal);
const res = await request(current, conn, proxy, signal);
const status = res.statusCode ?? 0;
const location = res.headers.location;
if (STATUS_REDIRECT.has(status) && location !== undefined) {
res.resume();
if (hop >= FETCH_MAX_HOPS) throw fail("ERR_TOO_MANY_REDIRECTS");
let next: URL;
try {
next = new URL(location, current);
} catch (err) {
throw fail(causeCode(err));
}
current = parseUrl(next.href);
continue;
}
if (status < STATUS_OK_FIRST || status >= STATUS_OK_END) {
res.resume();
// D-1380-FETCH-UA-1: name the host that refused, so the user knows which hop failed.
throw fail(status + " from " + bare(current.hostname));
}
const body = await readBody(res);
// finalUrl labels the indexed source and is echoed in replies: never carry userinfo (a secret).
const shown = new URL(current.href);
shown.username = "";
shown.password = "";
return { body, contentType: res.headers["content-type"] ?? "", finalUrl: shown.href };
}
}