Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
egress gate: reach the next address when one family cannot route
WhatAKittya65c88163f7b
diff --git a/server/browser/egress/gate.test.ts b/server/browser/egress/gate.test.tsindex 0b399489b7..607aa5242b 100644--- a/server/browser/egress/gate.test.ts+++ b/server/browser/egress/gate.test.ts@@ -209,6 +209,33 @@ describe("egress gate", () => {expect(code).toBe(5);});+ it("reaches the next address when the first family cannot route, as autoSelectFamily was meant to", async () => {+ const reachable = NodeNet.createServer((socket) => socket.end("reached"));+ await new Promise<void>((resolve) => reachable.listen(0, "127.0.0.1", resolve));+ const reachablePort = (reachable.address() as NodeNet.AddressInfo).port;+ // A mixed list is what a public name usually resolves to. The first address is a public IPv6 this host cannot+ // route (a machine with no IPv6 route leaves the old code stalled until the socket times out); the second is+ // the local listener the gate must reach anyway. The name is this machine's own, as in the test above, so the+ // loopback answer is a place to connect to, not a rebinding.+ const resolve = async () => [+ { address: "2a00:1450:4009:c0f::54", family: 6 },+ { address: "127.0.0.1", family: 4 },+ ];+ const { port } = await gate({ ...serverRules, host: "desktop" }, [], resolve);+ const { code, socket } = await connectThrough(port, domainTarget("localhost", reachablePort));+ const answer = await new Promise<Buffer>((resolveAnswer, decline) => {+ socket.once("data", resolveAnswer);+ socket.once("close", () => decline(new Error("closed before an answer")));+ socket.once("error", decline);+ }).catch(() => Buffer.alloc(0));+ socket.destroy();+ await new Promise<void>((resolve) => reachable.close(() => resolve()));+ expect(code).toBe(0);+ // Without a route to the first address the second answers; with one, the first does. Either way the gate+ // connected instead of stalling.+ expect(answer.length === 0 || answer.toString() === "reached").toBe(true);+ });+it("fails instead of crashing when it cannot listen", async () => {const exhausted = Object.assign(new Error("too many open files"), { code: "EMFILE" });const listen = vi.spyOn(NodeNet.Server.prototype, "listen").mockImplementationOnce(function (this: NodeNet.Server) {diff --git a/server/browser/egress/gate.ts b/server/browser/egress/gate.tsindex c7bfe0006a..7b2d898edd 100644--- a/server/browser/egress/gate.ts+++ b/server/browser/egress/gate.ts@@ -114,6 +114,44 @@ function readRequest(data: Buffer) {return { command: data[1], host, port: data.readUInt16BE(end - 2), rest: data.subarray(end) };}+/** Connects to the first of `addresses` that answers, trying them the way Node's autoSelectFamily documents: each+ * address gets its own attempt, attempts start staggered so a family that cannot route does not hold up one that+ * can, and the first socket to connect wins while the rest are dropped. Rejects with the last attempt's error when+ * every one of them fails, as one connect would report it.+ *+ * By hand, because autoSelectFamily with a custom lookup never falls back: on Node 24, a list that mixes families+ * where the first cannot route (a host with no IPv6 route is the usual case) leaves the socket stalled until it+ * times out, with the IPv4 answer never tried. */+function connectChecked(port: number, addresses: readonly ResolvedAddress[], staggerMs = 250): Promise<Socket> {+ return new Promise((resolve, reject) => {+ const inFlight = new Set<Socket>();+ let next = 0;+ let settled = false;+ const startNext = (): void => {+ if (settled || next >= addresses.length) return;+ const { address, family } = addresses[next++]!;+ const attempt = connect({ host: address, port, family });+ inFlight.add(attempt);+ attempt.once("connect", () => {+ if (settled) return void attempt.destroy();+ settled = true;+ for (const other of inFlight) if (other !== attempt) other.destroy();+ resolve(attempt);+ });+ attempt.once("error", (error: NodeJS.ErrnoException) => {+ inFlight.delete(attempt);+ if (settled) return;+ if (inFlight.size === 0 && next >= addresses.length) {+ settled = true;+ reject(error);+ }+ });+ if (next < addresses.length) setTimeout(startNext, staggerMs).unref?.();+ };+ startNext();+ });+}+/** Listens on an ephemeral loopback port until closed; a gate that is not running fails every connection. */export function openGate(options: GateOptions): Promise<EgressGate> {const resolve = options.resolve ?? resolveTarget;@@ -181,26 +219,20 @@ export function openGate(options: GateOptions): Promise<EgressGate> {}if (!addresses.length) return refuse(client, HOST_UNREACHABLE);client.pause();- // Every checked address, IPv6 and IPv4 alike, so a host is still reached where one family is broken; the- // lookup hands back only checked addresses, so a name that now resolves elsewhere changes nothing.- const upstream = track(connect({- host: target.host,- port: target.port,- autoSelectFamily: true,- lookup: (_host, lookupOptions, callback) => lookupOptions.all- ? callback(null, addresses)- : callback(null, addresses[0]!.address, addresses[0]!.family),- }));- let connected = false;- upstream.once("connect", () => {- connected = true;- client.write(reply(SUCCEEDED));- for (const chunk of early) upstream.write(chunk);- upstream.pipe(client);- client.pipe(upstream);- });- upstream.once("error", () => { if (!connected && !client.destroyed) refuse(client, CONNECTION_REFUSED); });- upstream.on("close", () => { if (connected) client.destroy(); });+ // Every checked address, IPv6 and IPv4 alike, so a host is still reached where one family is broken. The+ // attempts go to exactly the checked addresses, so a name that now resolves elsewhere changes nothing.+ let upstream: Socket;+ try {+ upstream = track(await connectChecked(target.port, addresses));+ } catch {+ return refuse(client, CONNECTION_REFUSED);+ }+ if (client.destroyed) return void upstream.destroy();+ client.write(reply(SUCCEEDED));+ for (const chunk of early) upstream.write(chunk);+ upstream.pipe(client);+ client.pipe(upstream);+ upstream.on("close", () => client.destroy());client.on("close", () => upstream.destroy());})().catch(() => client.destroy());};