@mnaimfaizy/agent-kit 1.0.0-beta.1 → 1.0.0-beta.11

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,150 @@
1
+ // The setup phase's egress gate (#369): an HTTP proxy that runs in the
2
+ // launcher, on the host, outside the sandbox, and forwards only to the Scan
3
+ // recipe's `registries`. The sandbox sits on a Docker network with no route
4
+ // out (`--internal`), and reaches this proxy only through a relay, so the
5
+ // proxy is its only way to the internet during setup; the network is cut
6
+ // before the agent step. Node core only.
7
+
8
+ import { createServer, request } from "node:http";
9
+ import { connect } from "node:net";
10
+
11
+ /**
12
+ * Each registry as the host and ports it allows: a bare host name allows
13
+ * ports 80 and 443; a URL or `host:port` allows the port it names (or its
14
+ * scheme's default).
15
+ * @param {string[]} registries
16
+ * @returns {Map<string, Set<number>>}
17
+ */
18
+ export function allowlistOf(registries) {
19
+ const allowed = new Map();
20
+ for (const entry of registries) {
21
+ let host;
22
+ let ports;
23
+ try {
24
+ const url = new URL(entry.includes("://") ? entry : `none://${entry}`);
25
+ host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
26
+ if (url.port) ports = [Number(url.port)];
27
+ else if (url.protocol === "http:") ports = [80];
28
+ else if (url.protocol === "https:") ports = [443];
29
+ else ports = [80, 443];
30
+ } catch {
31
+ continue;
32
+ }
33
+ if (!host) continue;
34
+ const set = allowed.get(host) ?? new Set();
35
+ for (const p of ports) set.add(p);
36
+ allowed.set(host, set);
37
+ }
38
+ return allowed;
39
+ }
40
+
41
+ // Hop-by-hop headers (RFC 9110 7.6.1) and the client's proxy headers, which
42
+ // go no further than this proxy, and the client's Host: the upstream gets
43
+ // the allowed URL's host, so a shared front end cannot route by another.
44
+ const DROPPED = new Set([
45
+ "host",
46
+ "proxy-authorization",
47
+ "proxy-authenticate",
48
+ "proxy-connection",
49
+ "connection",
50
+ "keep-alive",
51
+ "te",
52
+ "trailer",
53
+ "transfer-encoding",
54
+ "upgrade",
55
+ ]);
56
+
57
+ /** The headers to send upstream for a request to `url`. */
58
+ function forwardedHeaders(headers, url) {
59
+ const named = String(headers.connection ?? "")
60
+ .split(",")
61
+ .map((h) => h.trim().toLowerCase())
62
+ .filter(Boolean);
63
+ const out = {};
64
+ for (const [name, value] of Object.entries(headers)) {
65
+ const lower = name.toLowerCase();
66
+ if (!DROPPED.has(lower) && !named.includes(lower) && value !== undefined) out[name] = value;
67
+ }
68
+ out.host = url.host;
69
+ return out;
70
+ }
71
+
72
+ /**
73
+ * Start the proxy on `bind` (an address the relay reaches, never all
74
+ * interfaces). `refused` collects every host it turned away.
75
+ * @param {{ registries: string[], bind: string }} opts
76
+ * @returns {Promise<{ port: number, refused: string[], close: () => Promise<void> }>}
77
+ */
78
+ export async function startEgressProxy({ registries, bind }) {
79
+ const allowed = allowlistOf(registries);
80
+ const permits = (host, port) =>
81
+ allowed.get(host.toLowerCase().replace(/^\[|\]$/g, ""))?.has(port) ?? false;
82
+ const refused = [];
83
+ const sockets = new Set();
84
+
85
+ const server = createServer((req, res) => {
86
+ let url;
87
+ try {
88
+ url = new URL(req.url ?? "");
89
+ } catch {
90
+ res.writeHead(400).end("deep-scan setup proxy: an absolute http:// URL is required\n");
91
+ return;
92
+ }
93
+ const port = Number(url.port || 80);
94
+ if (url.protocol !== "http:" || !permits(url.hostname, port)) {
95
+ refused.push(url.host);
96
+ res
97
+ .writeHead(403)
98
+ .end(`deep-scan setup proxy: ${url.host} is not in the recipe's registries\n`);
99
+ return;
100
+ }
101
+ const upstream = request(
102
+ url,
103
+ { method: req.method, headers: forwardedHeaders(req.headers, url) },
104
+ (r) => {
105
+ res.writeHead(r.statusCode ?? 502, r.headers);
106
+ r.pipe(res);
107
+ },
108
+ );
109
+ upstream.on("error", () => res.destroy());
110
+ req.pipe(upstream);
111
+ });
112
+
113
+ server.on("connect", (req, socket, head) => {
114
+ socket.on("error", () => {});
115
+ const target = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(req.url ?? "");
116
+ if (!target || !permits(target[1], Number(target[2]))) {
117
+ refused.push(req.url ?? "");
118
+ socket.end("HTTP/1.1 403 Forbidden\r\n\r\n");
119
+ return;
120
+ }
121
+ const upstream = connect(Number(target[2]), target[1].replace(/^\[|\]$/g, ""), () => {
122
+ socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
123
+ if (head?.length) upstream.write(head);
124
+ upstream.pipe(socket);
125
+ socket.pipe(upstream);
126
+ });
127
+ sockets.add(upstream);
128
+ upstream.on("close", () => sockets.delete(upstream));
129
+ upstream.on("error", () => socket.destroy());
130
+ });
131
+ server.on("connection", (socket) => {
132
+ sockets.add(socket);
133
+ socket.on("close", () => sockets.delete(socket));
134
+ });
135
+
136
+ await new Promise((resolve, reject) => {
137
+ server.once("error", reject);
138
+ server.listen(0, bind, () => resolve(undefined));
139
+ });
140
+ const address = server.address();
141
+ return {
142
+ port: typeof address === "object" && address ? address.port : 0,
143
+ refused,
144
+ close: () =>
145
+ new Promise((resolve) => {
146
+ for (const s of sockets) s.destroy();
147
+ server.close(() => resolve(undefined));
148
+ }),
149
+ };
150
+ }