@parcha/agentrun-computer 0.0.0-placeholder → 0.1.0-beta.32

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.
Files changed (173) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +8 -0
  3. package/README.md +2400 -1
  4. package/box/Dockerfile +69 -0
  5. package/box/agentrun-archil +168 -0
  6. package/box/build-daytona.py +26 -0
  7. package/box/build-e2b.mjs +32 -0
  8. package/box/build-modal.py +17 -0
  9. package/dist/actions.d.ts +18 -0
  10. package/dist/actions.js +139 -0
  11. package/dist/browser.d.ts +151 -0
  12. package/dist/browser.js +305 -0
  13. package/dist/browserbase.d.ts +139 -0
  14. package/dist/browserbase.js +408 -0
  15. package/dist/child.d.ts +40 -0
  16. package/dist/child.js +127 -0
  17. package/dist/client.d.ts +22 -0
  18. package/dist/client.js +136 -0
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/conformance/archil.d.ts +68 -0
  22. package/dist/conformance/archil.js +152 -0
  23. package/dist/conformance/browserbase.d.ts +35 -0
  24. package/dist/conformance/browserbase.js +45 -0
  25. package/dist/conformance/cases/apps.d.ts +2 -0
  26. package/dist/conformance/cases/apps.js +155 -0
  27. package/dist/conformance/cases/browser.d.ts +4 -0
  28. package/dist/conformance/cases/browser.js +105 -0
  29. package/dist/conformance/cases/drift.d.ts +2 -0
  30. package/dist/conformance/cases/drift.js +64 -0
  31. package/dist/conformance/cases/exec.d.ts +2 -0
  32. package/dist/conformance/cases/exec.js +125 -0
  33. package/dist/conformance/cases/files.d.ts +2 -0
  34. package/dist/conformance/cases/files.js +294 -0
  35. package/dist/conformance/cases/health.d.ts +2 -0
  36. package/dist/conformance/cases/health.js +71 -0
  37. package/dist/conformance/cases/index.d.ts +9 -0
  38. package/dist/conformance/cases/index.js +37 -0
  39. package/dist/conformance/cases/input.d.ts +12 -0
  40. package/dist/conformance/cases/input.js +109 -0
  41. package/dist/conformance/cases/isolation.d.ts +21 -0
  42. package/dist/conformance/cases/isolation.js +92 -0
  43. package/dist/conformance/cases/lifetime.d.ts +2 -0
  44. package/dist/conformance/cases/lifetime.js +64 -0
  45. package/dist/conformance/cases/mount.d.ts +2 -0
  46. package/dist/conformance/cases/mount.js +252 -0
  47. package/dist/conformance/cases/process.d.ts +2 -0
  48. package/dist/conformance/cases/process.js +240 -0
  49. package/dist/conformance/cases/provider.d.ts +2 -0
  50. package/dist/conformance/cases/provider.js +302 -0
  51. package/dist/conformance/cases/screen.d.ts +9 -0
  52. package/dist/conformance/cases/screen.js +230 -0
  53. package/dist/conformance/cases/settings.d.ts +57 -0
  54. package/dist/conformance/cases/settings.js +142 -0
  55. package/dist/conformance/cases/touch.d.ts +2 -0
  56. package/dist/conformance/cases/touch.js +117 -0
  57. package/dist/conformance/cases/util.d.ts +7 -0
  58. package/dist/conformance/cases/util.js +8 -0
  59. package/dist/conformance/cdp.d.ts +13 -0
  60. package/dist/conformance/cdp.js +88 -0
  61. package/dist/conformance/cli.d.ts +29 -0
  62. package/dist/conformance/cli.js +231 -0
  63. package/dist/conformance/daytona-sweep.d.ts +18 -0
  64. package/dist/conformance/daytona-sweep.js +118 -0
  65. package/dist/conformance/daytona.d.ts +83 -0
  66. package/dist/conformance/daytona.js +107 -0
  67. package/dist/conformance/docker.d.ts +38 -0
  68. package/dist/conformance/docker.js +70 -0
  69. package/dist/conformance/drift-daemon.d.ts +8 -0
  70. package/dist/conformance/drift-daemon.js +41 -0
  71. package/dist/conformance/e2b-diagnose.d.ts +16 -0
  72. package/dist/conformance/e2b-diagnose.js +61 -0
  73. package/dist/conformance/e2b-sweep.d.ts +18 -0
  74. package/dist/conformance/e2b-sweep.js +125 -0
  75. package/dist/conformance/e2b.d.ts +74 -0
  76. package/dist/conformance/e2b.js +111 -0
  77. package/dist/conformance/fixture.d.ts +65 -0
  78. package/dist/conformance/fixture.js +98 -0
  79. package/dist/conformance/index.d.ts +8 -0
  80. package/dist/conformance/index.js +8 -0
  81. package/dist/conformance/kernel.d.ts +31 -0
  82. package/dist/conformance/kernel.js +40 -0
  83. package/dist/conformance/kind.d.ts +23 -0
  84. package/dist/conformance/kind.js +58 -0
  85. package/dist/conformance/modal-sweep.d.ts +22 -0
  86. package/dist/conformance/modal-sweep.js +190 -0
  87. package/dist/conformance/modal.d.ts +69 -0
  88. package/dist/conformance/modal.js +76 -0
  89. package/dist/conformance/orgo.d.ts +41 -0
  90. package/dist/conformance/orgo.js +69 -0
  91. package/dist/conformance/phone-harness.d.ts +61 -0
  92. package/dist/conformance/phone-harness.js +241 -0
  93. package/dist/conformance/png.d.ts +16 -0
  94. package/dist/conformance/png.js +132 -0
  95. package/dist/conformance/report.d.ts +2 -0
  96. package/dist/conformance/report.js +86 -0
  97. package/dist/conformance/runner.d.ts +11 -0
  98. package/dist/conformance/runner.js +585 -0
  99. package/dist/conformance/tar.d.ts +13 -0
  100. package/dist/conformance/tar.js +105 -0
  101. package/dist/conformance/types.d.ts +257 -0
  102. package/dist/conformance/types.js +24 -0
  103. package/dist/daemon-copy.d.ts +40 -0
  104. package/dist/daemon-copy.js +259 -0
  105. package/dist/daytona.d.ts +178 -0
  106. package/dist/daytona.js +1484 -0
  107. package/dist/desktop.d.ts +24 -0
  108. package/dist/desktop.js +68 -0
  109. package/dist/docker/egress-main.d.ts +1 -0
  110. package/dist/docker/egress-main.js +68 -0
  111. package/dist/docker/egress-proxy.d.ts +53 -0
  112. package/dist/docker/egress-proxy.js +450 -0
  113. package/dist/docker/egress-table.d.ts +39 -0
  114. package/dist/docker/egress-table.js +197 -0
  115. package/dist/docker/egress.d.ts +109 -0
  116. package/dist/docker/egress.js +318 -0
  117. package/dist/docker/image.d.ts +49 -0
  118. package/dist/docker/image.js +302 -0
  119. package/dist/docker/stage.d.ts +21 -0
  120. package/dist/docker/stage.js +290 -0
  121. package/dist/docker/volume.d.ts +24 -0
  122. package/dist/docker/volume.js +67 -0
  123. package/dist/docker.d.ts +150 -0
  124. package/dist/docker.js +1200 -0
  125. package/dist/drift.d.ts +200 -0
  126. package/dist/drift.js +416 -0
  127. package/dist/e2b.d.ts +335 -0
  128. package/dist/e2b.js +1515 -0
  129. package/dist/entry.d.ts +2 -0
  130. package/dist/entry.js +24 -0
  131. package/dist/files.d.ts +50 -0
  132. package/dist/files.js +208 -0
  133. package/dist/index.d.ts +27 -0
  134. package/dist/index.js +26 -0
  135. package/dist/isolation.d.ts +29 -0
  136. package/dist/isolation.js +71 -0
  137. package/dist/janitor.d.ts +50 -0
  138. package/dist/janitor.js +135 -0
  139. package/dist/kernel.d.ts +113 -0
  140. package/dist/kernel.js +358 -0
  141. package/dist/kinds.d.ts +79 -0
  142. package/dist/kinds.js +133 -0
  143. package/dist/labels.d.ts +23 -0
  144. package/dist/labels.js +50 -0
  145. package/dist/modal.d.ts +302 -0
  146. package/dist/modal.js +1374 -0
  147. package/dist/mount-archil.d.ts +164 -0
  148. package/dist/mount-archil.js +471 -0
  149. package/dist/mount.d.ts +57 -0
  150. package/dist/mount.js +104 -0
  151. package/dist/orgo-channel.d.ts +96 -0
  152. package/dist/orgo-channel.js +391 -0
  153. package/dist/orgo.d.ts +139 -0
  154. package/dist/orgo.js +1006 -0
  155. package/dist/phone-harness.d.ts +185 -0
  156. package/dist/phone-harness.js +1420 -0
  157. package/dist/processes.d.ts +24 -0
  158. package/dist/processes.js +40 -0
  159. package/dist/protocol.d.ts +729 -0
  160. package/dist/protocol.js +54 -0
  161. package/dist/provider.d.ts +245 -0
  162. package/dist/provider.js +37 -0
  163. package/dist/providers.d.ts +68 -0
  164. package/dist/providers.js +25 -0
  165. package/dist/result.d.ts +15 -0
  166. package/dist/result.js +2 -0
  167. package/dist/screen-watch.d.ts +150 -0
  168. package/dist/screen-watch.js +490 -0
  169. package/dist/test-connection.d.ts +17 -0
  170. package/dist/test-connection.js +26 -0
  171. package/dist/wait.d.ts +23 -0
  172. package/dist/wait.js +65 -0
  173. package/package.json +64 -1
@@ -0,0 +1,450 @@
1
+ // A Docker computer's egress proxy, written for AgentRun: the one way out of a computer whose network namespace has only
2
+ // its own loopback. Moved from serve's egress-proxy.ts; the CIDR entries a list may hold are new here. It runs in the
3
+ // computer's own proxy container (egress-main.ts, egress.ts), listens on a Unix socket (0600) in a volume only that
4
+ // container and its computer mount, and speaks HTTP CONNECT, plain HTTP forwarding and SOCKS5 CONNECT (told apart by the
5
+ // first byte), each to the public internet only (egress-table.ts):
6
+ // - a host is resolved once, every address in the answer is checked, and the connection goes to exactly the address
7
+ // that was checked, so a name cannot point elsewhere between the check and the dial; an IP literal is checked the
8
+ // same way, by its bytes, whatever form the client wrote it in;
9
+ // - a refusal is an answer, sent before any socket opens: 403 (or SOCKS reply 2) with the class in its reason;
10
+ // - plain HTTP goes to the request URI's host, and a Host header that names another host is refused (400);
11
+ // - a redirect is never followed here: it reaches the client as the origin sent it, and the client's next request is
12
+ // one more request through this proxy, checked the same way;
13
+ // - SOCKS5 BIND and UDP ASSOCIATE are refused by name, and so is an HTTP upgrade;
14
+ // - a computer has a cap on connections open at once and a budget of connections in all, each refused by name;
15
+ // - a log line holds the host, the port, the address and the class, never a path, a query, a header or a body;
16
+ // - with a list (`allow`), a host off it and any port but 80 and 443 are refused before any lookup, so a name off the
17
+ // list never leaves the host (no DNS channel out); an IP literal is reached only inside a CIDR on the list, of its
18
+ // own family, and a CIDR never admits a name. A listed name or address then meets the address rule as any other does.
19
+ // It holds no key. `close()` ends every connection and removes the socket. It imports only node: modules and the table:
20
+ // the proxy container runs it in a bare Node image.
21
+ import { randomBytes } from "node:crypto";
22
+ import { lookup as dnsLookup } from "node:dns";
23
+ import { chmod, link, lstat, unlink } from "node:fs/promises";
24
+ import { createServer as createHttpServer, request as httpRequest } from "node:http";
25
+ import { connect as netConnect, createServer } from "node:net";
26
+ import { networkInterfaces } from "node:os";
27
+ import { dirname, join } from "node:path";
28
+ import { addressBytes, checkAddress, cidrOf, inCidr } from "./egress-table.js";
29
+ /** A list's name entry: a name of two labels or more, or `*.` and such a name. */
30
+ const ENTRY = /^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$/;
31
+ /** What an entry that is neither a name nor a CIDR is told. */
32
+ const NEITHER = "is not a name with at least two labels, or *. and one, and not a CIDR (an IPv4 address in four decimal parts or an IPv6 address, then / and a prefix length its family holds)";
33
+ /**
34
+ * A list from its entries, or a comma list of them: each lowercased, a name's trailing dot dropped, the repeats gone.
35
+ * An entry is a name of two labels or more, `*.` and one, or a CIDR (cidrOf: its host bits zero, over no range the
36
+ * address rule refuses). Throws in words, naming the entry, for anything else: an address with no prefix, a port, a URL,
37
+ * a bare `*`.
38
+ */
39
+ export function parseAllow(entries) {
40
+ const list = (typeof entries === "string" ? entries.split(/[\s,]+/) : entries).map((entry) => entry.trim()).filter((entry) => entry !== "");
41
+ const out = [];
42
+ for (const entry of list) {
43
+ const lower = entry.toLowerCase();
44
+ let name;
45
+ if (lower.includes("/")) {
46
+ const cidr = cidrOf(lower);
47
+ if (typeof cidr === "string")
48
+ throw new Error(`the network list's entry ${JSON.stringify(entry)} ${cidr}`);
49
+ if (cidr === undefined)
50
+ throw new Error(`the network list's entry ${JSON.stringify(entry)} ${NEITHER}`);
51
+ name = lower;
52
+ }
53
+ else {
54
+ name = lower.replace(/\.$/, "");
55
+ if (!ENTRY.test(name) || addressBytes(name.replace(/^\*\./, "")) !== undefined)
56
+ throw new Error(`the network list's entry ${JSON.stringify(entry)} ${NEITHER}`);
57
+ }
58
+ if (!out.includes(name))
59
+ out.push(name);
60
+ }
61
+ return out;
62
+ }
63
+ /** Whether `host` (a name) is on `names`: an exact name, or below a `*.suffix`; in any case, and without a trailing dot. */
64
+ const listedHost = (names, host) => {
65
+ const name = host.toLowerCase().replace(/\.$/, "");
66
+ return names.some((entry) => (entry.startsWith("*.") ? name.endsWith(entry.slice(1)) && name.length > entry.length - 1 : name === entry));
67
+ };
68
+ /** The ports a list opens: plain HTTP and HTTPS. */
69
+ export const LISTED_PORTS = [80, 443];
70
+ /** What the proxy container's entry (egress-main.ts) logs once its socket listens: the provider waits for it. */
71
+ export const EGRESS_READY = "egress ready";
72
+ const HOP = new Set(["connection", "proxy-connection", "keep-alive", "proxy-authorization", "proxy-authenticate", "te", "trailer", "upgrade", "transfer-encoding"]);
73
+ /** The headers that stay on this hop: the fixed hop-by-hop names, and every name a Connection header lists. */
74
+ function hopHeaders(headers) {
75
+ const listed = [headers.connection ?? []]
76
+ .flat()
77
+ .flatMap((value) => String(value).split(","))
78
+ .map((name) => name.trim().toLowerCase())
79
+ .filter(Boolean);
80
+ return new Set([...HOP, ...listed]);
81
+ }
82
+ /** The canonical text of an address's bytes: what is dialled. */
83
+ function addressText(bytes) {
84
+ if (bytes.length === 4)
85
+ return [...bytes].join(".");
86
+ const groups = [];
87
+ for (let i = 0; i < 16; i += 2)
88
+ groups.push(((bytes[i] << 8) | bytes[i + 1]).toString(16));
89
+ return groups.join(":");
90
+ }
91
+ const hostOf = (text) => JSON.stringify(text.slice(0, 255));
92
+ export async function startEgressProxy(options) {
93
+ const { socketPath, maxTunnels, maxConnections, log } = options;
94
+ const allow = options.allow === undefined ? undefined : parseAllow(options.allow);
95
+ const names = (allow ?? []).filter((entry) => !entry.includes("/"));
96
+ const cidrs = (allow ?? []).filter((entry) => entry.includes("/")).map((entry) => cidrOf(entry));
97
+ // The hint goes into a status line, which carries printable ASCII only: Node refuses anything else there (an em dash
98
+ // included), and a control character would end the line.
99
+ if (options.allowHint !== undefined && !/^[\x20-\x7e]*$/.test(options.allowHint))
100
+ throw new Error("the egress proxy's allowHint holds a character a status line cannot carry: printable ASCII only");
101
+ const hinted = (words) => (options.allowHint ? `${words}: ${options.allowHint}` : words);
102
+ /** The refusal of a target off the list, or undefined: checked before any lookup. */
103
+ const offList = (host, port) => {
104
+ if (allow === undefined)
105
+ return undefined;
106
+ // A phrase holds only a plain host: anything else is named as such.
107
+ const shown = /^[A-Za-z0-9._:-]+$/.test(host) ? host : "the host";
108
+ const literal = addressBytes(host);
109
+ const words = literal !== undefined && cidrs.length === 0
110
+ ? hinted(`${shown} is an address, not a name on this box's network list`)
111
+ : literal !== undefined
112
+ ? !cidrs.some((cidr) => inCidr(literal, cidr))
113
+ ? hinted(`${shown} is not on this box's network list`)
114
+ : undefined
115
+ : !listedHost(names, host)
116
+ ? hinted(`${shown} is not on this box's network list`)
117
+ : undefined;
118
+ const portWords = words === undefined && !LISTED_PORTS.includes(port) ? `${shown}:${port} is not open on this box's network list, which takes ports 80 and 443 only` : undefined;
119
+ const said = words ?? portWords;
120
+ return said === undefined ? undefined : { status: 403, reason: "not-listed", socks: 2, words: said };
121
+ };
122
+ const lookup = options.lookup ?? ((hostname, opts, callback) => dnsLookup(hostname, opts, callback));
123
+ const dial = options.dial ?? ((address, port) => netConnect({ host: address, port }));
124
+ const sockets = new Set();
125
+ let open = 0;
126
+ let used = 0;
127
+ let closed = false;
128
+ const track = (socket) => {
129
+ sockets.add(socket);
130
+ socket.once("close", () => sockets.delete(socket));
131
+ if (closed)
132
+ socket.destroy();
133
+ };
134
+ /** The host's addresses at this moment: every interface's, and the seam's. */
135
+ const local = () => [...Object.values(networkInterfaces()).flatMap((list) => (list ?? []).map((entry) => entry.address)), ...(options.alsoLocal?.() ?? [])];
136
+ /** Resolves `host` once and checks every answer: the address to dial, or the refusal. */
137
+ const resolve = async (host) => {
138
+ const literal = addressBytes(host);
139
+ let answers;
140
+ if (literal)
141
+ answers = [literal];
142
+ else {
143
+ if (!/^[A-Za-z0-9._-]+$/.test(host) || host.length > 253)
144
+ return { refused: { status: 400, reason: "invalid host", socks: 4 } };
145
+ try {
146
+ const found = await new Promise((ok, fail) => lookup(host, { all: true, verbatim: true }, (error, list) => (error ? fail(error) : ok(list))));
147
+ answers = found.map((entry) => addressBytes(entry.address)).filter((bytes) => bytes !== undefined);
148
+ }
149
+ catch {
150
+ return { refused: { status: 502, reason: "name not resolved", socks: 4 } };
151
+ }
152
+ if (answers.length === 0)
153
+ return { refused: { status: 502, reason: "name not resolved", socks: 4 } };
154
+ }
155
+ const here = local();
156
+ for (const bytes of answers) {
157
+ const verdict = checkAddress(bytes, here);
158
+ if (!verdict.ok)
159
+ return { refused: { status: 403, reason: verdict.class, socks: 2 }, address: addressText(bytes) };
160
+ }
161
+ return { address: addressText(answers[0]) };
162
+ };
163
+ /** A connection may open now: the cap and the budget. Takes a slot; `release` gives it back. */
164
+ const admit = () => {
165
+ if (open >= maxTunnels)
166
+ return { status: 429, reason: "tunnel cap", socks: 2 };
167
+ if (used >= maxConnections)
168
+ return { status: 429, reason: "connection budget", socks: 2 };
169
+ open++;
170
+ used++;
171
+ return undefined;
172
+ };
173
+ /** Resolve, check, admit and dial: the upstream socket once it connects, or the refusal. */
174
+ const reach = async (kind, host, port) => {
175
+ const unlisted = offList(host, port);
176
+ if (unlisted) {
177
+ log(`egress ${kind} host=${hostOf(host)} port=${port} ip=- class=${unlisted.reason}`);
178
+ return { refused: unlisted };
179
+ }
180
+ const target = await resolve(host);
181
+ if ("refused" in target) {
182
+ log(`egress ${kind} host=${hostOf(host)} port=${port} ip=${target.address ?? "-"} class=${target.refused.reason}`);
183
+ return target;
184
+ }
185
+ const full = admit();
186
+ if (full) {
187
+ log(`egress ${kind} host=${hostOf(host)} port=${port} ip=${target.address} class=${full.reason}`);
188
+ return { refused: full };
189
+ }
190
+ log(`egress ${kind} host=${hostOf(host)} port=${port} ip=${target.address} class=ok`);
191
+ const upstream = dial(target.address, port);
192
+ track(upstream);
193
+ upstream.once("close", () => open--);
194
+ return await new Promise((ok) => {
195
+ upstream.once("connect", () => ok({ socket: upstream, address: target.address }));
196
+ upstream.once("error", () => ok({ refused: { status: 502, reason: "dial failed", socks: 5 } }));
197
+ });
198
+ };
199
+ // HTTP: CONNECT, and plain requests in absolute form.
200
+ const http = createHttpServer();
201
+ const refuseRaw = (socket, refusal) => {
202
+ const body = `${refusal.words ?? `egress refused: ${refusal.reason}`}\n`;
203
+ socket.end(`HTTP/1.1 ${refusal.status} ${refusal.words ?? `Egress refused: ${refusal.reason}`}\r\nx-egress-refused: ${refusal.reason}\r\ncontent-type: text/plain\r\ncontent-length: ${Buffer.byteLength(body)}\r\nconnection: close\r\n\r\n${body}`);
204
+ };
205
+ const refuse = (res, refusal) => {
206
+ const body = `${refusal.words ?? `egress refused: ${refusal.reason}`}\n`;
207
+ res.writeHead(refusal.status, refusal.words ?? `Egress refused: ${refusal.reason}`, {
208
+ "x-egress-refused": refusal.reason,
209
+ "content-type": "text/plain",
210
+ "content-length": Buffer.byteLength(body),
211
+ connection: "close",
212
+ });
213
+ res.end(body);
214
+ };
215
+ http.on("connect", (req, client, head) => {
216
+ void (async () => {
217
+ const target = /^\[([0-9A-Fa-f:.%a-zA-Z]+)\]:(\d{1,5})$/.exec(req.url ?? "") ?? /^([^:[\]/@\s]+):(\d{1,5})$/.exec(req.url ?? "");
218
+ const port = Number(target?.[2]);
219
+ if (!target || !(port >= 1 && port <= 65535))
220
+ return refuseRaw(client, { status: 400, reason: "invalid target", socks: 1 });
221
+ const reached = await reach("connect", target[1], port);
222
+ if ("refused" in reached)
223
+ return refuseRaw(client, reached.refused);
224
+ // A client that left during the lookup or the dial gets no tunnel: its socket goes, and so does its slot.
225
+ if (client.destroyed)
226
+ return void reached.socket.destroy();
227
+ client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
228
+ if (head.length)
229
+ reached.socket.write(head);
230
+ reached.socket.pipe(client).pipe(reached.socket);
231
+ reached.socket.on("error", () => client.destroy());
232
+ client.on("error", () => reached.socket.destroy());
233
+ reached.socket.on("close", () => client.destroy());
234
+ client.on("close", () => reached.socket.destroy());
235
+ })();
236
+ });
237
+ http.on("upgrade", (_req, client) => refuseRaw(client, { status: 400, reason: "upgrade not supported", socks: 7 }));
238
+ http.on("request", (req, res) => {
239
+ // Watched from the start: a client that leaves during the lookup or the dial is gone before any listener below exists.
240
+ let gone = false;
241
+ res.once("close", () => (gone = true));
242
+ void (async () => {
243
+ let url;
244
+ try {
245
+ url = new URL(req.url ?? "");
246
+ }
247
+ catch {
248
+ return refuse(res, { status: 400, reason: "not an absolute URI", socks: 1 });
249
+ }
250
+ if (url.protocol !== "http:")
251
+ return refuse(res, { status: 400, reason: "not an http URI", socks: 1 });
252
+ const host = url.hostname.replace(/^\[|\]$/g, "");
253
+ const port = url.port === "" ? 80 : Number(url.port);
254
+ if (req.headers.host !== undefined) {
255
+ let named;
256
+ try {
257
+ named = new URL(`http://${req.headers.host}`);
258
+ }
259
+ catch { }
260
+ if (!named || named.hostname !== url.hostname || (named.port === "" ? 80 : Number(named.port)) !== port) {
261
+ log(`egress http host=${hostOf(host)} port=${port} ip=- class=host mismatch`);
262
+ return refuse(res, { status: 400, reason: "host mismatch", socks: 1 });
263
+ }
264
+ }
265
+ const reached = await reach("http", host, port);
266
+ if ("refused" in reached)
267
+ return refuse(res, reached.refused);
268
+ if (gone)
269
+ return void reached.socket.destroy();
270
+ const headers = {};
271
+ const hop = hopHeaders(req.headers);
272
+ for (const [name, value] of Object.entries(req.headers))
273
+ if (!hop.has(name))
274
+ headers[name] = value;
275
+ headers.host = url.host;
276
+ headers.connection = "close";
277
+ // The request goes over the socket already dialled to the checked address. Its host and port name that address too,
278
+ // so nothing else is reached even if the socket were not used (with `agent: false`, Node ignores createConnection
279
+ // and dials host and port itself).
280
+ const upstream = httpRequest({ host: reached.address, port, method: req.method, path: `${url.pathname}${url.search}`, headers, createConnection: () => reached.socket });
281
+ upstream.on("response", (answer) => {
282
+ const out = {};
283
+ const back = hopHeaders(answer.headers);
284
+ for (const [name, value] of Object.entries(answer.headers))
285
+ if (!back.has(name) && value !== undefined)
286
+ out[name] = value;
287
+ res.writeHead(answer.statusCode ?? 502, answer.statusMessage, out);
288
+ answer.pipe(res);
289
+ });
290
+ upstream.on("error", () => (res.headersSent ? res.destroy() : refuse(res, { status: 502, reason: "upstream failed", socks: 1 })));
291
+ req.pipe(upstream);
292
+ res.on("close", () => reached.socket.destroy());
293
+ })();
294
+ });
295
+ // SOCKS5: a greeting offering "no authentication", then one CONNECT.
296
+ const socks = (client) => {
297
+ let buffer = Buffer.alloc(0);
298
+ let stage = "greet";
299
+ const reply = (code) => Buffer.from([5, code, 0, 1, 0, 0, 0, 0, 0, 0]);
300
+ const onData = (chunk) => {
301
+ buffer = Buffer.concat([buffer, chunk]);
302
+ if (buffer.length > 1024)
303
+ return client.destroy();
304
+ if (stage === "greet") {
305
+ if (buffer.length < 2 || buffer.length < 2 + buffer[1])
306
+ return;
307
+ const methods = buffer.subarray(2, 2 + buffer[1]);
308
+ buffer = buffer.subarray(2 + buffer[1]);
309
+ if (!methods.includes(0))
310
+ return client.end(Buffer.from([5, 0xff]));
311
+ client.write(Buffer.from([5, 0]));
312
+ stage = "request";
313
+ }
314
+ if (stage !== "request" || buffer.length < 5)
315
+ return;
316
+ const [version, command, , type] = buffer;
317
+ if (version !== 5)
318
+ return client.destroy();
319
+ const length = type === 1 ? 4 : type === 4 ? 16 : type === 3 ? 1 + buffer[4] : -1;
320
+ if (length < 0)
321
+ return client.end(reply(8));
322
+ if (buffer.length < 4 + length + 2)
323
+ return;
324
+ stage = "done";
325
+ client.off("data", onData);
326
+ client.setTimeout(0);
327
+ const raw = buffer.subarray(4, 4 + length);
328
+ const host = type === 3 ? raw.subarray(1).toString("latin1") : addressText(raw);
329
+ const port = buffer.readUInt16BE(4 + length);
330
+ const rest = buffer.subarray(4 + length + 2);
331
+ if (command !== 1) {
332
+ const name = command === 2 ? "socks bind" : command === 3 ? "socks udp associate" : "socks command";
333
+ log(`egress socks host=${hostOf(host)} port=${port} ip=- class=${name}`);
334
+ return client.end(reply(7));
335
+ }
336
+ void (async () => {
337
+ const reached = await reach("socks", host, port);
338
+ if ("refused" in reached)
339
+ return client.end(reply(reached.refused.socks));
340
+ if (client.destroyed)
341
+ return void reached.socket.destroy();
342
+ client.write(reply(0));
343
+ if (rest.length)
344
+ reached.socket.write(rest);
345
+ reached.socket.pipe(client).pipe(reached.socket);
346
+ reached.socket.on("error", () => client.destroy());
347
+ client.on("error", () => reached.socket.destroy());
348
+ reached.socket.on("close", () => client.destroy());
349
+ client.on("close", () => reached.socket.destroy());
350
+ })();
351
+ };
352
+ client.on("data", onData);
353
+ };
354
+ const server = createServer((client) => {
355
+ track(client);
356
+ client.on("error", () => client.destroy());
357
+ client.setTimeout(30_000, () => client.destroy());
358
+ client.once("data", (first) => {
359
+ client.pause();
360
+ client.unshift(first);
361
+ if (first[0] === 5) {
362
+ socks(client);
363
+ client.resume();
364
+ }
365
+ else {
366
+ client.setTimeout(0);
367
+ http.emit("connection", client);
368
+ client.resume();
369
+ }
370
+ });
371
+ });
372
+ // A socket already at the path belongs to another proxy while it answers, and is never taken from it. The socket's
373
+ // directory is local; a connect refused there means nothing listens. So only a socket that refuses a connection is
374
+ // removed; any other failure of the probe (EACCES, say) is thrown and the socket left, and anything that is not a socket
375
+ // is left where it is. Two starts that both find the same dead socket could each remove it in turn, the second after
376
+ // the first has linked its live socket there; that needs two proxies for one computer's volume, which its provider
377
+ // never starts, so nothing here guards it (moving the socket aside to check it would leave a live one briefly missing
378
+ // from its path instead).
379
+ const taken = (code, what) => Object.assign(new Error(`egress proxy: ${socketPath} ${what}`), { code });
380
+ let found;
381
+ try {
382
+ found = await lstat(socketPath);
383
+ }
384
+ catch (error) {
385
+ if (error.code !== "ENOENT")
386
+ throw error;
387
+ }
388
+ if (found) {
389
+ if (!found.isSocket())
390
+ throw taken("egress_socket_path_taken", "exists and is not a socket");
391
+ const answer = await new Promise((ok) => {
392
+ const probe = netConnect(socketPath);
393
+ probe.once("connect", () => {
394
+ probe.destroy();
395
+ ok(true);
396
+ });
397
+ probe.once("error", (error) => ok(error));
398
+ });
399
+ if (answer === true)
400
+ throw taken("egress_socket_in_use", "is a live egress proxy's socket");
401
+ if (answer.code !== "ECONNREFUSED")
402
+ throw answer;
403
+ await unlink(socketPath);
404
+ }
405
+ // Made under a name of its own and made 0600 before it gets its path, so it is never reachable there with a wider
406
+ // mode. The path is a hard link, never a rename. Between the check above and this link, another start can put a socket
407
+ // at the path: a link then fails (EEXIST, refused as egress_socket_in_use), where a rename would replace that socket
408
+ // silently. No test can hold that window open, so this comment is its record. The temporary name is removed once linked.
409
+ const making = join(dirname(socketPath), `.egress-${randomBytes(6).toString("hex")}.sock`);
410
+ await new Promise((ok, fail) => {
411
+ server.once("error", fail);
412
+ server.listen(making, () => {
413
+ server.off("error", fail);
414
+ ok();
415
+ });
416
+ });
417
+ try {
418
+ await chmod(making, 0o600);
419
+ await link(making, socketPath);
420
+ }
421
+ catch (error) {
422
+ server.close();
423
+ await unlink(making).catch(() => { });
424
+ if (error.code === "EEXIST")
425
+ throw taken("egress_socket_in_use", "was taken while this proxy started");
426
+ throw error;
427
+ }
428
+ // This socket's inode: close removes the path only while it still holds it, never a socket another start put there.
429
+ const mine = await lstat(making);
430
+ await unlink(making).catch(() => { });
431
+ return {
432
+ socketPath,
433
+ async close() {
434
+ if (closed)
435
+ return;
436
+ closed = true;
437
+ const done = new Promise((ok) => server.close(() => ok()));
438
+ for (const socket of sockets)
439
+ socket.destroy();
440
+ http.close();
441
+ await done;
442
+ const now = await lstat(socketPath).catch((error) => {
443
+ if (error.code !== "ENOENT")
444
+ throw error;
445
+ });
446
+ if (now && now.dev === mine.dev && now.ino === mine.ino)
447
+ await unlink(socketPath);
448
+ },
449
+ };
450
+ }
@@ -0,0 +1,39 @@
1
+ /** Why an address is refused. */
2
+ export type EgressClass = "loopback" | "unspecified" | "private" | "cgnat" | "link-local" | "metadata" | "multicast" | "broadcast" | "reserved" | "benchmarking" | "this-host" | "invalid";
3
+ export type EgressVerdict = {
4
+ ok: true;
5
+ } | {
6
+ ok: false;
7
+ class: EgressClass;
8
+ };
9
+ /** The table's ranges as written, in order: what the no-drift test pins. */
10
+ export declare const EGRESS_RANGES: readonly string[];
11
+ /**
12
+ * An IP address's bytes (4 or 16), or undefined when `text` is not one. Takes what a socket or a URL could carry for a
13
+ * host: a dotted IPv4 address, or the forms the classic resolver reads as one (a single number, 0x hex and 0 octal
14
+ * parts, fewer than four parts with the last filling the rest), and an IPv6 address, bracketed or not, with or without a
15
+ * zone. Never a name.
16
+ */
17
+ export declare function addressBytes(text: string): Uint8Array | undefined;
18
+ /**
19
+ * Whether a computer may reach `address` (its bytes, or an address's text: never a name). `local` is the host's own
20
+ * addresses: an address equal to one of them is refused as "this-host". An IPv6 address that carries an IPv4 one is
21
+ * judged by the IPv4 inside, and is then still the host's own if the host holds that IPv6 address itself (the dial goes
22
+ * to the IPv6 address, not to the IPv4 inside it).
23
+ */
24
+ export declare function checkAddress(address: Uint8Array | string, local: readonly string[]): EgressVerdict;
25
+ /** A CIDR an allowlist holds: its base address's bytes and its prefix length. */
26
+ export interface Cidr {
27
+ bytes: Uint8Array;
28
+ bits: number;
29
+ }
30
+ /**
31
+ * A CIDR entry of an allowlist; or why it is not one, in words, when it reads as one; or undefined when it is not a CIDR
32
+ * at all. A CIDR is an IPv4 address in four decimal parts or an IPv6 address (no zone), then a prefix length its family
33
+ * holds. Its host bits are zero; it overlaps no range the table refuses; and an IPv6 one lies inside global unicast
34
+ * (2000::/3). A CIDR that could name a private or local address is refused here, though the table would refuse each
35
+ * such address at the dial anyway: a list never claims what it cannot reach. Lowercase is the caller's.
36
+ */
37
+ export declare function cidrOf(text: string): Cidr | string | undefined;
38
+ /** Whether `address` lies inside `cidr`: of the same family, IPv4 or IPv6, and with the same prefix. */
39
+ export declare const inCidr: (address: Uint8Array, cidr: Cidr) => boolean;