Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Network gates: bounded, cached name lookups off the file-write pool; a CONNECT with no answer ends in a 502 (#7974)

Milind Sonid98b9edc9c79
diff --git a/server/bot-box/egress-gate.test.ts b/server/bot-box/egress-gate.test.ts
index a62e065ef1..773e3d47fa 100644
--- a/server/bot-box/egress-gate.test.ts
+++ b/server/bot-box/egress-gate.test.ts
@@ -87,6 +87,24 @@ linuxBox("the box's egress gate", () => {
expect(opened.refused).toBe(0);
});
+ it("a CONNECT whose first address cannot be reached goes on to the next checked address", async () => {
+ const upstream = createServer((_req, res) => res.end("ok"));
+ await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));
+ cleanup.push(() => new Promise<void>((resolve) => upstream.close(() => resolve())));
+ const port = (upstream.address() as { port: number }).port;
+ // Nothing listens on the IPv6 loopback at this port, so the first attempt fails and the IPv4 one answers.
+ const opened = await gate({ resolve: async () => [{ address: "::1", family: 6 }, { address: "127.0.0.1", family: 4 }], decide: async () => null });
+ expect((await connectVia(opened.socketPath, `example.com:${port}`)).status).toBe("200");
+ });
+
+ it("a CONNECT to a destination that never answers gets a 502 at the time limit instead of waiting on", async () => {
+ // 192.0.2.1 is a documentation address: packets to it are dropped, or refused at once where there is no route.
+ const opened = await gate({ resolve: async () => [{ address: "192.0.2.1", family: 4 }], decide: async () => null, connectTimeoutMs: 300 });
+ const started = Date.now();
+ expect((await connectVia(opened.socketPath, "example.com:443")).status).toBe("502");
+ expect(Date.now() - started).toBeLessThan(5_000);
+ });
+
/** A loopback listener standing in for a public host that never answers, noting each connection, each request and when it ended. */
async function stalledUpstream() {
const requests: Array<{ url: string; closed: boolean }> = [];
diff --git a/server/bot-box/egress-gate.ts b/server/bot-box/egress-gate.ts
index 302afcc550..7fb6b241a1 100644
--- a/server/bot-box/egress-gate.ts
+++ b/server/bot-box/egress-gate.ts
@@ -3,10 +3,10 @@
// names itself and connects only to public addresses, so a bot's shell reaches neither this server's loopback routes,
// the local network, the cloud metadata service nor Fly's private network, whatever name it uses.
import { createServer, request as httpRequest, type ClientRequest, type IncomingMessage, type Server, type ServerResponse } from "node:http";
-import { connect, type Socket } from "node:net";
+import type { Socket } from "node:net";
import type { Duplex } from "node:stream";
-import { resolveTarget, type ResolvedAddress } from "../browser/egress/gate.ts";
+import { connectChecked, resolveTarget, type ResolvedAddress } from "../browser/egress/gate.ts";
import { refusalFor, type EgressRules } from "../browser/egress/policy.ts";
import { guardedHandler } from "./broker-headers.ts";
@@ -16,8 +16,12 @@ export interface EgressGateOptions {
decide?(target: { host: string; port: number }, addresses: readonly ResolvedAddress[]): Promise<string | null>;
resolve?(host: string): Promise<ResolvedAddress[]>;
onRefusal?(target: { host: string; port: number }, reason: string): void;
+ /** How long a CONNECT waits for the destination to answer before a 502. */
+ connectTimeoutMs?: number;
}
+const CONNECT_TIMEOUT_MS = 20_000;
+
export interface BoxEgressGate {
socketPath: string;
refused: number;
@@ -105,16 +109,19 @@ export function openBoxEgressGate(options: EgressGateOptions): Promise<BoxEgress
if (client.destroyed) return;
if ("refused" in verdict) { client.end(`HTTP/1.1 403 Forbidden\r\nX-Omb-Blocked: ${verdict.refused}\r\nConnection: close\r\n\r\n`); return; }
if ("unresolved" in verdict) { client.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n"); return; }
- const upstream = track(connect({ host: target.host, port: target.port, autoSelectFamily: true, lookup: pinnedLookup(verdict.addresses) as never }));
- let connected = false;
- upstream.once("connect", () => {
- connected = true;
- client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
- if (head.length) upstream.write(head);
- upstream.pipe(client);
- client.pipe(upstream);
- });
- upstream.once("error", () => { if (!connected && !client.destroyed) client.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n"); });
+ // Every checked address gets its own attempt, and one that never answers ends with a 502 the caller can retry.
+ let upstream: Socket;
+ try {
+ upstream = await connectChecked(target.port, verdict.addresses, track, client, undefined, options.connectTimeoutMs ?? CONNECT_TIMEOUT_MS);
+ } catch {
+ if (!client.destroyed) client.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n");
+ return;
+ }
+ if (client.destroyed) { upstream.destroy(); return; }
+ client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
+ if (head.length) upstream.write(head);
+ upstream.pipe(client);
+ client.pipe(upstream);
upstream.on("close", () => client.destroy());
client.on("close", () => upstream.destroy());
});
diff --git a/server/browser/egress/gate.test.ts b/server/browser/egress/gate.test.ts
index 95d1f20df8..0996abf64c 100644
--- a/server/browser/egress/gate.test.ts
+++ b/server/browser/egress/gate.test.ts
@@ -7,7 +7,7 @@ import type { NetworkInterfaceInfo } from "node:os";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { LinkOpened } from "../../../electron/device-link-protocol.mjs";
-import { gateChromeFlags, openGate, resolveTarget, type EgressGate, type GateTarget } from "./gate.ts";
+import { familiesInTurn, gateChromeFlags, openGate, resolveTarget, type EgressGate, type GateTarget } from "./gate.ts";
import { ownAddresses, refusalFor, type EgressRules, type Refusal } from "./policy.ts";
// A public IPv4 address this machine holds, which no private range covers.
@@ -598,3 +598,12 @@ describe("egress gate with the person's own computer as the way out", () => {
await vi.waitFor(() => expect(cancelled).toHaveBeenCalledOnce());
});
});
+
+describe("the order addresses are tried in", () => {
+ it("lets the families take turns, the first listed family first, and keeps every address", () => {
+ const six = (n: number) => ({ address: `2001:db8::${n}`, family: 6 }), four = (n: number) => ({ address: `203.0.113.${n}`, family: 4 });
+ expect(familiesInTurn([six(1), six(2), six(3), four(1), four(2)])).toEqual([six(1), four(1), six(2), four(2), six(3)]);
+ expect(familiesInTurn([four(1), four(2)])).toEqual([four(1), four(2)]);
+ expect(familiesInTurn([])).toEqual([]);
+ });
+});
diff --git a/server/browser/egress/gate.ts b/server/browser/egress/gate.ts
index 328e646a93..5bc8a027bc 100644
--- a/server/browser/egress/gate.ts
+++ b/server/browser/egress/gate.ts
@@ -9,8 +9,11 @@
// upstream connection gets a SOCKS reply, and a connection may go out through an upstream.
import { lookup } from "node:dns/promises";
import { connect, createServer, isIP, type BlockList, type Socket } from "node:net";
+import type { Duplex } from "node:stream";
import type { LinkOpened } from "../../../electron/device-link-protocol.mjs";
+import { cloudHomeConfigured } from "../../cloud-home.ts";
+import { lookupName } from "./names.ts";
import { addressClass, namesThisMachine, ownAddresses } from "./policy.ts";
export interface ResolvedAddress { address: string; family: number }
@@ -76,7 +79,9 @@ export async function resolveTarget(host: string): Promise<ResolvedAddress[]> {
const literal = isIP(host);
if (literal) return [{ address: host, family: literal }];
if (namesThisMachine(host)) return LOOPBACK_NAMES;
- return lookup(host, { all: true, verbatim: true }).catch(() => []);
+ // A Cloud home asks the name servers itself (names.ts). A person's own computer keeps the system lookup, which
+ // follows the network it is on: a VPN's name servers, split DNS, and the hosts file ahead of public answers.
+ return (cloudHomeConfigured() ? lookupName(host) : lookup(host, { all: true, verbatim: true })).catch(() => []);
}
// SOCKS5 (RFC 1928) replies: success, refused by rule, host unreachable, connection refused, command unsupported.
@@ -203,20 +208,43 @@ function readRequest(data: Buffer) {
* 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[], track: (socket: Socket) => Socket, client: Socket, staggerMs = 250): Promise<Socket> {
+/** The families take turns, first one first, so a host with many addresses of a family that cannot route is not
+ * held for a stagger per address before the other family gets its first attempt. */
+export function familiesInTurn(addresses: readonly ResolvedAddress[]): ResolvedAddress[] {
+ const first = addresses.filter((entry) => entry.family === addresses[0]?.family);
+ const rest = addresses.filter((entry) => entry.family !== addresses[0]?.family);
+ const order: ResolvedAddress[] = [];
+ for (let index = 0; index < Math.max(first.length, rest.length); index++) {
+ if (index < first.length) order.push(first[index]!);
+ if (index < rest.length) order.push(rest[index]!);
+ }
+ return order;
+}
+
+export function connectChecked(port: number, checked: readonly ResolvedAddress[], track: (socket: Socket) => Socket, client: Duplex, staggerMs = 250, giveUpMs = 0): Promise<Socket> {
+ const addresses = familiesInTurn(checked);
return new Promise((resolve, reject) => {
const inFlight = new Set<Socket>();
let next = 0;
let settled = false;
+ // With a limit, a destination that never answers is reported instead of holding the caller until the OS gives up.
+ const limit = giveUpMs > 0 ? setTimeout(() => {
+ if (settled) return;
+ settle();
+ for (const attempt of inFlight) attempt.destroy();
+ reject(new Error("connect timed out"));
+ }, giveUpMs) : null;
+ limit?.unref?.();
// The gate closing or the browser leaving drops every attempt still dialing, so none waits out the OS timeout.
const giveUp = () => {
if (settled) return;
settled = true;
+ if (limit) clearTimeout(limit);
for (const attempt of inFlight) attempt.destroy();
reject(new Error("client left"));
};
client.once("close", giveUp);
- const settle = () => { settled = true; client.off("close", giveUp); };
+ const settle = () => { settled = true; client.off("close", giveUp); if (limit) clearTimeout(limit); };
const startNext = (): void => {
if (settled || next >= addresses.length) return;
const { address, family } = addresses[next++]!;
diff --git a/server/browser/egress/names.test.ts b/server/browser/egress/names.test.ts
new file mode 100644
index 0000000000..2eb5105da9
--- /dev/null
+++ b/server/browser/egress/names.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from "vitest";
+
+import { createNameLookup, hasPublicIpv6, type NameAddress } from "./names.ts";
+
+const coded = (code: string) => Object.assign(new Error(code), { code });
+const never = <T>() => new Promise<T>(() => {});
+
+describe("the gates' name lookup", () => {
+ it("asks the name servers for both families and lists IPv6 first on a machine with a routable IPv6 address", async () => {
+ const asked: string[] = [];
+ const lookup = createNameLookup({
+ ipv6First: () => true,
+ query: async (host, family) => { asked.push(`${host}/${family}`); return family === 4 ? ["203.0.113.7"] : ["2001:db8::7"]; },
+ system: async () => { throw new Error("the system lookup is not asked when the name servers answer"); },
+ });
+ expect(await lookup("Example.COM.")).toEqual([{ address: "2001:db8::7", family: 6 }, { address: "203.0.113.7", family: 4 }]);
+ expect(asked.sort()).toEqual(["example.com/4", "example.com/6"]);
+ });
+
+ it("reuses an answer for a minute, then asks again", async () => {
+ let time = 1_000, asks = 0;
+ const lookup = createNameLookup({
+ now: () => time,
+ query: async (_host, family) => { if (family === 4) asks += 1; return family === 4 ? [`203.0.113.${asks}`] : []; },
+ });
+ expect(await lookup("example.com")).toEqual([{ address: "203.0.113.1", family: 4 }]);
+ time += 59_000;
+ expect(await lookup("example.com")).toEqual([{ address: "203.0.113.1", family: 4 }]);
+ expect(asks).toBe(1);
+ time += 2_000;
+ expect(await lookup("example.com")).toEqual([{ address: "203.0.113.2", family: 4 }]);
+ });
+
+ it("asks once for callers that arrive together", async () => {
+ let asks = 0;
+ let answer!: (addresses: string[]) => void;
+ const lookup = createNameLookup({
+ query: (_host, family) => family === 6 ? Promise.reject(coded("ENODATA")) : new Promise((resolve) => { asks += 1; answer = resolve; }),
+ });
+ const both = Promise.all([lookup("example.com"), lookup("example.com"), lookup("EXAMPLE.com")]);
+ await new Promise((resolve) => setImmediate(resolve));
+ answer(["203.0.113.7"]);
+ expect(await both).toEqual(Array.from({ length: 3 }, () => [{ address: "203.0.113.7", family: 4 }]));
+ expect(asks).toBe(1);
+ });
+
+ it("uses the last answer while the name servers are silent, without asking the system lookup, and for a quarter hour only", async () => {
+ let time = 1_000, silent = false, systemAsks = 0;
+ const lookup = createNameLookup({
+ now: () => time,
+ waitMs: 30,
+ query: (_host, family) => silent ? never<string[]>() : Promise.resolve(family === 4 ? ["203.0.113.7"] : []),
+ system: async () => { systemAsks += 1; return []; },
+ });
+ expect(await lookup("api.example.com")).toHaveLength(1);
+ silent = true;
+ time += 5 * 60_000;
+ const started = Date.now();
+ expect(await lookup("api.example.com")).toEqual([{ address: "203.0.113.7", family: 4 }]);
+ expect(Date.now() - started).toBeLessThan(2_000);
+ expect(lookup.stale).toBe(1);
+ time += 11 * 60_000;
+ expect(await lookup("api.example.com")).toEqual([]);
+ expect(await lookup("never-seen.example.com")).toEqual([]);
+ expect(systemAsks).toBe(0);
+ });
+
+ it("a name server error other than 'no such record' also leaves the system lookup alone", async () => {
+ let systemAsks = 0;
+ const lookup = createNameLookup({
+ query: () => Promise.reject(coded("ESERVFAIL")),
+ system: async () => { systemAsks += 1; return [{ address: "203.0.113.9", family: 4 }]; },
+ });
+ expect(await lookup("example.com")).toEqual([]);
+ expect(systemAsks).toBe(0);
+ });
+
+ it("asks the system lookup for a name the name servers do not have, so the hosts file still works", async () => {
+ const local: NameAddress[] = [{ address: "203.0.113.20", family: 4 }];
+ const lookup = createNameLookup({
+ query: (_host, family) => Promise.reject(coded(family === 4 ? "ENOTFOUND" : "ENODATA")),
+ system: async (host) => host === "build-box" ? local : [],
+ });
+ expect(await lookup("build-box")).toEqual(local);
+ expect(await lookup("no-such-name.invalid")).toEqual([]);
+ });
+
+ it("a system lookup that never returns does not hold the caller", async () => {
+ const lookup = createNameLookup({ waitMs: 30, query: () => Promise.reject(coded("ENOTFOUND")), system: () => never<NameAddress[]>() });
+ const started = Date.now();
+ expect(await lookup("build-box")).toEqual([]);
+ expect(Date.now() - started).toBeLessThan(2_000);
+ });
+
+ it("a query that throws at once is an unanswered one", async () => {
+ const lookup = createNameLookup({ query: () => { throw coded("EBADNAME"); }, system: async () => [] });
+ expect(await lookup("bad host name")).toEqual([]);
+ expect(await lookup("")).toEqual([]);
+ });
+
+ it("keeps no more names than its limit", async () => {
+ let asks = 0;
+ const lookup = createNameLookup({ maxNames: 2, query: async (_host, family) => { if (family === 4) asks += 1; return family === 4 ? ["203.0.113.7"] : []; } });
+ await lookup("a.example"); await lookup("b.example"); await lookup("c.example");
+ expect(asks).toBe(3);
+ await lookup("c.example"); await lookup("b.example");
+ expect(asks).toBe(3);
+ await lookup("a.example");
+ expect(asks).toBe(4);
+ });
+
+ it("lists IPv4 first on a machine with no routable IPv6 address, for the callers that connect to the first address only", async () => {
+ const lookup = createNameLookup({ ipv6First: () => false, query: async (_host, family) => family === 4 ? ["203.0.113.7"] : ["2001:db8::7"] });
+ expect(await lookup("example.com")).toEqual([{ address: "203.0.113.7", family: 4 }, { address: "2001:db8::7", family: 6 }]);
+ });
+
+ it("counts only a routable IPv6 address: not loopback, link-local or a private one", () => {
+ const entry = (address: string, family: "IPv4" | "IPv6", internal = false) => ({ address, family, internal, netmask: "", mac: "", cidr: null }) as never;
+ expect(hasPublicIpv6({ lo: [entry("::1", "IPv6", true)], eth0: [entry("10.0.0.5", "IPv4"), entry("fe80::1", "IPv6"), entry("fd00::5", "IPv6")] })).toBe(false);
+ expect(hasPublicIpv6({ eth0: [entry("2a01:4f8:c0c::1", "IPv6")] })).toBe(true);
+ expect(hasPublicIpv6({})).toBe(false);
+ });
+
+ it("makes its resolver again after a round nobody answered, and not after an answer or a 'no such record'", async () => {
+ let renewed = 0, mode: "silent" | "answer" | "missing" = "silent";
+ const lookup = createNameLookup({
+ waitMs: 30, freshMs: 0, renew: () => { renewed += 1; },
+ query: () => mode === "silent" ? never<string[]>() : mode === "answer" ? Promise.resolve(["203.0.113.7"]) : Promise.reject(coded("ENOTFOUND")),
+ system: async () => [],
+ });
+ await lookup("example.com");
+ expect(renewed).toBe(1);
+ mode = "answer"; await lookup("example.com");
+ mode = "missing"; await lookup("other.example");
+ expect(renewed).toBe(1);
+ });
+});
diff --git a/server/browser/egress/names.ts b/server/browser/egress/names.ts
new file mode 100644
index 0000000000..ab6e5f7fd5
--- /dev/null
+++ b/server/browser/egress/names.ts
@@ -0,0 +1,135 @@
+// Name lookups for the network gates. Every connection a bot's shell or browser opens asks here first, so a lookup
+// must never wait without bound, and must not queue behind file writes: the system lookup (getaddrinfo) runs on the
+// four-thread pool that file writes share, where a slow name server holds every thread and the event log backs up
+// behind it. So, on a Cloud home, names are asked of the name servers directly, off that pool, with a time limit; an answer is reused
+// for a minute; and while the name servers do not answer, the last answer of the past quarter hour is used. Callers
+// check the addresses against their policy on every call, reused or not.
+import { lookup as systemLookup, Resolver } from "node:dns/promises";
+import { networkInterfaces } from "node:os";
+
+export interface NameAddress { address: string; family: number }
+
+export interface NameLookupOptions {
+ /** One record type from the name servers; rejects with a `code` as node:dns does. */
+ query?(host: string, family: 4 | 6): Promise<string[]>;
+ /** Called after a round no name server answered. */
+ renew?(): void;
+ /** Whether IPv6 addresses are listed before IPv4 ones. */
+ ipv6First?(): boolean;
+ /** The system's own lookup, which also reads the hosts file. */
+ system?(host: string): Promise<NameAddress[]>;
+ now?(): number;
+ freshMs?: number;
+ staleMs?: number;
+ /** The longest one call waits for the name servers, and then for the system lookup. */
+ waitMs?: number;
+ maxNames?: number;
+}
+
+export interface NameLookup {
+ (host: string): Promise<NameAddress[]>;
+ /** Names answered from an answer past its minute because the name servers did not answer. */
+ stale: number;
+}
+
+/** The name servers said the name has no such record: the hosts file may still know it. */
+const NO_RECORD = new Set(["ENOTFOUND", "ENODATA", "ENONAME", "EBADNAME", "EBADRESP", "EFORMERR"]);
+
+const withTimeout = <T>(work: Promise<T>, ms: number, fallback: T): Promise<T> =>
+ new Promise((resolve) => {
+ const timer = setTimeout(() => resolve(fallback), ms);
+ timer.unref?.();
+ work.then((value) => { clearTimeout(timer); resolve(value); }, () => { clearTimeout(timer); resolve(fallback); });
+ });
+
+/** A resolver keeps the name servers it read when it was made, so one that got no answer is made again: a machine
+ * whose name servers changed is then asked through the new ones. */
+function defaultQuery(): { query(host: string, family: 4 | 6): Promise<string[]>; renew(): void } {
+ let resolver: Resolver | null = null;
+ return {
+ query: (host, family) => {
+ resolver ??= new Resolver({ timeout: 2_000, tries: 2 });
+ return family === 4 ? resolver.resolve4(host) : resolver.resolve6(host);
+ },
+ renew: () => { resolver = null; },
+ };
+}
+
+/** Whether this machine has an IPv6 address the internet can route to. Without one IPv4 is listed first, as the
+ * system lookup orders them, because some callers connect to the first address only. */
+export function hasPublicIpv6(interfaces: ReturnType<typeof networkInterfaces> = networkInterfaces()): boolean {
+ for (const entries of Object.values(interfaces)) {
+ for (const entry of entries ?? []) {
+ if (entry.family !== "IPv6" || entry.internal) continue;
+ const first = Number.parseInt(entry.address.split(":")[0] || "0", 16);
+ // 2000::/3 is the routable range; link-local (fe80::/10) and private (fc00::/7) addresses do not count.
+ if ((first & 0xe000) === 0x2000) return true;
+ }
+ }
+ return false;
+}
+
+const defaultSystem = (host: string): Promise<NameAddress[]> => systemLookup(host, { all: true, verbatim: true });
+
+export function createNameLookup(options: NameLookupOptions = {}): NameLookup {
+ const own = options.query ? null : defaultQuery();
+ const query = options.query ?? own!.query;
+ const renew = options.renew ?? own?.renew ?? (() => {});
+ const ipv6First = options.ipv6First ?? hasPublicIpv6;
+ const system = options.system ?? defaultSystem;
+ const now = options.now ?? Date.now;
+ const freshMs = options.freshMs ?? 60_000, staleMs = options.staleMs ?? 15 * 60_000;
+ const waitMs = options.waitMs ?? 8_000, maxNames = options.maxNames ?? 2_048;
+ const known = new Map<string, { addresses: NameAddress[]; at: number }>();
+ const asking = new Map<string, Promise<NameAddress[]>>();
+
+ const remember = (name: string, addresses: NameAddress[]) => {
+ known.delete(name);
+ known.set(name, { addresses, at: now() });
+ if (known.size > maxNames) known.delete(known.keys().next().value!);
+ };
+
+ const ask = async (name: string): Promise<NameAddress[]> => {
+ type Answer = { addresses: string[]; missing: boolean };
+ const one = (family: 4 | 6): Promise<Answer> =>
+ Promise.resolve().then(() => query(name, family)).then(
+ (addresses) => ({ addresses, missing: false }),
+ (error: NodeJS.ErrnoException) => ({ addresses: [], missing: NO_RECORD.has(error?.code ?? "") }),
+ );
+ const unanswered: Answer = { addresses: [], missing: false };
+ const [six, four] = await Promise.all([withTimeout(one(6), waitMs, unanswered), withTimeout(one(4), waitMs, unanswered)]);
+ const sixes = six.addresses.map((address) => ({ address, family: 6 })), fours = four.addresses.map((address) => ({ address, family: 4 }));
+ const found: NameAddress[] = ipv6First() ? [...sixes, ...fours] : [...fours, ...sixes];
+ if (found.length) { remember(name, found); return found; }
+ // Only a name the name servers answered "no such record" for goes to the system lookup: asking it while they are
+ // silent is what holds the shared pool.
+ if (six.missing && four.missing) {
+ const local = await withTimeout(system(name), waitMs, [] as NameAddress[]);
+ if (local.length) { remember(name, local); return local; }
+ known.delete(name);
+ return [];
+ }
+ if (!six.missing && !four.missing) renew();
+ const last = known.get(name);
+ if (last && now() - last.at <= staleMs) { lookupName.stale += 1; return last.addresses; }
+ return [];
+ };
+
+ const lookupName = (async (host: string): Promise<NameAddress[]> => {
+ const name = host.toLowerCase().replace(/\.$/, "");
+ if (!name) return [];
+ const last = known.get(name);
+ if (last && now() - last.at <= freshMs) return last.addresses;
+ let pending = asking.get(name);
+ if (!pending) {
+ pending = ask(name).finally(() => asking.delete(name));
+ asking.set(name, pending);
+ }
+ return pending;
+ }) as NameLookup;
+ lookupName.stale = 0;
+ return lookupName;
+}
+
+/** The one lookup every gate in this process shares, so a name one bot just reached is not asked again for another. */
+export const lookupName: NameLookup = createNameLookup();
diff --git a/server/use-my-mac.e2e.test.ts b/server/use-my-mac.e2e.test.ts
index 542cfed8d0..cc73115ade 100644
--- a/server/use-my-mac.e2e.test.ts
+++ b/server/use-my-mac.e2e.test.ts
@@ -188,7 +188,9 @@ async function boot() {
// Off the internet: My Cloud's own fetches go nowhere, and its own way out resolves no name, so it reaches nothing.
const offlinePrelude = `data:text/javascript,${encodeURIComponent([
'import dns from "node:dns/promises"; import { syncBuiltinESMExports } from "node:module";',
- 'dns.lookup = async (host) => { throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${host}`), { code: "ENOTFOUND" }); }; syncBuiltinESMExports();',
+ 'const missing = async (host) => { throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${host}`), { code: "ENOTFOUND" }); };',
+ // A Cloud home asks the name servers itself (browser/egress/names.ts), so its resolver answers "no such name" too.
+ 'dns.lookup = missing; dns.Resolver = class { resolve4(host) { return missing(host); } resolve6(host) { return missing(host); } }; syncBuiltinESMExports();',
'const real = globalThis.fetch; globalThis.fetch = async (url, init) => String(url).startsWith("http://127.0.0.1:") ? real(url, init) : new Response("offline fixture", { status: 503 });',
].join("\n"))}`;
child = spawn(process.execPath, ["--import", offlinePrelude, join(SERVER_DIR, "index.ts")], {