Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Turning the tailnet share off ends its WebSockets, and policy gates it from launch
Milind Sonif4d0ecc054df
diff --git a/electron/main.mjs b/electron/main.mjsindex 6e9fa7088f..3c2793de86 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -87,7 +87,7 @@ import {} from "./companion-account-service.mjs";import capabilitiesModule from "./capabilities.cjs";import environmentsModule from "./environments.cjs";-import { pairingPageUrl } from "./server-address.mjs"; import { createServerConnect } from "./server-probe.mjs"; import { createTailnetShare } from "./tailnet-share.mjs"; import { checkTailscale } from "./tailscale-check.mjs"; import { onTailnet } from "./tailnet.mjs"; import { checkServer, createServerStatus, installServerStatus } from "./server-status.mjs";+import { pairingPageUrl } from "./server-address.mjs"; import { createServerConnect } from "./server-probe.mjs"; import { createTailnetShare, remotePolicyAllows } from "./tailnet-share.mjs"; import { checkTailscale } from "./tailscale-check.mjs"; import { onTailnet } from "./tailnet.mjs"; import { checkServer, createServerStatus, installServerStatus } from "./server-status.mjs";import localOriginModule from "./local-origin.cjs";import { buildApplicationMenu } from "./menu.mjs";import { createComputerSharing, isHomeFolder, validateSharedFolders } from "./computer-sharing.mjs"; import { installServerLending } from "./server-lending.mjs"; import { ownEnvironmentIds } from "./lent-mcp.mjs";@@ -689,7 +689,7 @@ async function stopDesktopCompanion({ remember = true } = {}) {return desktopCompanionState();}-const tailnetShare = createTailnetShare({ check: checkTailscale, allowed: () => !managedRemoteAccessRefusal(), log: slog }); const phoneLinkRoutes = createPhoneLinkRoutes({ shareChanged: () => tailnetShare.apply(companionSettings().routes.tailscale), rememberRoute: rememberCompanionRoute, routeOn: companionRouteOn, dismissNotice: dismissCompanionNotice, state: () => desktopCompanionState(), running: companionRunning, log: slog, changed: (route, on) => (route !== "https" ? companionE2E?.reconcile() : on ? startManagedCompanionConnection({ waitForVerification: false }) : stopManagedCompanionEndpointLocally()),+const tailnetShare = createTailnetShare({ check: checkTailscale, allowed: () => remotePolicyAllows({ managed: app.isPackaged && !desktopRemoteAccess, client: managedDesktop }), markerFile: () => path.join(app.getPath("userData"), "tailnet-serve.marker"), log: slog }); const phoneLinkRoutes = createPhoneLinkRoutes({ shareChanged: () => tailnetShare.apply(companionSettings().routes.tailscale), rememberRoute: rememberCompanionRoute, routeOn: companionRouteOn, dismissNotice: dismissCompanionNotice, state: () => desktopCompanionState(), running: companionRunning, log: slog, changed: (route, on) => (route !== "https" ? companionE2E?.reconcile() : on ? startManagedCompanionConnection({ waitForVerification: false }) : stopManagedCompanionEndpointLocally()),wake: () => (!companionRunning() && companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }) ? startDesktopCompanion({ waitForHosted: false, remember: false }) : null), sleep: () => stopDesktopCompanion({ remember: false }) });setCompanionMigrationFacts(() => ({ managedAddress: Boolean(managedCompanionTunnelAccess(secureCredentials)) }));@@ -914,7 +914,7 @@ function ensureManagedDesktop() {appVersion: app.getVersion(),openBrowser: url => shell.openExternal(url),onState: state => {- if (state.status === "license-expired") companyBackupController?.abort();+ if (state.status === "license-expired") companyBackupController?.abort(); void tailnetShare.recheck();const lost = ["signed-out", "reauth-required"].includes(state.status), withoutStorage = state.status === "connected" && !state.cloudBackups;if (lost || withoutStorage) {companyBackupConfigurationRevision++;@@ -3028,7 +3028,7 @@ app.whenReady().then(async () => {}}if (desktopShutdownStarted) return;- if (app.isPackaged && !desktopRemoteAccess) void ensureManagedDesktop().start().then(() => companyBackupSchedule.start()).catch(() => {});+ if (app.isPackaged && !desktopRemoteAccess) { void ensureManagedDesktop().start().then(() => companyBackupSchedule.start()).catch(() => {}); void managedDesktop.whenRestored().then(() => tailnetShare.recheck()); }// Fresh local use never makes a Cloud request; start only restores an existing grant.if (app.isPackaged && !desktopRemoteAccess) {cloudAccountRestoring = true;diff --git a/electron/managed-desktop.mjs b/electron/managed-desktop.mjsindex fdae4db33e..395579ca05 100644--- a/electron/managed-desktop.mjs+++ b/electron/managed-desktop.mjs@@ -163,7 +163,7 @@ export function createManagedDesktopClient({ store, applyConnection, applyPolicyconst restored = new Promise(resolve => { markRestored = resolve; });let grant = null, connection = null, pending = null, state = { status: "signed-out" };let renewalCheckedFor = null, lastRenewAttempt = 0, renewalSupported = false, reportedPolicyVersion = null;- let policyLifted = false;+ let policyLifted = false, policyRead = false;let issuedGrant = null, cleanupGrant = null, cleanupNeeded = false, clearing = null, restoreFailures = 0;let generation = 0, timer = null, closed = false, controller = new AbortController(), refreshing = null;let branding = parseOrganizationBranding(null);@@ -465,6 +465,7 @@ export function createManagedDesktopClient({ store, applyConnection, applyPolicy// Restore the last policy before any network call.if (grant?.policy && grant.expiresAt > now()) await sendPolicy(grant);if (library && grant && grant.expiresAt > now()) await Promise.resolve().then(() => library.restore(libraryIdentity(grant))).catch(() => {});+ policyRead = true;markRestored();await sendIdentity(grant);return refresh();@@ -514,6 +515,8 @@ export function createManagedDesktopClient({ store, applyConnection, applyPolicy/** Main-process only. Never expose this method through the renderer bridge. */connection: () => connection ? structuredClone(connection) : null,whenRestored: () => restored,+ /** The saved policy has been read; until then, and while it can't be read, `policy()` is null without meaning "none". */+ policyKnown: () => policyRead,policy: () => !policyLifted && grant?.policy && grant.expiresAt > now() ? structuredClone(grant.policy) : null,backupGeneration: () => generation,/** Fixed first-party backup API only; this function stays in Electron main. */diff --git a/electron/managed-desktop.node-test.mjs b/electron/managed-desktop.node-test.mjsindex d08dfee40e..c5f614916c 100644--- a/electron/managed-desktop.node-test.mjs+++ b/electron/managed-desktop.node-test.mjs@@ -557,3 +557,13 @@ test("reports when the saved enrollment has been read", async t => {await f.client.start(); await settle();assert.equal(restored, true); assert.equal(f.policies[0].remoteAccess, false, "the saved policy applied before the Admin answered");});++test("the saved policy counts as known only once it has been read", async t => {+ const f = fixture(t, { saved: null });+ assert.equal(f.client.policyKnown(), false);+ await f.client.start();+ assert.equal(f.client.policyKnown(), true);+ const unreadable = fixture(t, { store: { read: async () => { throw new Error("locked"); }, write: async () => {}, remove: async () => {}, clear: async () => {} } });+ await unreadable.client.start();+ assert.equal(unreadable.client.policyKnown(), false, "a store that can't be read says nothing about the policy");+});diff --git a/electron/server-address.mjs b/electron/server-address.mjsindex b92d640848..2733927938 100644--- a/electron/server-address.mjs+++ b/electron/server-address.mjs@@ -1,6 +1,6 @@// What a person types or pastes to reach a MausBot server: a pairing link, an address, an address and a code typed// apart, or a code on its own. One reader for the desktop's Connect sheet, `openmausbot connect` and the MCP bridge.-import { isTailnetHost } from "./tailnet.mjs";+import { isTailnetHost, isTailnetName } from "./tailnet.mjs";export const PAIRING_CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";export const PAIRING_CODE_LENGTH = 12;@@ -43,11 +43,11 @@ export function isPrivateHost(host) {return !name.includes(".") && /^[a-z0-9-]+$/.test(name);}-/** How a saved server is reached, for the line under its name. A tailnet address is Tailscale over http too: WireGuard- * encrypts it. */+/** How a saved server is reached, for the line under its name. A MagicDNS name is Tailscale over http too: WireGuard+ * encrypts it. A bare 100.64/10 address may be carrier NAT or another VPN, so it is only a private address. */export function serverTransport(origin) {const url = new URL(origin);- if (isTailnetHost(bareHost(url.hostname))) return "tailscale";+ if (isTailnetName(bareHost(url.hostname))) return "tailscale";if (url.protocol === "https:") return "https";return isLoopbackHost(url.hostname) ? "loopback" : "private-http";}diff --git a/electron/server-address.node-test.mjs b/electron/server-address.node-test.mjsindex 1d2f5062fd..4c58d1bd50 100644--- a/electron/server-address.node-test.mjs+++ b/electron/server-address.node-test.mjs@@ -89,7 +89,8 @@ test("each transport is named for the line under a saved server", () => {assert.equal(serverTransport("https://box.tail1234.ts.net"), "tailscale");// Inside WireGuard: encrypted although the scheme is http.assert.equal(serverTransport("http://box.tail1234.ts.net:8799"), "tailscale");- assert.equal(serverTransport("http://100.101.102.103:8799"), "tailscale");+ // A bare 100.64/10 address may be carrier NAT or another VPN.+ assert.equal(serverTransport("http://100.101.102.103:8799"), "private-http");assert.equal(serverTransport("http://192.168.1.20:8799"), "private-http");assert.equal(serverTransport("http://127.0.0.1:8799"), "loopback");});diff --git a/electron/server-probe.mjs b/electron/server-probe.mjsindex c61a83966b..b36aed74a5 100644--- a/electron/server-probe.mjs+++ b/electron/server-probe.mjs@@ -1,7 +1,7 @@// Before connecting, the Connect sheet asks the address who it is: the server's public descriptor names it, and a// failure is sorted into one thing the person can fix.import { EXAMPLE_ADDRESS, isLoopbackHost, parseServerInput, serverTransport } from "./server-address.mjs";-import { isTailnetHost } from "./tailnet.mjs";+import { inTailscaleRange, isTailnetName } from "./tailnet.mjs";const DESCRIPTOR = "/.well-known/openmausbot/environment";/** A MausBot desktop app's Remote access (companion/src/routes.ts) refuses the descriptor with this until a phone pairs. */@@ -127,7 +127,9 @@ export async function probeServer({ address, code = "", fetch: fetchImpl, ownEnvconst blockedOnMac = platform === "darwin" && serverTransport(origin) === "private-http" && (kind === "unreachable" || kind === "timeout");// Once a candidate turned out to be another computer's desktop app, that's the problem to report.if (failure?.problem === "desktopApp") continue;- const tailnetHost = isTailnetHost(hostname.replace(/^\[|\]$/g, "")) && !["certificate", "notMausBot", "desktopApp"].includes(found.kind);+ // A bare 100.64/10 address counts only on a computer that is on a tailnet: carrier NAT and other VPNs use that range.+ const bare = hostname.replace(/^\[|\]$/g, "");+ const tailnetHost = (isTailnetName(bare) || (inTailscaleRange(bare) && tailnet())) && found.kind !== "certificate" && found.kind !== "notMausBot";const problem = loopback ? { problem: "loopback", host } : tailnetHost ? { problem: tailnetProblem(found.kind, platform, tailnet()), host } : blockedOnMac ? { problem: "localNetwork", host }: { problem: kind === "refused" || kind === "timeout" ? "unreachable" : kind, host, ...(kind === "refused" || kind === "timeout" ? { reason: kind } : {}) };// A later guess at a tailnet name that just didn't answer says less than whatever an earlier one said.diff --git a/electron/server-probe.node-test.mjs b/electron/server-probe.node-test.mjsindex 896c2e8889..4e6b541e76 100644--- a/electron/server-probe.node-test.mjs+++ b/electron/server-probe.node-test.mjs@@ -67,6 +67,9 @@ test("a tailnet address that doesn't answer says whose Tailscale to fix", asyncassert.equal((await probe(fakeFetch({}).fetch)).problem, "tailnetSilent");// A bare tailnet address and an https name are tailnet addresses too.assert.equal((await probeServer({ address: "http://100.101.102.103:8799", fetch: fakeFetch({ "http://100.101.102.103:8799": blocked() }).fetch, platform: "darwin", tailnet: () => true })).problem, "tailnetBlocked");+ // Off a tailnet a bare 100.64/10 address is just a private one: carrier NAT or another VPN keeps the Local Network hint.+ const bare = await probeServer({ address: "http://100.101.102.103:8799", fetch: fakeFetch({ "http://100.101.102.103:8799": blocked() }).fetch, platform: "darwin", tailnet: () => false });+ assert.deepEqual(bare, { outcome: "problem", problem: "localNetwork", host: "100.101.102.103:8799" });// Typed alone, the name is tried three ways; the one that named a cause is the one shown.const typed = fakeFetch({ "https://macmini.tail1234.ts.net": new Error("net::ERR_CERT_COMMON_NAME_INVALID"), "http://macmini.tail1234.ts.net": refused(), "http://macmini.tail1234.ts.net:8799": refused() });assert.equal((await probeServer({ address: "macmini.tail1234.ts.net", fetch: typed.fetch, tailnet: () => true })).problem, "certificate");diff --git a/electron/tailnet-share.mjs b/electron/tailnet-share.mjsindex 55e32fc438..49ae8ce825 100644--- a/electron/tailnet-share.mjs+++ b/electron/tailnet-share.mjs@@ -2,6 +2,7 @@// the tailnet hands out certificates and nothing else holds the port; otherwise the server listens on its tailnet// addresses itself. Never Funnel: nothing here is reachable from outside the tailnet.import { execFile, spawn as spawnChild } from "node:child_process";+import fs from "node:fs";import { tailnetOrigin } from "./tailnet.mjs";import { tailscaleEnvironment } from "./tailscale-check.mjs";@@ -29,12 +30,33 @@ const readServeStatus = (cli) =>(error, stdout) => resolve(error ? "" : String(stdout ?? "")));});+const readCommandLine = (pid) =>+ new Promise((resolve) => {+ const [file, args] = process.platform === "win32"+ ? ["powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`]]+ : ["ps", ["-o", "command=", "-p", String(pid)]];+ execFile(file, args, { timeout: 5_000, windowsHide: true }, (error, stdout) => resolve(error ? "" : String(stdout ?? "")));+ });++/**+ * Security: whether an organization's policy lets this computer share itself. `managed` is a packaged app running its own+ * server; until its client has read the saved policy nothing is known, and unknown counts as no.+ */+export function remotePolicyAllows({ managed, client }) {+ return !managed || (client?.policyKnown?.() === true && client.policy()?.remoteAccess !== false);+}+/*** `check()` is checkTailscale. `allowed()` is false while an organization's policy keeps remote access off. `apply` takes* the saved Tailscale route, `attach` each new server process; a server process forgets its share when it exits.+ * `recheck` follows a change in `allowed()`. `markerFile()` notes a running `tailscale serve`, so the next launch can end+ * one a crash left behind.*/-export function createTailnetShare({ check, allowed = () => true, spawn = spawnChild, serveStatus = readServeStatus, settleMs = 2_500, answerMs = 5_000, log = () => {} }) {+export function createTailnetShare({ check, allowed = () => true, spawn = spawnChild, serveStatus = readServeStatus, markerFile = () => null, commandLine = readCommandLine, kill = process.kill.bind(process), settleMs = 2_500, answerMs = 5_000, log = () => {} }) {let server = null;+ let starting = null;+ let quitting = false;+ let lastAllowed;let wanted = null;let serving = null;let shown = OFF;@@ -64,6 +86,34 @@ export function createTailnetShare({ check, allowed = () => true, spawn = spawnC});}+ const forgetMarker = () => {+ const file = markerFile();+ if (file) fs.rmSync(file, { force: true });+ };++ /** Only a process still running exactly the command noted is ended, so a reused pid is left alone. */+ async function endLeftover() {+ const file = markerFile();+ if (serving || !file) return;+ let marker;+ try {+ marker = JSON.parse(fs.readFileSync(file, "utf8"));+ } catch {+ return;+ }+ const { pid, port } = marker ?? {};+ const command = `serve --https=${HTTPS_PORT} http://127.0.0.1:${port}`;+ if (Number.isSafeInteger(pid) && pid > 0 && Number.isSafeInteger(port) && (await commandLine(pid)).includes(command)) {+ log("tailnet: ending a tailscale serve an earlier run left behind");+ try {+ kill(pid, "SIGTERM");+ } catch {+ }+ for (let tries = 0; tries < 30 && (await commandLine(pid)).includes(command); tries++) await new Promise((done) => setTimeout(done, 100));+ }+ forgetMarker();+ }+async function stopServing() {const current = serving;serving = null;@@ -73,6 +123,7 @@ export function createTailnetShare({ check, allowed = () => true, spawn = spawnCcurrent.child.kill("SIGTERM");} catch {}+ forgetMarker();await Promise.race([current.exited, new Promise((done) => setTimeout(done, 3_000).unref?.())]);}@@ -88,15 +139,28 @@ export function createTailnetShare({ check, allowed = () => true, spawn = spawnC} catch {return null;}+ starting = child;+ const file = markerFile();+ if (file && child.pid) {+ try {+ fs.writeFileSync(file, JSON.stringify({ pid: child.pid, port }), { mode: 0o600 });+ } catch {+ }+ }const exited = new Promise((done) => { child.once("exit", () => done("exited")); child.once("error", () => done("exited")); });const early = await Promise.race([exited, new Promise((done) => setTimeout(() => done("running"), settleMs))]);if (early !== "running") {+ starting = null;+ forgetMarker();log("tailnet: tailscale serve stopped at once; listening on the tailnet instead");return null;}// Serve waits on an enablement link without saying so; only a listed port is a share.- if (!servePortTaken(await serveStatus(cli))) {+ const listed = servePortTaken(await serveStatus(cli));+ starting = null;+ if (!listed || quitting) {child.kill("SIGTERM");+ forgetMarker();log("tailnet: tailscale serve did not take the port; listening on the tailnet instead");return null;}@@ -107,6 +171,7 @@ export function createTailnetShare({ check, allowed = () => true, spawn = spawnClog("tailnet: tailscale serve ended; listening on the tailnet instead");serving = null;httpsBroken = true;+ forgetMarker();void enqueue(reconcile);});return tailnetOrigin(name, HTTPS_PORT, true);@@ -114,7 +179,10 @@ export function createTailnetShare({ check, allowed = () => true, spawn = spawnCasync function reconcile() {const route = wanted;- if (!server || !route?.on || route.computers !== true || !allowed()) {+ await endLeftover();+ lastAllowed = allowed();+ if (quitting) return shown;+ if (!server || !route?.on || route.computers !== true || !lastAllowed) {await stopServing();if (server?.told) await tell(null);shown = OFF;@@ -133,6 +201,7 @@ export function createTailnetShare({ check, allowed = () => true, spawn = spawnCconst origin = serving? tailnetOrigin(name, HTTPS_PORT, true): ready && status.https && status.cli && !httpsBroken ? await startServing(status.cli, name, server.port) : null;+ if (quitting) return shown;const reply = await tell(origin ? { name, served: origin } : { name });const reached = reply?.origin ?? null;shown = { on: true, origin: reached, https: Boolean(origin), problem: reached ? null : ready ? "not-listening" : status.state };@@ -153,6 +222,10 @@ export function createTailnetShare({ check, allowed = () => true, spawn = spawnChttpsBroken = false;return enqueue(reconcile);},+ /** The organization's policy may have changed; a share that it now forbids closes, and one it allows again opens. */+ recheck() {+ return allowed() === lastAllowed ? Promise.resolve(shown) : enqueue(reconcile);+ },/** The server's answer, and its word when Tailscale's interface comes or goes. */receive(message) {if (message?.type !== "openmausbot:tailnet-share-state") return false;@@ -164,6 +237,11 @@ export function createTailnetShare({ check, allowed = () => true, spawn = spawnC/** The app is quitting: `tailscale serve` must not outlive the server it fronts. */stop() {wanted = null;+ quitting = true;+ try {+ starting?.kill("SIGTERM");+ } catch {+ }return stopServing();},};diff --git a/electron/tailnet-share.node-test.mjs b/electron/tailnet-share.node-test.mjsindex 6116e573da..546e474144 100644--- a/electron/tailnet-share.node-test.mjs+++ b/electron/tailnet-share.node-test.mjs@@ -2,22 +2,27 @@ import assert from "node:assert/strict";import { EventEmitter } from "node:events";import test from "node:test";-import { createTailnetShare, servePortTaken } from "./tailnet-share.mjs";+import { mkdtempSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";++import { createTailnetShare, remotePolicyAllows, servePortTaken } from "./tailnet-share.mjs";const NAME = "macmini.tail1234.ts.net";const route = (over = {}) => ({ on: true, since: 1, name: NAME, computers: true, ...over });-function world({ status = { state: "ready", name: NAME, addresses: ["100.101.102.103"], https: false, cli: "/usr/bin/tailscale" }, serveStatus = ["{}", '{"TCP":{"443":{"HTTPS":true}}}'], serveExits = false, allowed = () => true } = {}) {+function world({ status = { state: "ready", name: NAME, addresses: ["100.101.102.103"], https: false, cli: "/usr/bin/tailscale" }, serveStatus = ["{}", '{"TCP":{"443":{"HTTPS":true}}}'], serveExits = false, allowed = () => true, settleMs = 5, ...extra } = {}) {const w = { posted: [], spawned: [], children: [], checks: 0, statuses: 0 };w.share = createTailnetShare({check: async () => { w.checks++; return status; },allowed,- settleMs: 5,+ settleMs,answerMs: 50,+ ...extra,serveStatus: async () => serveStatus[Math.min(w.statuses++, serveStatus.length - 1)],spawn: (cli, args) => {w.spawned.push([cli, ...args]);- const child = Object.assign(new EventEmitter(), { killed: [], kill(signal) { child.killed.push(signal); setImmediate(() => child.emit("exit", null)); } });+ const child = Object.assign(new EventEmitter(), { pid: 4242, killed: [], kill(signal) { child.killed.push(signal); setImmediate(() => child.emit("exit", null)); } });w.children.push(child);if (serveExits) setImmediate(() => child.emit("exit", 1));return child;@@ -122,3 +127,72 @@ test("a new server port moves the serve; turning off stops it and clears the serassert.equal(w.posted.at(-1), null);assert.equal(w.share.state().on, false);});++const HTTPS = { state: "ready", name: NAME, addresses: [], https: true, cli: "/usr/bin/tailscale" };++test("the policy check fails closed until the saved policy has been read", () => {+ const client = (known, policy) => ({ policyKnown: () => known, policy: () => policy });+ assert.equal(remotePolicyAllows({ managed: false, client: null }), true, "a development build or a client of another computer has no policy of its own");+ assert.equal(remotePolicyAllows({ managed: true, client: null }), false, "packaged, before the managed client exists");+ assert.equal(remotePolicyAllows({ managed: true, client: client(false, null) }), false, "created, nothing read yet");+ assert.equal(remotePolicyAllows({ managed: true, client: client(true, null) }), true);+ assert.equal(remotePolicyAllows({ managed: true, client: client(true, { remoteAccess: true }) }), true);+ assert.equal(remotePolicyAllows({ managed: true, client: client(true, { remoteAccess: false }) }), false);+});++test("the share waits for the policy at launch, and closes and reopens when it changes", async () => {+ let open = false;+ const w = world({ status: HTTPS, allowed: () => open, serveStatus: ["{}", '{"TCP":{"443":{}}}', "{}", '{"TCP":{"443":{}}}'] });+ await w.share.attach(w.proc, 8799, route());+ assert.deepEqual([w.checks, w.spawned.length, w.posted.length], [0, 0, 0], "nothing before the policy is known");+ await w.share.recheck();+ assert.equal(w.checks, 0, "no change, no work");+ open = true;+ assert.equal((await w.share.recheck()).https, true);+ assert.equal(w.spawned.length, 1);+ open = false;+ assert.equal((await w.share.recheck()).on, false);+ assert.deepEqual(w.children[0].killed, ["SIGTERM"]);+ assert.equal(w.posted.at(-1), null, "the server closes its side too");+ open = true;+ assert.equal((await w.share.recheck()).on, true);+ assert.equal(w.spawned.length, 2);+});++test("quitting while serve is still settling ends it and tells the server nothing", async () => {+ const w = world({ status: HTTPS, settleMs: 5_000 });+ const attached = w.share.attach(w.proc, 8799, route());+ for (let i = 0; i < 100 && w.spawned.length === 0; i++) await new Promise((resolve) => setImmediate(resolve));+ await w.share.stop();+ await attached;+ assert.deepEqual(w.children[0].killed, ["SIGTERM"]);+ assert.deepEqual(w.posted, []);+});++test("a serve a crash left behind is ended at the next launch, even with the share off, and a reused pid is left alone", async () => {+ const dir = mkdtempSync(path.join(tmpdir(), "omb-tailnet-marker-"));+ const file = path.join(dir, "marker");+ try {+ const ours = "/usr/bin/tailscale serve --https=443 http://127.0.0.1:8799";+ const killed = [];+ let running = ours;+ writeFileSync(file, JSON.stringify({ pid: 777, port: 8799 }));+ const left = world({ markerFile: () => file, commandLine: async () => running, kill: (pid, signal) => { killed.push([pid, signal]); running = ""; } });+ await left.share.attach(left.proc, 8799, route({ computers: false }));+ assert.deepEqual(killed, [[777, "SIGTERM"]]);+ assert.equal(existsSync(file), false);++ writeFileSync(file, JSON.stringify({ pid: 778, port: 8799 }));+ const reused = world({ markerFile: () => file, commandLine: async () => "/usr/bin/vim notes.txt", kill: () => assert.fail("not ours") });+ await reused.share.attach(reused.proc, 8799, route({ computers: false }));+ assert.equal(existsSync(file), false);++ const noted = world({ status: HTTPS, markerFile: () => file });+ await noted.share.attach(noted.proc, 8799, route());+ assert.deepEqual(JSON.parse(readFileSync(file, "utf8")), { pid: 4242, port: 8799 });+ await noted.share.stop();+ assert.equal(existsSync(file), false, "a clean stop leaves nothing to clean up");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/scripts/control-omb.ts b/scripts/control-omb.tsindex 3b9c7e8be5..a2756f0bca 100644--- a/scripts/control-omb.ts+++ b/scripts/control-omb.ts@@ -175,7 +175,7 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, data// One log line per browser call and preview frame.if (parentEnv.OMB_BROWSER_TIMING === "1") childEnv.OMB_BROWSER_TIMING = "1";// A share on the tailnet (server/tailnet-listener.ts): a test names one of this machine's own addresses as its stand-in.- for (const key of ["OMB_TAILNET_NAME", "OMB_TAILNET_ADDRESSES"]) if (parentEnv[key]) childEnv[key] = parentEnv[key];+ for (const key of ["OMB_TAILNET_NAME", "OMB_TAILNET_ADDRESSES", "OMB_TEST_TAILNET_STAND_IN"]) if (parentEnv[key]) childEnv[key] = parentEnv[key];// Warm summaries' minutes as seconds (server/warm-summary.ts), and the switch that turns them off.for (const key of ["OMB_WARM_SUMMARY_TIME_SCALE", "OMB_WARM_SUMMARY"]) if (parentEnv[key]) childEnv[key] = parentEnv[key];// A loopback fake only: the key never reaches a real provider.diff --git a/server/cli-lifecycle.test.ts b/server/cli-lifecycle.test.tsindex d35dd0c903..1b12d3cb55 100644--- a/server/cli-lifecycle.test.ts+++ b/server/cli-lifecycle.test.ts@@ -132,12 +132,12 @@ describe("CLI startup lifecycle", () => {it("starts the server on the tailnet when tailscale serve can't front it, with nothing of Tailscale's to stop", async () => {mocks.tailscaleServe.mockResolvedValue({ failure: "https-not-enabled" });- mocks.tailnetListenFallback.mockReturnValue({ origin: "http://fixture.tail.ts.net:18451", env: { OMB_TAILNET_NAME: "fixture.tail.ts.net", OMB_TAILNET_ADDRESSES: "100.64.0.7" }, line: "tailscale: listening" });+ mocks.tailnetListenFallback.mockReturnValue({ origin: "http://fixture.tail.ts.net:18451", env: { OMB_TAILNET_NAME: "fixture.tail.ts.net" }, line: "tailscale: listening" });let started: NodeJS.ProcessEnv = {};mocks.spawn.mockImplementation((_command: string, _args: string[], spawned: { env: NodeJS.ProcessEnv }) => { started = spawned.env; throw new Error("Fixture spawn failure"); });const log = vi.fn();await expect(runServe({ ...options, tailscale: true }, log)).rejects.toThrow("Fixture spawn failure");- expect(started).toMatchObject({ OMB_TAILNET_NAME: "fixture.tail.ts.net", OMB_TAILNET_ADDRESSES: "100.64.0.7", OMB_PUBLIC_URL: "http://fixture.tail.ts.net:18451" });+ expect(started).toMatchObject({ OMB_TAILNET_NAME: "fixture.tail.ts.net", OMB_PUBLIC_URL: "http://fixture.tail.ts.net:18451" });expect(log).toHaveBeenCalledWith("tailscale: listening");expect(mocks.tailscaleStop).not.toHaveBeenCalled();});diff --git a/server/tailnet-listener.e2e.test.ts b/server/tailnet-listener.e2e.test.tsindex efbabc768b..f45c6bba98 100644--- a/server/tailnet-listener.e2e.test.ts+++ b/server/tailnet-listener.e2e.test.ts@@ -36,7 +36,7 @@ async function untilShared(port: number, host: string) {describe.skipIf(!standIn)("a server shared on the tailnet", () => {it("answers its tailnet name on the tailnet address, pairs another computer there, and gives that computer no owner trust", async () => {- const fixture = await launchVerificationServer({ OMB_DEV_TRUST_LOCAL_BROWSER: "0", OMB_TAILNET_NAME: NAME, OMB_TAILNET_ADDRESSES: standIn! });+ const fixture = await launchVerificationServer({ OMB_DEV_TRUST_LOCAL_BROWSER: "0", OMB_TAILNET_NAME: NAME, OMB_TAILNET_ADDRESSES: standIn!, OMB_TEST_TAILNET_STAND_IN: standIn! });const port = Number(new URL(fixture.info.url).port);const host = `${NAME}:${port}`;const origin = `http://${host}`;@@ -86,7 +86,7 @@ describe.skipIf(!standIn)("a server shared on the tailnet", () => {const owner = "o".repeat(43);const realFetch = globalThis.fetch;globalThis.fetch = (input, init = {}) => realFetch(input, { ...init, headers: { ...Object.fromEntries(new Headers(init.headers)), "x-openmausbot-desktop-owner": owner } });- const fixture = await launchVerificationServer({ OMB_TEST_DESKTOP_OWNER_TOKEN: owner, OMB_TEST_DESKTOP_TAILNET_SHARE: JSON.stringify({ name: NAME, addresses: [standIn] }) });+ const fixture = await launchVerificationServer({ OMB_TEST_DESKTOP_OWNER_TOKEN: owner, OMB_TEST_TAILNET_STAND_IN: standIn!, OMB_TEST_DESKTOP_TAILNET_SHARE: JSON.stringify({ name: NAME, addresses: [standIn] }) });const port = Number(new URL(fixture.info.url).port);const host = `${NAME}:${port}`;try {diff --git a/server/tailnet-listener.test.ts b/server/tailnet-listener.test.tsindex 01b3462416..2497fb9b62 100644--- a/server/tailnet-listener.test.ts+++ b/server/tailnet-listener.test.ts@@ -1,7 +1,9 @@import { request, type Server } from "node:http";+import { connect, type Socket } from "node:net";import { afterEach, describe, expect, it } from "vitest";import { createTailnetShare, hostAllowed, readTailnetShare, tailnetPeerAllowed, tailnetShareFromEnv } from "./tailnet-listener.ts";+import { createUpgrades } from "./routes/upgrades.ts";import { freePortBlock } from "./testing/ports.ts";const NAME = "macmini.tail1234.ts.net";@@ -19,9 +21,15 @@ describe("a tailnet share's configuration", () => {null, "x", { name: "macmini.example.com" }, { name: NAME, served: "https://evil.example.com" }, { name: NAME, served: "http://macmini.tail1234.ts.net" },{ name: NAME, served: "https://macmini.tail1234.ts.net/pair" }, { name: NAME, addresses: ["0.0.0.0"] }, { name: NAME, addresses: ["::"] },{ name: NAME, addresses: ["127.0.0.1"] }, { name: NAME, addresses: ["macmini.local"] }, { name: NAME, addresses: [] },+ { name: NAME, addresses: ["::0"] }, { name: NAME, addresses: ["0::"] }, { name: NAME, addresses: ["0:0::0"] }, { name: NAME, addresses: ["192.168.1.20"] }, { name: NAME, addresses: ["fd00::1"] },]) expect(readTailnetShare(input), JSON.stringify(input)).toBeNull();});+ it("takes a test rig's stand-in address only when named exactly", () => {+ expect(readTailnetShare({ name: NAME, addresses: ["192.168.1.20"] }, "192.168.1.20")).toEqual({ name: NAME, addresses: ["192.168.1.20"] });+ expect(readTailnetShare({ name: NAME, addresses: ["192.168.1.21"] }, "192.168.1.20")).toBeNull();+ });+it("reads the environment openmausbot serve --tailscale sets", () => {expect(tailnetShareFromEnv({})).toBeNull();expect(tailnetShareFromEnv({ OMB_TAILNET_NAME: NAME, OMB_TAILNET_ADDRESSES: "100.101.102.103, fd7a:115c:a1e0::1" }))@@ -86,6 +94,39 @@ describe("the listeners", () => {await expect(ask(port, `${NAME}:${port}`)).rejects.toThrow();});+ it("ends an open WebSocket when the share closes, and the next change isn't held up by it", async () => {+ const port = await freePortBlock([0]);+ const upgrades = createUpgrades();+ upgrades.route(() => true);+ const accepted: Socket[] = [];+ share = createTailnetShare({ port, attach: (server, handle) => upgrades.attach(server, handle), handle: async (req) => {+ const upgrade = upgrades.pending(req)!;+ upgrade.release();+ upgrade.socket.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n");+ accepted.push(upgrade.socket);+ } });+ await share.start();+ await share.apply({ name: NAME, addresses: ["127.0.0.1"] });+ const open = () => new Promise<{ client: Socket; line: string }>((resolve, reject) => {+ const client = connect(port, "127.0.0.1", () => client.write(`GET /socket HTTP/1.1\r\nHost: ${NAME}:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n`));+ client.once("data", (data) => resolve({ client, line: String(data).split("\r\n")[0]! }));+ client.once("error", reject);+ });+ const held = await open();+ expect(held.line).toContain("101");+ const ended = new Promise<void>((resolve) => held.client.once("close", () => resolve()));++ await share.apply(null);+ await ended;+ expect(accepted[0]!.destroyed).toBe(true);++ await share.apply({ name: NAME, addresses: ["127.0.0.1"] });+ expect(share.state().listening).toEqual(["127.0.0.1"]);+ const again = await open();+ expect(again.line).toContain("101");+ again.client.destroy();+ });+it("says why nothing listens, and links to the served HTTPS origin without binding", async () => {const port = await freePortBlock([0]);share = createTailnetShare({ port: port, handle: async () => {}, attach: () => {}, interfaces: () => ({ en0: [{ address: "192.168.1.20", family: "IPv4", internal: false, netmask: "", mac: "", cidr: null }] }) });diff --git a/server/tailnet-listener.ts b/server/tailnet-listener.tsindex 5ade0e6029..ac201aea39 100644--- a/server/tailnet-listener.ts+++ b/server/tailnet-listener.ts@@ -1,7 +1,7 @@// This server on the tailnet: either `tailscale serve` fronts it with HTTPS (nothing is bound here, the origin goes into// links), or it listens on each tailnet address itself.import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";-import { isIP } from "node:net";+import { isIP, type Socket } from "node:net";import { networkInterfaces } from "node:os";import { IDLE_HTTP_SERVER } from "./due-timer.ts";@@ -17,8 +17,7 @@ export interface TailnetShareState {}const FOLLOW_MS = 15_000;--const notShareable = (address: string) => /^(?:0\.0\.0\.0|::|0:0:0:0:0:0:0:0)$/.test(address) || address.startsWith("127.") || address === "::1";+const CLOSE_MS = 1_000;/** A served origin must be `https://<name>[:port]` and nothing more. */function servedOrigin(name: string, value: unknown): string | null {@@ -32,8 +31,9 @@ function servedOrigin(name: string, value: unknown): string | null {}}-/** Fails closed: anything malformed is no share at all. */-export function readTailnetShare(input: unknown): TailnetShareConfig | null {+/** Fails closed: anything malformed is no share at all, and an address must be Tailscale's. `standIn` is a test rig's own+ * address playing a tailnet one, where CI has no Tailscale. */+export function readTailnetShare(input: unknown, standIn = process.env.OMB_TEST_TAILNET_STAND_IN): TailnetShareConfig | null {if (!input || typeof input !== "object") return null;const raw = input as Record<string, unknown>;const name = typeof raw.name === "string" ? raw.name.trim().toLowerCase().replace(/\.$/, "") : "";@@ -45,11 +45,11 @@ export function readTailnetShare(input: unknown): TailnetShareConfig | null {if (raw.addresses === undefined || raw.addresses === "interface") return { name, addresses: "interface" };if (!Array.isArray(raw.addresses) || raw.addresses.length === 0 || raw.addresses.length > 8) return null;const addresses = raw.addresses.map((address) => bareAddress(String(address)));- return addresses.every((address) => isIP(address) !== 0 && !notShareable(address)) ? { name, addresses: [...new Set(addresses)] } : null;+ return addresses.every((address) => isIP(address) !== 0 && (inTailscaleRange(address) || address === standIn)) ? { name, addresses: [...new Set(addresses)] } : null;}-/** `OMB_TAILNET_NAME` with `OMB_TAILNET_SERVED` (the HTTPS origin `tailscale serve` gives it) or `OMB_TAILNET_ADDRESSES`- * (a comma list; unset follows Tailscale's interface). `openmausbot serve --tailscale` sets them. */+/** `OMB_TAILNET_NAME`, set by `openmausbot serve --tailscale`, follows Tailscale's interface. With `OMB_TAILNET_SERVED`+ * (the HTTPS origin `tailscale serve` gives it) nothing is bound; `OMB_TAILNET_ADDRESSES` (a comma list) pins the addresses. */export function tailnetShareFromEnv(env: NodeJS.ProcessEnv): TailnetShareConfig | null {if (!env.OMB_TAILNET_NAME) return null;const addresses = env.OMB_TAILNET_ADDRESSES?.split(",").map((part) => part.trim()).filter(Boolean);@@ -87,6 +87,7 @@ export function createTailnetShare(options: TailnetShareOptions) {let started = false;let desired: TailnetShareConfig | null = null;let listeners = new Map<string, Server>();+ const connections = new WeakMap<Server, Set<Socket>>();let allowed: ReadonlySet<string> = new Set();let error: string | null = null;let timer: ReturnType<typeof setInterval> | null = null;@@ -111,16 +112,25 @@ export function createTailnetShare(options: TailnetShareOptions) {return options.handle(req, res);};- const close = (server: Server) => new Promise<void>((resolve) => {- server.closeAllConnections?.();- server.close(() => resolve());- });+ /** Node's closeAllConnections skips upgraded sockets and close() waits for them, so an open WebSocket would outlive the+ * share and hold up every later change. */+ const close = (server: Server) => {+ for (const socket of connections.get(server) ?? []) socket.destroy();+ return Promise.race([+ new Promise<void>((resolve) => server.close(() => resolve())),+ new Promise<void>((resolve) => setTimeout(resolve, CLOSE_MS).unref()),+ ]);+ };function open(address: string): Promise<Server> {const server = createServer(IDLE_HTTP_SERVER, guarded);options.attach(server, guarded);+ const held = new Set<Socket>();+ connections.set(server, held);server.on("connection", (socket) => {- if (!tailnetPeerAllowed(socket.remoteAddress, [...listeners.keys()])) socket.destroy();+ if (!tailnetPeerAllowed(socket.remoteAddress, [...listeners.keys()])) return void socket.destroy();+ held.add(socket);+ socket.once("close", () => held.delete(socket));});return new Promise((resolve, reject) => {server.once("error", reject);diff --git a/server/tailscale.test.ts b/server/tailscale.test.tsindex 1a7e8ecfef..49acaf8fbf 100644--- a/server/tailscale.test.ts+++ b/server/tailscale.test.ts@@ -40,7 +40,8 @@ describe("serve --tailscale without HTTPS", () => {it("listens on this machine's own tailnet addresses at http://<name>:<port>, and says how to get https", () => {const fallback = tailnetListenFallback("https-not-enabled", status, 8799, interfaces);expect(fallback?.origin).toBe("http://nuc.tail1234.ts.net:8799");- expect(fallback?.env).toEqual({ OMB_TAILNET_NAME: "nuc.tail1234.ts.net", OMB_TAILNET_ADDRESSES: "100.70.0.9,fd7a:115c:a1e0::9" });+ // The name alone: the server follows Tailscale's interface, so a restart of Tailscale needs no restart here.+ expect(fallback?.env).toEqual({ OMB_TAILNET_NAME: "nuc.tail1234.ts.net" });expect(fallback?.line).toContain("login.tailscale.com/admin/dns");expect(tailnetListenFallback("needs-operator", status, 8799, interfaces)?.line).toContain("--operator=$USER");});diff --git a/server/tailscale.ts b/server/tailscale.tsindex da658f1ebe..4283ed1c5e 100644--- a/server/tailscale.ts+++ b/server/tailscale.ts@@ -121,7 +121,7 @@ const LISTEN_INSTEAD: Partial<Record<TailscaleFailure, [why: string, fix: string* name, or no Tailscale interface here (userspace networking, as in most containers).*/export function tailnetListenFallback(failure: TailscaleFailure, status: TailscaleStatus, port: number, interfaces: NodeJS.Dict<Array<{ address: string }>> = networkInterfaces()):- { origin: string; env: { OMB_TAILNET_NAME: string; OMB_TAILNET_ADDRESSES: string }; line: string } | null {+ { origin: string; env: { OMB_TAILNET_NAME: string }; line: string } | null {const reason = LISTEN_INSTEAD[failure];const local = tailnetInterfaceAddresses(interfaces);const addresses = status.addresses.filter((address) => local.includes(address.toLowerCase()));@@ -129,7 +129,7 @@ export function tailnetListenFallback(failure: TailscaleFailure, status: Tailscaconst origin = tailnetOrigin(status.dnsName, port);return {origin,- env: { OMB_TAILNET_NAME: status.dnsName, OMB_TAILNET_ADDRESSES: addresses.join(",") },+ env: { OMB_TAILNET_NAME: status.dnsName },line: `tailscale: ${reason[0]}, so this server listens on ${origin} itself (only your tailnet can reach it, and WireGuard encrypts it). For an https:// address, ${reason[1]}.`,};}