Skip to content

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

fix(network): share the LAN listener with tailnet IPv4 addresses

Afloat83e3a784817c
diff --git a/server/index.ts b/server/index.ts
index adffe7d40b..8fa6621cb7 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -767,7 +767,7 @@ delete process.env.OMB_CLI_OWNER_STDIN;
// Empty is a deny-all bootstrap state; only Electron's private utility-process port replaces it.
let desktopMutationToken: string | undefined = DESKTOP_MANAGED ? "" : undefined;
let companionMutationToken: string | undefined = DESKTOP_MANAGED ? "" : undefined;
-const FALLBACK_PUBLIC_URL = process.env.OMB_PUBLIC_URL?.trim().replace(/\/+$/, "") || null; const tailnetShare = createTailnetShare({ port: PORT, handle: (req, res) => handleRequest(req, res), attach: (listener, handle) => upgrades.attach(listener, handle), log: (line) => console.log(line) });
+const FALLBACK_PUBLIC_URL = process.env.OMB_PUBLIC_URL?.trim().replace(/\/+$/, "") || null; const tailnetShare = createTailnetShare({ port: PORT, primaryAddress: () => server.address(), handle: (req, res) => handleRequest(req, res), attach: (listener, handle) => upgrades.attach(listener, handle), log: (line) => console.log(line) });
const cfg = loadConfig();
const hostedModels = hostedModelPolicy(DATA_DIR);
const providerConfigs = () => hostedModels ? hostedModels.configs() : instanceConfigs(cfg);
diff --git a/server/tailnet-lan.test.ts b/server/tailnet-lan.test.ts
new file mode 100644
index 0000000000..7211c4c7f4
--- /dev/null
+++ b/server/tailnet-lan.test.ts
@@ -0,0 +1,102 @@
+import { createServer, request, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { afterEach, expect, it } from "vitest";
+
+import { listenHost } from "./lan-address.ts";
+import { createTailnetShare } from "./tailnet-listener.ts";
+
+const NAME = "laptop.tail1234.ts.net";
+const servers: Server[] = [];
+let share: ReturnType<typeof createTailnetShare> | null = null;
+const handle = async (_req: unknown, res: { end: (body: string) => void }) => { res.end("handled"); };
+const interfaces = () => ({ lo: [{ address: "127.0.0.1", family: "IPv4" as const, internal: true, netmask: "255.0.0.0", mac: "", cidr: "127.0.0.1/8" }] });
+
+async function listen(lan = true): Promise<Server> {
+ const server = createServer(handle);
+ servers.push(server);
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, listenHost(server, lan ? { OMB_LAN: "1" } : {}), resolve);
+ });
+ return server;
+}
+
+function ask(port: number, host: string, address = "127.0.0.1"): Promise<{ status: number; body: string }> {
+ return new Promise((resolve, reject) => {
+ const call = request({ host: address, port, headers: { host } }, (res) => {
+ let body = "";
+ res.setEncoding("utf8");
+ res.on("data", (chunk) => { body += chunk; });
+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body }));
+ });
+ call.on("error", reject);
+ call.end();
+ });
+}
+
+afterEach(async () => {
+ await share?.close();
+ share = null;
+ await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))));
+});
+
+it("shares the live LAN listener without repeatedly binding the same IPv4 address", async () => {
+ const main = await listen();
+ const port = (main.address() as AddressInfo).port;
+ const attached: Server[] = [];
+ const logs: string[] = [];
+ share = createTailnetShare({ port, primaryAddress: () => main.address(), interfaces, handle, attach: (server) => attached.push(server), log: (line) => logs.push(line) });
+ const config = { name: NAME, addresses: ["127.0.0.1"] };
+ await share.apply(config);
+ expect(share.origin()).toBeNull();
+ await share.start();
+ expect(share.state()).toEqual({ origin: `http://${NAME}:${port}`, listening: ["127.0.0.1"], error: null });
+ expect(await ask(port, `${NAME}:${port}`)).toEqual({ status: 200, body: "handled" });
+ await share.apply(config);
+ expect(attached).toHaveLength(0);
+ expect(logs.join("\n")).not.toContain("EADDRINUSE");
+
+ await share.apply(null);
+ expect(share.state()).toEqual({ origin: null, listening: [], error: null });
+ expect((await ask(port, "localhost")).body).toBe("handled");
+ await share.apply(config);
+ await share.close();
+ expect(share.origin()).toBeNull();
+ expect((await ask(port, "localhost")).body).toBe("handled");
+});
+
+it("still binds IPv6 separately and accepts the shared IPv4 address as a tailnet Host", async () => {
+ const main = await listen();
+ const port = (main.address() as AddressInfo).port;
+ const attached: Server[] = [];
+ share = createTailnetShare({ port, primaryAddress: () => main.address(), interfaces, handle, attach: (server) => attached.push(server) });
+ await share.start();
+ await share.apply({ name: NAME, addresses: ["127.0.0.1", "::1"] });
+ expect(share.state()).toEqual({ origin: `http://${NAME}:${port}`, listening: ["127.0.0.1", "::1"], error: null });
+ expect(attached).toHaveLength(1);
+ expect(await ask(port, `127.0.0.1:${port}`, "::1")).toEqual({ status: 200, body: "handled" });
+ expect((await ask(port, `evil.example.com:${port}`, "::1")).status).toBe(421);
+});
+
+it("reports a port occupied by another listener instead of borrowing a primary on a different port", async () => {
+ const other = await listen();
+ const main = await listen();
+ const port = (other.address() as AddressInfo).port;
+ share = createTailnetShare({ port, primaryAddress: () => main.address(), interfaces, handle, attach: () => {} });
+ await share.start();
+ await share.apply({ name: NAME, addresses: ["127.0.0.1"] });
+ expect(share.origin()).toBeNull();
+ expect(share.state().listening).toEqual([]);
+ expect(share.state().error).toContain("127.0.0.1: EADDRINUSE");
+});
+
+it("does not advertise an address absent from the machine just because the primary is a wildcard", async () => {
+ const main = await listen();
+ const port = (main.address() as AddressInfo).port;
+ share = createTailnetShare({ port, primaryAddress: () => main.address(), interfaces, handle, attach: () => {} });
+ await share.start();
+ await share.apply({ name: NAME, addresses: ["192.0.2.123"] });
+ expect(share.origin()).toBeNull();
+ expect(share.state().listening).toEqual([]);
+ expect(share.state().error).toContain("192.0.2.123:");
+});
diff --git a/server/tailnet-listener.ts b/server/tailnet-listener.ts
index ac201aea39..4d8794aeb6 100644
--- a/server/tailnet-listener.ts
+++ b/server/tailnet-listener.ts
@@ -74,6 +74,8 @@ type Handle = (req: IncomingMessage, res: ServerResponse) => Promise<unknown>;
export interface TailnetShareOptions {
port: number;
+ /** The existing primary server's live address, for reusing its listener. */
+ primaryAddress?: () => ReturnType<Server["address"]>;
handle: Handle;
/** WebSocket upgrades through the same handler. */
attach: (server: Server, handle: Handle) => void;
@@ -87,6 +89,8 @@ export function createTailnetShare(options: TailnetShareOptions) {
let started = false;
let desired: TailnetShareConfig | null = null;
let listeners = new Map<string, Server>();
+ let covered: string[] = [];
+ const listening = () => [...covered, ...listeners.keys()];
const connections = new WeakMap<Server, Set<Socket>>();
let allowed: ReadonlySet<string> = new Set();
let error: string | null = null;
@@ -128,7 +132,7 @@ export function createTailnetShare(options: TailnetShareOptions) {
const held = new Set<Socket>();
connections.set(server, held);
server.on("connection", (socket) => {
- if (!tailnetPeerAllowed(socket.remoteAddress, [...listeners.keys()])) return void socket.destroy();
+ if (!tailnetPeerAllowed(socket.remoteAddress, listening())) return void socket.destroy();
held.add(socket);
socket.once("close", () => held.delete(socket));
});
@@ -143,16 +147,22 @@ export function createTailnetShare(options: TailnetShareOptions) {
}
async function bind(config: TailnetShareConfig | null): Promise<void> {
- const wanted = config && "addresses" in config ? (config.addresses === "interface" ? tailnetInterfaceAddresses(interfaces()) : config.addresses) : [];
+ const primary = options.primaryAddress?.();
+ const wildcard = primary && typeof primary === "object" && primary.port === options.port && primary.address === "0.0.0.0";
+ const currentInterfaces: ReturnType<typeof networkInterfaces> = config && "addresses" in config && (config.addresses === "interface" || wildcard) ? interfaces() : {};
+ const wanted = config && "addresses" in config ? (config.addresses === "interface" ? tailnetInterfaceAddresses(currentInterfaces) : config.addresses) : [];
+ const local = Object.values(currentInterfaces).flatMap((entries) => (entries ?? []).map((entry) => bareAddress(entry.address)));
+ covered = primary && typeof primary === "object" && primary.port === options.port
+ ? wanted.filter((address) => primary.address === address || (wildcard && isIP(address) === 4 && local.includes(address))) : [];
for (const [address, server] of listeners) {
- if (!wanted.includes(address)) {
+ if (!wanted.includes(address) || covered.includes(address)) {
listeners.delete(address);
await close(server);
}
}
const failures: string[] = [];
for (const address of wanted) {
- if (listeners.has(address)) continue;
+ if (listeners.has(address) || covered.includes(address)) continue;
try {
listeners.set(address, await open(address));
log(`tailnet: listening on ${address.includes(":") ? `[${address}]` : address}:${options.port} for ${config!.name}`);
@@ -160,8 +170,8 @@ export function createTailnetShare(options: TailnetShareOptions) {
failures.push(`${address}: ${(failure as NodeJS.ErrnoException).code ?? (failure as Error).message}`);
}
}
- allowed = config ? tailnetHosts({ name: config.name, addresses: [...listeners.keys()], port: options.port }) : new Set();
- error = config && "addresses" in config && listeners.size === 0
+ allowed = config ? tailnetHosts({ name: config.name, addresses: listening(), port: options.port }) : new Set();
+ error = config && "addresses" in config && listening().length === 0
? failures.length ? `could not listen on the tailnet (${failures.join("; ")})` : "Tailscale's interface has no address on this computer"
: failures.length ? `could not listen on ${failures.join("; ")}` : null;
if (error) log(`tailnet: ${error}`);
@@ -196,10 +206,10 @@ export function createTailnetShare(options: TailnetShareOptions) {
origin(): string | null {
if (!desired) return null;
if ("served" in desired) return desired.served;
- return listeners.size ? tailnetOrigin(desired.name, options.port) : null;
+ return listening().length ? tailnetOrigin(desired.name, options.port) : null;
},
state(): TailnetShareState {
- return { origin: share.origin(), listening: [...listeners.keys()], error: desired && "served" in desired ? null : error };
+ return { origin: share.origin(), listening: listening(), error: desired && "served" in desired ? null : error };
},
/** The desktop app's private message; anything else is not ours. Replies with the state once it is applied. */
receive(message: unknown, reply: (answer: object) => void): boolean {
@@ -218,6 +228,7 @@ export function createTailnetShare(options: TailnetShareOptions) {
await applying;
const open = [...listeners.values()];
listeners = new Map();
+ covered = [];
allowed = new Set();
await Promise.all(open.map(close));
},