Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
A server can be shared on the tailnet, and serve --tailscale no longer needs HTTPS
Milind Soni2b42d1d3164f
diff --git a/electron/tailnet.d.mts b/electron/tailnet.d.mtsnew file mode 100644index 0000000000..86beea7bd9--- /dev/null+++ b/electron/tailnet.d.mts@@ -0,0 +1,17 @@+export type TailscaleState = "ready" | "signed-out" | "not-running" | "needs-approval";+export interface TailscaleStatusJson {+ state: TailscaleState;+ name: string | null;+ addresses: string[];+ https: boolean;+}++export declare const bareAddress: (address: string | undefined | null) => string;+export declare function inTailscaleRange(address: string | undefined | null): boolean;+export declare function isTailnetName(host: string | undefined | null): boolean;+export declare const isTailnetHost: (host: string | undefined | null) => boolean;+export declare function tailnetInterfaceAddresses(interfaces: NodeJS.Dict<Array<{ address: string }>>): string[];+export declare const onTailnet: (interfaces: NodeJS.Dict<Array<{ address: string }>>) => boolean;+export declare function readTailscaleStatusJson(stdout: string): TailscaleStatusJson | null;+export declare function tailnetOrigin(name: string, port: number, https?: boolean): string;+export declare function tailnetHosts(input: { name: string | null; addresses?: string[]; port: number }): Set<string>;diff --git a/electron/tailnet.mjs b/electron/tailnet.mjsnew file mode 100644index 0000000000..f37081ce8c--- /dev/null+++ b/electron/tailnet.mjs@@ -0,0 +1,100 @@+// What Tailscale says about this computer, and the exact names and addresses a share on the tailnet answers to. Runs+// nothing and imports nothing, so the window's bundle can read it too.++const TAILSCALE_V6 = /^fd7a:115c:a1e0:/i;+const LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";+const TAILNET_NAME = new RegExp(`^(?=.{1,253}$)${LABEL}(?:\\.${LABEL})*\\.ts\\.net$`);++/** An address as a socket reports it, without the IPv4-mapped prefix, zone or brackets. */+export const bareAddress = (address) => String(address ?? "").trim().replace(/^\[|\]$/g, "").replace(/^::ffff:(?=\d)/i, "").replace(/%.*$/, "").toLowerCase();++function ipv4(address) {+ const parts = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(address);+ if (!parts) return null;+ const octets = parts.slice(1).map(Number);+ return octets.some((octet) => octet > 255) ? null : octets;+}++/** Tailscale's own ranges: 100.64.0.0/10 and fd7a:115c:a1e0::/48. 100.64/10 is RFC 6598 shared space that carrier NAT+ * and other VPNs use too, so on its own it never proves a tailnet. */+export function inTailscaleRange(address) {+ const value = bareAddress(address);+ const v4 = ipv4(value);+ if (v4) return v4[0] === 100 && v4[1] >= 64 && v4[1] <= 127;+ return TAILSCALE_V6.test(value);+}++/** A MagicDNS name, like `macmini.tail1234.ts.net`; a trailing dot is allowed. */+export function isTailnetName(host) {+ return TAILNET_NAME.test(String(host ?? "").trim().toLowerCase().replace(/\.$/, ""));+}++/** A host only a tailnet reaches: a MagicDNS name or an address in Tailscale's ranges. */+export const isTailnetHost = (host) => isTailnetName(host) || inTailscaleRange(host);++/** Addresses on Tailscale's own interface: `tailscale0` on Linux, "Tailscale" on Windows, and on macOS the utun that+ * carries a fd7a:115c:a1e0::/48 address. IPv4 first. */+export function tailnetInterfaceAddresses(interfaces) {+ const found = [];+ for (const [name, entries = []] of Object.entries(interfaces ?? {})) {+ const list = entries ?? [];+ if (!/^tailscale/i.test(name) && !list.some((entry) => TAILSCALE_V6.test(entry?.address ?? ""))) continue;+ for (const entry of list) {+ const address = bareAddress(entry?.address);+ if (inTailscaleRange(address) && !found.includes(address)) found.push(address);+ }+ }+ return found.sort((a, b) => Number(a.includes(":")) - Number(b.includes(":")));+}++export const onTailnet = (interfaces) => tailnetInterfaceAddresses(interfaces).length > 0;++/**+ * One `tailscale status --json`, read: `state` is "ready" (signed in and connected), "signed-out", "not-running" or+ * "needs-approval"; `name` this computer's MagicDNS name; `addresses` its tailnet addresses; `https` whether the tailnet+ * hands out certificates (`CertDomains`, or the `https` capability in `Self.CapMap`), without which `tailscale serve`+ * waits on an enablement link. Null when the text is not that JSON.+ */+export function readTailscaleStatusJson(stdout) {+ let parsed;+ try {+ parsed = JSON.parse(String(stdout ?? ""));+ } catch {+ return null;+ }+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;+ const self = parsed.Self && typeof parsed.Self === "object" ? parsed.Self : {};+ const dns = typeof self.DNSName === "string" ? self.DNSName.trim().toLowerCase().replace(/\.$/, "") : "";+ const backend = typeof parsed.BackendState === "string" ? parsed.BackendState : "";+ const state = backend === "Running" ? "ready" : backend === "NeedsMachineAuth" ? "needs-approval" : backend === "Stopped" || backend === "Starting" || backend === "NoState" ? "not-running" : "signed-out";+ const addresses = (Array.isArray(self.TailscaleIPs) ? self.TailscaleIPs : []).map(bareAddress).filter(inTailscaleRange);+ const certDomains = Array.isArray(parsed.CertDomains) && parsed.CertDomains.some((domain) => typeof domain === "string" && domain);+ const capability = self.CapMap && typeof self.CapMap === "object" && Object.hasOwn(self.CapMap, "https");+ return { state, name: isTailnetName(dns) ? dns : null, addresses: addresses.sort((a, b) => Number(a.includes(":")) - Number(b.includes(":"))), https: Boolean(certDomains || capability) };+}++const authority = (host, port) => (host.includes(":") ? `[${host}]` : host) + (port ? `:${port}` : "");++/** The address another computer opens: `https://<name>` when `tailscale serve` fronts this one with HTTPS, else+ * `http://<name>:<port>` (inside WireGuard, so encrypted despite the http). */+export function tailnetOrigin(name, port, https = false) {+ if (https) return port && port !== 443 ? `https://${name}:${port}` : `https://${name}`;+ return `http://${authority(name, port)}`;+}++/**+ * Security: the only Host headers a listener on the tailnet answers, exactly: its MagicDNS name and the addresses it is+ * bound to, each with its port. A page that rebinds its own name to a tailnet address sends that name, so it is refused.+ */+export function tailnetHosts({ name, addresses = [], port }) {+ const hosts = new Set();+ if (isTailnetName(name)) {+ const bare = name.toLowerCase().replace(/\.$/, "");+ hosts.add(authority(bare, port));+ }+ for (const address of addresses) {+ const value = bareAddress(address);+ if (value) hosts.add(authority(value, port));+ }+ return hosts;+}diff --git a/electron/tailnet.test.mjs b/electron/tailnet.test.mjsnew file mode 100644index 0000000000..340357647f--- /dev/null+++ b/electron/tailnet.test.mjs@@ -0,0 +1,84 @@+import { describe, expect, it } from "vitest";++import { bareAddress, inTailscaleRange, isTailnetHost, isTailnetName, onTailnet, readTailscaleStatusJson, tailnetHosts, tailnetInterfaceAddresses, tailnetOrigin } from "./tailnet.mjs";++/** The shape `tailscale status --json` prints (Tailscale 1.7x), trimmed to what is read. */+const status = (overrides = {}, self = {}) => JSON.stringify({+ BackendState: "Running",+ MagicDNSSuffix: "tail1234.ts.net",+ CertDomains: ["macmini.tail1234.ts.net"],+ Self: { DNSName: "macmini.tail1234.ts.net.", TailscaleIPs: ["fd7a:115c:a1e0::1234:abcd", "100.101.102.103"], ...self },+ ...overrides,+});++const v4 = (address) => ({ address, family: "IPv4", internal: false });+const v6 = (address) => ({ address, family: "IPv6", internal: false });++describe("reading tailscale status --json", () => {+ it("finds the MagicDNS name, the tailnet addresses (IPv4 first) and whether HTTPS certificates are on", () => {+ expect(readTailscaleStatusJson(status())).toEqual({+ state: "ready", name: "macmini.tail1234.ts.net", addresses: ["100.101.102.103", "fd7a:115c:a1e0::1234:abcd"], https: true,+ });+ });++ it("reads HTTPS from the https capability when CertDomains is absent, and off when neither says so", () => {+ expect(readTailscaleStatusJson(status({ CertDomains: null }, { CapMap: { https: null, "funnel": null } }))?.https).toBe(true);+ expect(readTailscaleStatusJson(status({ CertDomains: [] }))?.https).toBe(false);+ });++ it("names each state the row explains", () => {+ expect(readTailscaleStatusJson(status({ BackendState: "NeedsLogin" }))?.state).toBe("signed-out");+ expect(readTailscaleStatusJson(status({ BackendState: "Stopped" }))?.state).toBe("not-running");+ expect(readTailscaleStatusJson(status({ BackendState: "NeedsMachineAuth" }))?.state).toBe("needs-approval");+ });++ it("drops a name that is not a MagicDNS name and addresses outside Tailscale's ranges", () => {+ const read = readTailscaleStatusJson(status({}, { DNSName: "macmini.example.com.", TailscaleIPs: ["192.168.1.20", "100.64.0.7"] }));+ expect(read?.name).toBeNull();+ expect(read?.addresses).toEqual(["100.64.0.7"]);+ });++ it("is null for the GUI's startup text and for anything not an object", () => {+ for (const text of ["", "Tailscale started", "[]", "null", "{"]) expect(readTailscaleStatusJson(text)).toBeNull();+ });+});++describe("Tailscale's interface and ranges", () => {+ it("lists addresses only on Tailscale's own interface, never a bare 100.64/10 address on another one", () => {+ const interfaces = {+ en0: [v4("192.168.1.20")],+ utun4: [v4("100.101.102.103"), v6("fd7a:115c:a1e0::1234:abcd"), v6("fe80::1%utun4")],+ utun2: [v4("100.96.0.5")],+ tailscale0: [v4("100.70.0.9")],+ };+ expect(tailnetInterfaceAddresses(interfaces)).toEqual(["100.101.102.103", "100.70.0.9", "fd7a:115c:a1e0::1234:abcd"]);+ expect(onTailnet({ en0: [v4("192.168.1.20")], utun2: [v4("100.96.0.5")] })).toBe(false);+ });++ it("knows Tailscale's ranges and MagicDNS names", () => {+ expect(inTailscaleRange("100.64.0.1")).toBe(true);+ expect(inTailscaleRange("::ffff:100.127.255.254")).toBe(true);+ expect(inTailscaleRange("100.128.0.1")).toBe(false);+ expect(inTailscaleRange("[fd7a:115c:a1e0::1]")).toBe(true);+ expect(inTailscaleRange("fd00::1")).toBe(false);+ expect(isTailnetName("MacMini.tail1234.ts.net.")).toBe(true);+ for (const host of ["ts.net", "evil.ts.net.example.com", "a..ts.net", "-x.ts.net", "macmini.local"]) expect(isTailnetName(host)).toBe(false);+ expect(isTailnetHost("100.101.102.103")).toBe(true);+ expect(isTailnetHost("192.168.1.20")).toBe(false);+ expect(bareAddress("::ffff:100.101.102.103")).toBe("100.101.102.103");+ });+});++describe("what a share answers to", () => {+ it("builds the address another computer opens", () => {+ expect(tailnetOrigin("macmini.tail1234.ts.net", 8799)).toBe("http://macmini.tail1234.ts.net:8799");+ expect(tailnetOrigin("macmini.tail1234.ts.net", 443, true)).toBe("https://macmini.tail1234.ts.net");+ expect(tailnetOrigin("macmini.tail1234.ts.net", 8443, true)).toBe("https://macmini.tail1234.ts.net:8443");+ });++ it("accepts exactly the name and the bound addresses with their port", () => {+ const hosts = tailnetHosts({ name: "macmini.tail1234.ts.net", addresses: ["100.101.102.103", "fd7a:115c:a1e0::1"], port: 8799 });+ expect([...hosts].sort()).toEqual(["100.101.102.103:8799", "[fd7a:115c:a1e0::1]:8799", "macmini.tail1234.ts.net:8799"]);+ expect(tailnetHosts({ name: "evil.example.com", addresses: [], port: 8799 }).size).toBe(0);+ });+});diff --git a/scripts/control-omb.ts b/scripts/control-omb.tsindex d4f9a4a3da..3b9c7e8be5 100644--- a/scripts/control-omb.ts+++ b/scripts/control-omb.ts@@ -174,6 +174,8 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, dataif (parentEnv.OMB_TEST_INTERNAL_CAPABILITY_KEY) childEnv.OMB_TEST_INTERNAL_CAPABILITY_KEY = parentEnv.OMB_TEST_INTERNAL_CAPABILITY_KEY;// 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];// 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.@@ -238,6 +240,7 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, datachildEnv.OMB_TEST_DESKTOP_OWNER_TOKEN = parentEnv.OMB_TEST_DESKTOP_OWNER_TOKEN;childEnv.OMB_DESKTOP_PARENT = "1";if (parentEnv.OMB_TEST_DESKTOP_PAGES_ACCESS) childEnv.OMB_TEST_DESKTOP_PAGES_ACCESS = parentEnv.OMB_TEST_DESKTOP_PAGES_ACCESS;+ if (parentEnv.OMB_TEST_DESKTOP_TAILNET_SHARE) childEnv.OMB_TEST_DESKTOP_TAILNET_SHARE = parentEnv.OMB_TEST_DESKTOP_TAILNET_SHARE;}// The driver record the app hands its own server: without it, no server may use this computer.if (parentEnv.OMB_TEST_DESKTOP_CUA_CONNECTION) childEnv.OMB_TEST_DESKTOP_CUA_CONNECTION = parentEnv.OMB_TEST_DESKTOP_CUA_CONNECTION;diff --git a/server/cli.ts b/server/cli.tsindex 2682c18613..6eb9d609e5 100644--- a/server/cli.ts+++ b/server/cli.ts@@ -34,7 +34,7 @@ import { runSentinelCli } from "./sentinel/cli.ts";import { runFleetCommand, type FleetInput } from "./fleet-cli.ts";import { startFleetAgent } from "./fleet-agent.ts";import { fleetLayout } from "./fleet.ts";-import { clearLeftoverTailscaleServe, explainTailscaleFailure, tailscaleServe, tailscaleStatus, type TailscaleStatus } from "./tailscale.ts";+import { clearLeftoverTailscaleServe, explainTailscaleFailure, tailnetListenFallback, tailscaleServe, tailscaleStatus, type TailscaleStatus } from "./tailscale.ts";import { defaultSetupIo, SetupCancelled, type SetupIo } from "./cli-prompts.ts";import { HEADLESS_VERB_NAMES, usage } from "./cli-usage.ts";import { normalizePhoneOrigin, phonePairingInstructions, runPhoneSetup } from "./cli-phone-setup.ts";@@ -755,11 +755,11 @@ export async function runServe(options: CliOptions, log: (line: string) => void}if (tailscale) {const served = await tailscaleServe(tailscale, options.port, { dataDir: options.dataDir, otherServer: answersAsMausBot });- if (!("failure" in served)) tailscaleShare = served;- if (startupCancelled) throw new SetupCancelled();- if ("failure" in served) throw new Error(`--tailscale: ${explainTailscaleFailure(served.failure)}`);- publicUrl = served.origin;- log(`tailscale: serving https://${tailscale.dnsName} → http://127.0.0.1:${options.port} (only your tailnet can reach it)`);+ const listening = "failure" in served ? tailnetListenFallback(served.failure, tailscale, options.port) : null;+ tailscaleShare = "failure" in served ? listening && { origin: listening.origin, stop: async () => {} } : served;+ if (startupCancelled || !tailscaleShare) throw startupCancelled ? new SetupCancelled() : new Error(`--tailscale: ${explainTailscaleFailure("failure" in served ? served.failure : "unknown")}`);+ Object.assign(env, listening?.env); publicUrl = tailscaleShare.origin;+ log(listening?.line ?? `tailscale: serving https://${tailscale.dnsName} → http://127.0.0.1:${options.port} (only your tailnet can reach it)`);}if (startupCancelled) throw new SetupCancelled();if (publicUrl) env.OMB_PUBLIC_URL = publicUrl;diff --git a/server/index.ts b/server/index.tsindex deb4b22ca0..7c6ca4717a 100644--- a/server/index.ts+++ b/server/index.ts@@ -530,7 +530,7 @@ import { applyPendingWorkspaceRestore, readLastWorkspaceRestore, type WorkspaceRimport { repairMovedWorkspacePaths } from "./moved-paths-repair.ts";import { createCustomDomainVerifier, customDomainIpv4, normalizeCustomDomain } from "./custom-domain.ts";import { allowedScopes, createEmailSignIn, parseAllowList } from "./account-signin.ts";-import { pairingLinkBase, signInMailTarget } from "./pairing-base.ts"; import { lanUrl, listenHost } from "./lan-address.ts";+import { pairingLinkBase, signInMailTarget } from "./pairing-base.ts"; import { lanUrl, listenHost } from "./lan-address.ts"; import { createTailnetShare } from "./tailnet-listener.ts";import { ProviderAuthSessions } from "./provider-auth-sessions.ts";import {clearSessionCookie,@@ -777,7 +777,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 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 cfg = loadConfig();const hostedModels = hostedModelPolicy(DATA_DIR);const providerConfigs = () => hostedModels ? hostedModels.configs() : instanceConfigs(cfg);@@ -801,7 +801,7 @@ function savedCustomDomain(): string | null {try { return normalizeCustomDomain(cfg.customDomain); }catch { return null; }}-function publicUrl(): string | null { return savedCustomDomain() ?? FALLBACK_PUBLIC_URL ?? lanUrl(PORT); }+function publicUrl(): string | null { return savedCustomDomain() ?? FALLBACK_PUBLIC_URL ?? tailnetShare.origin() ?? lanUrl(PORT); }function customDomainStatus() {return {customDomain: savedCustomDomain(), publicUrl: publicUrl(), fallbackUrl: FALLBACK_PUBLIC_URL,@@ -1418,7 +1418,7 @@ type UtilityParentPort = {postMessage(message: object): void;};// Only Electron's utility process supplies parentPort, private to the desktop main process; plain Node leaves it absent.-const utilityParentPort = (process as NodeJS.Process & { parentPort?: UtilityParentPort }).parentPort;+const utilityParentPort = (process as NodeJS.Process & { parentPort?: UtilityParentPort }).parentPort; utilityParentPort?.on("message", (event) => void tailnetShare.receive(event.data, (answer) => utilityParentPort.postMessage(answer)));type DesktopPrivateMessage = BrowserCleanupWireRequest | import("./login-handoff.ts").LoginHandoffResult | {type: "openmausbot:browser-control";botId: string;@@ -15496,7 +15496,7 @@ if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATAmaintenance: () => workspaceMaintenance.active || providerFleetReloading || providerAuthSessions.active || browserEngineInstall !== null } }));server.listen(PORT, listenHost(server), async () => {- companyRuntimeReady();+ companyRuntimeReady(); void tailnetShare.start(process.env);console.log(`openmausbot server on http://127.0.0.1:${PORT}`);personWaits.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });void afterFirstEngineRead().then(() => { if (builtInBrowserEnabled(cfg)) chromeLauncher.start(); });@@ -15577,7 +15577,7 @@ const gracefulShutdown = createGracefulShutdown({cacheKeepWarm.dispose(); warmSummaries.dispose();skillReview.stop();webhookIngress?.server.close();- tunnelListener?.close(); stopCloudHomeConnectedApps();+ tunnelListener?.close(); void tailnetShare.close(); stopCloudHomeConnectedApps();},async () => { await managedDesktop.close(); await registry.disposeAll(); },async () => { await dataEngine.closeAll().catch((error) => console.warn("data: close failed", error)); },diff --git a/server/tailnet-listener.e2e.test.ts b/server/tailnet-listener.e2e.test.tsnew file mode 100644index 0000000000..efbabc768b--- /dev/null+++ b/server/tailnet-listener.e2e.test.ts@@ -0,0 +1,104 @@+// A real server shared on the tailnet. CI has no Tailscale, so one of the runner's own non-loopback addresses stands in+// for this computer's tailnet address: the server listens there, beside its loopback listener, exactly as it would on+// 100.x, and the test dials it as another computer on the tailnet would (by the MagicDNS name in the Host header).+import { request } from "node:http";+import { networkInterfaces } from "node:os";+import { describe, expect, it } from "vitest";++import { launchVerificationServer } from "../scripts/control-omb.ts";++const NAME = "fixture.tail1234.ts.net";++/** The runner's first ordinary IPv4 address: not loopback, not link-local. */+const standIn = Object.values(networkInterfaces()).flat().find((entry) => entry?.family === "IPv4" && !entry.internal && !entry.address.startsWith("169.254."))?.address;++function dial(address: string, port: number, path: string, headers: Record<string, string>, method = "GET", body?: string) {+ return new Promise<{ status: number; headers: Record<string, string | string[] | undefined>; body: string }>((resolve, reject) => {+ const call = request({ host: address, port, path, method, headers }, (res) => {+ let text = "";+ res.setEncoding("utf8");+ res.on("data", (chunk) => { text += chunk; });+ res.on("end", () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body: text }));+ });+ call.on("error", reject);+ call.end(body);+ });+}++async function untilShared(port: number, host: string) {+ let descriptor = { status: 0, headers: {}, body: "" } as Awaited<ReturnType<typeof dial>>;+ for (let attempt = 0; attempt < 50 && descriptor.status !== 200; attempt++) {+ descriptor = await dial(standIn!, port, "/.well-known/openmausbot/environment", { host }).catch(() => descriptor);+ if (descriptor.status !== 200) await new Promise((resolve) => setTimeout(resolve, 100));+ }+ return descriptor;+}++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 port = Number(new URL(fixture.info.url).port);+ const host = `${NAME}:${port}`;+ const origin = `http://${host}`;+ const page = { host, origin, "sec-fetch-site": "same-origin", "sec-fetch-mode": "cors", "sec-fetch-dest": "empty" };+ try {+ // The share comes up once the main listener does; the loopback owner's link already names it.+ const descriptor = await untilShared(port, host);+ expect(descriptor.status).toBe(200);+ expect(JSON.parse(descriptor.body).environmentId).toEqual(expect.any(String));++ // Any other name is refused before the server sees it, the loopback name included: no rebinding, no owner trust.+ for (const other of [`evil.example.com:${port}`, `127.0.0.1:${port}`, `localhost:${port}`, NAME]) {+ expect((await dial(standIn!, port, "/api/bots", { host: other })).status, other).toBe(421);+ }+ // A forwarded host never stands in for the real one.+ expect((await dial(standIn!, port, "/api/bots", { host: `evil.example.com:${port}`, "x-forwarded-host": host })).status).toBe(421);+ // The right name without a session is a stranger.+ expect((await dial(standIn!, port, "/api/bots", { host })).status).toBe(403);++ const opened = await fetch(`${fixture.info.url}/api/auth/pairing`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });+ const offer = await opened.json() as { code: string; url: string | null };+ expect(offer.url).toBe(`${origin}/pair#code=${offer.code}`);++ const pairPage = await dial(standIn!, port, "/pair", { host, "sec-fetch-site": "none", "sec-fetch-mode": "navigate", "sec-fetch-dest": "document" });+ expect(pairPage.status).not.toBe(421);++ const paired = await dial(standIn!, port, "/api/auth/pair", { ...page, "content-type": "application/json" }, "POST", JSON.stringify({ code: offer.code, label: "Laptop", cookie: true }));+ expect(paired.status).toBe(200);+ const cookie = String(paired.headers["set-cookie"]).split(";", 1)[0]!;+ expect(String(paired.headers["set-cookie"])).not.toContain("Secure");+ const bots = await dial(standIn!, port, "/api/bots", { ...page, cookie });+ expect(bots.status).toBe(200);+ expect(JSON.parse(bots.body).bots).toHaveLength(1);+ // The cookie works from its own page only.+ expect((await dial(standIn!, port, "/api/bots", { ...page, origin: "http://evil.example.com", "sec-fetch-site": "cross-site", cookie })).status).toBe(403);+ // An owner-only route stays closed to a session that only chats.+ const clientOffer = await (await fetch(`${fixture.info.url}/api/auth/pairing`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ scopes: ["client"] }) })).json() as { code: string };+ const client = JSON.parse((await dial(standIn!, port, "/api/auth/pair", { host, "content-type": "application/json" }, "POST", JSON.stringify({ code: clientOffer.code, label: "Phone" }))).body) as { token: string };+ expect((await dial(standIn!, port, "/api/bots", { host, authorization: `Bearer ${client.token}` })).status).toBe(200);+ expect((await dial(standIn!, port, "/api/auth/pairing", { host, authorization: `Bearer ${client.token}`, "content-type": "application/json" }, "POST", "{}")).status).toBe(403);+ } finally {+ await fixture.close();+ }+ }, 60_000);++ it("is shared when the desktop app asks, and the owner's desktop capability means nothing from the tailnet", async () => {+ 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 port = Number(new URL(fixture.info.url).port);+ const host = `${NAME}:${port}`;+ try {+ expect((await untilShared(port, host)).status).toBe(200);+ const offer = await (await fetch(`${fixture.info.url}/api/auth/pairing`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })).json() as { code: string; url: string | null };+ expect(offer.url).toBe(`http://${host}/pair#code=${offer.code}`);+ expect((await dial(standIn!, port, "/api/bots", { host, "x-openmausbot-desktop-owner": owner })).status).toBe(403);+ const paired = JSON.parse((await dial(standIn!, port, "/api/auth/pair", { host, "content-type": "application/json" }, "POST", JSON.stringify({ code: offer.code, label: "Laptop" }))).body) as { token: string };+ expect((await dial(standIn!, port, "/api/bots", { host, authorization: `Bearer ${paired.token}` })).status).toBe(200);+ } finally {+ await fixture.close();+ globalThis.fetch = realFetch;+ }+ }, 60_000);+});diff --git a/server/tailnet-listener.test.ts b/server/tailnet-listener.test.tsnew file mode 100644index 0000000000..01b3462416--- /dev/null+++ b/server/tailnet-listener.test.ts@@ -0,0 +1,109 @@+import { request, type Server } from "node:http";+import { afterEach, describe, expect, it } from "vitest";++import { createTailnetShare, hostAllowed, readTailnetShare, tailnetPeerAllowed, tailnetShareFromEnv } from "./tailnet-listener.ts";+import { freePortBlock } from "./testing/ports.ts";++const NAME = "macmini.tail1234.ts.net";++describe("a tailnet share's configuration", () => {+ it("takes a MagicDNS name with an HTTPS origin on that name, or addresses to listen on", () => {+ expect(readTailnetShare({ name: "MacMini.tail1234.ts.net.", served: "https://macmini.tail1234.ts.net" })).toEqual({ name: NAME, served: "https://macmini.tail1234.ts.net" });+ expect(readTailnetShare({ name: NAME, addresses: ["100.101.102.103", "::ffff:100.101.102.103", "fd7a:115c:a1e0::1"] }))+ .toEqual({ name: NAME, addresses: ["100.101.102.103", "fd7a:115c:a1e0::1"] });+ expect(readTailnetShare({ name: NAME })).toEqual({ name: NAME, addresses: "interface" });+ });++ it("fails closed on anything else: other names, other origins, wildcard or loopback addresses", () => {+ for (const input of [+ 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: [] },+ ]) expect(readTailnetShare(input), JSON.stringify(input)).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" }))+ .toEqual({ name: NAME, addresses: ["100.101.102.103", "fd7a:115c:a1e0::1"] });+ expect(tailnetShareFromEnv({ OMB_TAILNET_NAME: NAME })).toEqual({ name: NAME, addresses: "interface" });+ expect(tailnetShareFromEnv({ OMB_TAILNET_NAME: NAME, OMB_TAILNET_SERVED: `https://${NAME}` })).toEqual({ name: NAME, served: `https://${NAME}` });+ });+});++describe("who a tailnet listener answers", () => {+ it("answers Tailscale peers and this machine, never a LAN or public peer", () => {+ const bound = ["100.101.102.103"];+ expect(tailnetPeerAllowed("100.64.12.34", bound)).toBe(true);+ expect(tailnetPeerAllowed("::ffff:100.64.12.34", bound)).toBe(true);+ expect(tailnetPeerAllowed("fd7a:115c:a1e0::9", bound)).toBe(true);+ expect(tailnetPeerAllowed("100.101.102.103", bound)).toBe(true);+ for (const peer of ["192.168.1.50", "10.0.0.2", "203.0.113.9", "127.0.0.1", "fd00::1", undefined]) expect(tailnetPeerAllowed(peer, bound)).toBe(false);+ });++ it("matches the Host header exactly, ignoring case only", () => {+ const allowed = new Set([`${NAME}:8799`, "100.101.102.103:8799"]);+ expect(hostAllowed(`MacMini.tail1234.ts.net:8799`, allowed)).toBe(true);+ for (const host of [NAME, `${NAME}:8800`, `evil.${NAME}:8799`, "127.0.0.1:8799", "localhost:8799", undefined, ""]) expect(hostAllowed(host, allowed)).toBe(false);+ });+});++function ask(port: number, host: string, path = "/"): Promise<{ status: number; body: string }> {+ return new Promise((resolve, reject) => {+ const call = request({ host: "127.0.0.1", port, path, 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();+ });+}++describe("the listeners", () => {+ let share: ReturnType<typeof createTailnetShare> | null = null;+ afterEach(async () => { await share?.close(); share = null; });++ it("waits for the main listener, then hands only requests naming the share to the server's handler", async () => {+ const port = await freePortBlock([0]);+ const attached: Server[] = [];+ share = createTailnetShare({ port: port, handle: async (_req, res) => { res.end("handled"); }, attach: (server) => attached.push(server) });+ await share.apply({ name: NAME, addresses: ["127.0.0.1"] });+ expect(share.origin()).toBeNull();+ await share.start();+ expect(attached).toHaveLength(1);+ expect(share.origin()).toBe(`http://${NAME}:${port}`);+ 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" });+ expect((await ask(port, `127.0.0.1:${port}`)).status).toBe(200);+ const refused = await ask(port, `evil.example.com:${port}`);+ expect(refused.status).toBe(421);+ expect(refused.body).not.toContain("handled");++ await share.apply(null);+ expect(share.origin()).toBeNull();+ await expect(ask(port, `${NAME}:${port}`)).rejects.toThrow();+ });++ 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 }] }) });+ await share.start();+ await share.apply({ name: NAME, addresses: "interface" });+ expect(share.state()).toEqual({ origin: null, listening: [], error: "Tailscale's interface has no address on this computer" });+ await share.apply({ name: NAME, served: `https://${NAME}` });+ expect(share.state()).toEqual({ origin: `https://${NAME}`, listening: [], error: null });+ });++ it("answers the desktop app's message with the state it applied, and ignores other messages", async () => {+ const port = await freePortBlock([0]);+ share = createTailnetShare({ port: port, handle: async () => {}, attach: () => {} });+ await share.start();+ const answers: object[] = [];+ expect(share.receive({ type: "openmausbot:other" }, (answer) => answers.push(answer))).toBe(false);+ const replied = new Promise<object>((resolve) => share!.receive({ type: "openmausbot:tailnet-share", share: { name: NAME, served: `https://${NAME}` } }, resolve));+ expect(await replied).toEqual({ type: "openmausbot:tailnet-share-state", origin: `https://${NAME}`, listening: [], error: null });+ expect(answers).toEqual([]);+ });+});diff --git a/server/tailnet-listener.ts b/server/tailnet-listener.tsnew file mode 100644index 0000000000..5ade0e6029--- /dev/null+++ b/server/tailnet-listener.ts@@ -0,0 +1,216 @@+// 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 { networkInterfaces } from "node:os";++import { IDLE_HTTP_SERVER } from "./due-timer.ts";+import { bareAddress, inTailscaleRange, isTailnetName, tailnetHosts, tailnetInterfaceAddresses, tailnetOrigin } from "../electron/tailnet.mjs";++/** `addresses: "interface"` follows whatever Tailscale's own interface carries. */+export type TailnetShareConfig = { name: string; served: string } | { name: string; addresses: string[] | "interface" };++export interface TailnetShareState {+ origin: string | null;+ listening: string[];+ error: string | null;+}++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";++/** A served origin must be `https://<name>[:port]` and nothing more. */+function servedOrigin(name: string, value: unknown): string | null {+ if (typeof value !== "string") return null;+ try {+ const url = new URL(value);+ const bare = url.protocol === "https:" && !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash;+ return bare && url.hostname === name ? url.origin : null;+ } catch {+ return null;+ }+}++/** Fails closed: anything malformed is no share at all. */+export function readTailnetShare(input: unknown): 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(/\.$/, "") : "";+ if (!isTailnetName(name)) return null;+ if (raw.served !== undefined) {+ const served = servedOrigin(name, raw.served);+ return served ? { name, served } : 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;+}++/** `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. */+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);+ return readTailnetShare({ name: env.OMB_TAILNET_NAME, ...(env.OMB_TAILNET_SERVED ? { served: env.OMB_TAILNET_SERVED } : {}), ...(addresses?.length ? { addresses } : {}) });+}++/**+ * Security: a peer is answered only when it is a Tailscale address or this machine itself (a connection to one of its own+ * addresses comes from that address). Tailscale delivers a peer's packets only with that peer's own source address.+ */+export function tailnetPeerAllowed(remoteAddress: string | undefined, bound: readonly string[]): boolean {+ const remote = bareAddress(remoteAddress);+ return Boolean(remote) && (inTailscaleRange(remote) || bound.includes(remote));+}++export function hostAllowed(host: string | string[] | undefined, allowed: ReadonlySet<string>): boolean {+ const value = (Array.isArray(host) ? host[0] : host)?.trim().toLowerCase();+ return Boolean(value) && allowed.has(value!);+}++type Handle = (req: IncomingMessage, res: ServerResponse) => Promise<unknown>;++export interface TailnetShareOptions {+ port: number;+ handle: Handle;+ /** WebSocket upgrades through the same handler. */+ attach: (server: Server, handle: Handle) => void;+ log?: (line: string) => void;+ interfaces?: () => ReturnType<typeof networkInterfaces>;+}++export function createTailnetShare(options: TailnetShareOptions) {+ const log = options.log ?? (() => {});+ const interfaces = options.interfaces ?? networkInterfaces;+ let started = false;+ let desired: TailnetShareConfig | null = null;+ let listeners = new Map<string, Server>();+ let allowed: ReadonlySet<string> = new Set();+ let error: string | null = null;+ let timer: ReturnType<typeof setInterval> | null = null;+ let applying = Promise.resolve();+ let tellParent: ((answer: object) => void) | null = null;+ let toldParent = "";++ /** The desktop app hears what changed by itself: the share comes up after its message, or Tailscale's interface moves. */+ function announce(): void {+ const answer = JSON.stringify(share.state());+ if (!tellParent || answer === toldParent) return;+ toldParent = answer;+ tellParent({ type: "openmausbot:tailnet-share-state", ...share.state() });+ }++ const guarded: Handle = async (req, res) => {+ if (!hostAllowed(req.headers.host, allowed)) {+ res.writeHead(421, { "content-type": "application/json", "cache-control": "no-store" });+ res.end(JSON.stringify({ error: "misdirected: this listener answers only this computer's tailnet name" }));+ return;+ }+ return options.handle(req, res);+ };++ const close = (server: Server) => new Promise<void>((resolve) => {+ server.closeAllConnections?.();+ server.close(() => resolve());+ });++ function open(address: string): Promise<Server> {+ const server = createServer(IDLE_HTTP_SERVER, guarded);+ options.attach(server, guarded);+ server.on("connection", (socket) => {+ if (!tailnetPeerAllowed(socket.remoteAddress, [...listeners.keys()])) socket.destroy();+ });+ return new Promise((resolve, reject) => {+ server.once("error", reject);+ server.listen({ port: options.port, host: address, ipv6Only: address.includes(":") }, () => {+ server.off("error", reject);+ server.on("error", (failure) => log(`tailnet: ${address} ${failure.message}`));+ resolve(server);+ });+ });+ }++ async function bind(config: TailnetShareConfig | null): Promise<void> {+ const wanted = config && "addresses" in config ? (config.addresses === "interface" ? tailnetInterfaceAddresses(interfaces()) : config.addresses) : [];+ for (const [address, server] of listeners) {+ if (!wanted.includes(address)) {+ listeners.delete(address);+ await close(server);+ }+ }+ const failures: string[] = [];+ for (const address of wanted) {+ if (listeners.has(address)) continue;+ try {+ listeners.set(address, await open(address));+ log(`tailnet: listening on ${address.includes(":") ? `[${address}]` : address}:${options.port} for ${config!.name}`);+ } catch (failure) {+ 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+ ? 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}`);+ }++ function follow(config: TailnetShareConfig | null) {+ if (timer) clearInterval(timer);+ timer = null;+ if (!config || !("addresses" in config) || config.addresses !== "interface") return;+ timer = setInterval(() => void reconcile().then(announce), FOLLOW_MS);+ timer.unref?.();+ }++ const reconcile = () => {+ applying = applying.then(() => (started ? bind(desired) : undefined)).catch((failure: Error) => log(`tailnet: ${failure.message}`));+ return applying;+ };++ const share = {+ /** Takes effect once the main listener is up; until then it is remembered. */+ apply(config: TailnetShareConfig | null): Promise<void> {+ desired = config;+ follow(config);+ return reconcile();+ },+ start(env: NodeJS.ProcessEnv = {}): Promise<void> {+ started = true;+ const fromEnv = desired ?? tailnetShareFromEnv(env);+ return (fromEnv ? share.apply(fromEnv) : reconcile()).then(announce);+ },+ /** The origin a pairing link uses: the served HTTPS one, or this listener's while it listens somewhere. */+ origin(): string | null {+ if (!desired) return null;+ if ("served" in desired) return desired.served;+ return listeners.size ? tailnetOrigin(desired.name, options.port) : null;+ },+ state(): TailnetShareState {+ return { origin: share.origin(), listening: [...listeners.keys()], 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 {+ if (!message || typeof message !== "object" || (message as { type?: unknown }).type !== "openmausbot:tailnet-share") return false;+ tellParent = reply;+ const config = readTailnetShare((message as { share?: unknown }).share);+ void share.apply(config).then(() => {+ toldParent = JSON.stringify(share.state());+ reply({ type: "openmausbot:tailnet-share-state", ...share.state() });+ });+ return true;+ },+ async close(): Promise<void> {+ started = false;+ follow(null);+ await applying;+ const open = [...listeners.values()];+ listeners = new Map();+ allowed = new Set();+ await Promise.all(open.map(close));+ },+ };+ return share;+}diff --git a/server/tailscale.test.ts b/server/tailscale.test.tsindex 1e98ca3139..1a7e8ecfef 100644--- a/server/tailscale.test.ts+++ b/server/tailscale.test.ts@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, it } from "vitest";-import { classifyTailscaleStderr, clearLeftoverTailscaleServe, explainTailscaleFailure, parseTailscaleStatus, tailscaleMarker, tailscaleServe, type TailscaleStatus } from "./tailscale.ts";+import { classifyTailscaleStderr, clearLeftoverTailscaleServe, explainTailscaleFailure, parseTailscaleStatus, tailnetListenFallback, tailscaleMarker, tailscaleServe, type TailscaleStatus } from "./tailscale.ts";describe("tailscale helpers", () => {it("reads the MagicDNS name, addresses and state from status --json", () => {@@ -15,6 +15,7 @@ describe("tailscale helpers", () => {}));expect(status).toEqual({ cli: "/usr/bin/tailscale", dnsName: "mini.tail1234.ts.net", addresses: ["100.64.0.7", "fd7a:115c:a1e0::7"], backendState: "Running", httpsEnabled: true });expect(parseTailscaleStatus("t", JSON.stringify({ BackendState: "Running" }))?.httpsEnabled).toBe(false);+ expect(parseTailscaleStatus("t", JSON.stringify({ BackendState: "Running", Self: { CapMap: { https: null } } }))?.httpsEnabled).toBe(true);expect(parseTailscaleStatus("t", "{}")?.dnsName).toBeNull();expect(parseTailscaleStatus("t", "not json")).toBeNull();});@@ -32,6 +33,25 @@ describe("tailscale helpers", () => {});});+describe("serve --tailscale without HTTPS", () => {+ const status: TailscaleStatus = { cli: "/usr/bin/tailscale", dnsName: "nuc.tail1234.ts.net", addresses: ["100.70.0.9", "fd7a:115c:a1e0::9"], backendState: "Running", httpsEnabled: false };+ const interfaces = { eth0: [{ address: "192.168.1.30" }], tailscale0: [{ address: "100.70.0.9" }, { address: "fd7a:115c:a1e0::9" }] };++ 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" });+ expect(fallback?.line).toContain("login.tailscale.com/admin/dns");+ expect(tailnetListenFallback("needs-operator", status, 8799, interfaces)?.line).toContain("--operator=$USER");+ });++ it("fails as before where listening would not help: another failure, no name, or no Tailscale interface", () => {+ expect(tailnetListenFallback("not-running", status, 8799, interfaces)).toBeNull();+ expect(tailnetListenFallback("https-not-enabled", { ...status, dnsName: null }, 8799, interfaces)).toBeNull();+ expect(tailnetListenFallback("https-not-enabled", status, 8799, { eth0: interfaces.eth0 })).toBeNull();+ });+});+describe("serve --tailscale", () => {const status: TailscaleStatus = { cli: "/usr/bin/tailscale", dnsName: "mini.tail1234.ts.net", addresses: [], backendState: "Running", httpsEnabled: true };const fakeServe = (exitCode: number | null, stderr = "") => {diff --git a/server/tailscale.ts b/server/tailscale.tsindex 41f2695a82..da658f1ebe 100644--- a/server/tailscale.ts+++ b/server/tailscale.ts@@ -1,16 +1,18 @@// Never log Tailscale's raw stderr (it can contain auth keys and node names): failures are classified into a closed set.import { execFile, spawn } from "node:child_process";import { readFileSync, rmSync, writeFileSync } from "node:fs";+import { networkInterfaces } from "node:os";import { join } from "node:path";import { tailscaleCandidates, tailscaleEnvironment } from "../companion/src/listener.ts";+import { readTailscaleStatusJson, tailnetInterfaceAddresses, tailnetOrigin } from "../electron/tailnet.mjs";export interface TailscaleStatus {cli: string;dnsName: string | null;addresses: string[];backendState: string;- /** The tailnet hands out HTTPS certificates (`CertDomains` in `tailscale status --json`). */+ /** The tailnet hands out HTTPS certificates (`CertDomains`, or `https` in `Self.CapMap`, in `tailscale status --json`). */httpsEnabled: boolean;}@@ -80,13 +82,12 @@ export function parseTailscaleStatus(cli: string, stdout: string): TailscaleStatconst dns = Reflect.get(Object(self), "DNSName");const ips = Reflect.get(Object(self), "TailscaleIPs");const state = Reflect.get(Object(parsed), "BackendState");- const certDomains = Reflect.get(Object(parsed), "CertDomains");return {cli,dnsName: typeof dns === "string" && dns ? dns.replace(/\.$/, "") : null,addresses: Array.isArray(ips) ? ips.filter((v): v is string => typeof v === "string") : [],backendState: typeof state === "string" ? state : "unknown",- httpsEnabled: Array.isArray(certDomains) && certDomains.length > 0,+ httpsEnabled: readTailscaleStatusJson(stdout)?.https === true,};}@@ -107,6 +108,32 @@ export async function tailscaleStatus(): Promise<{ status: TailscaleStatus } | {return { failure: sawCli ? "unknown" : "not-installed" };}+/** What keeps `tailscale serve` from fronting this server, while the tailnet itself still reaches it. */+const LISTEN_INSTEAD: Partial<Record<TailscaleFailure, [why: string, fix: string]>> = {+ "https-not-enabled": ["HTTPS certificates are off for this tailnet", "turn on HTTPS Certificates at https://login.tailscale.com/admin/dns and start again"],+ "needs-operator": ["Tailscale won't let this user run tailscale serve", "run `sudo tailscale set --operator=$USER` once and start again"],+ "other-server": ["the tailnet name's HTTPS address already fronts a different MausBot server", "stop that server and start again"],+};++/**+ * When `tailscale serve` can't front this server, it listens on its own tailnet addresses instead, at+ * `http://<name>:<port>` (WireGuard encrypts it). Null when that would not help either: another failure, no MagicDNS+ * 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 {+ const reason = LISTEN_INSTEAD[failure];+ const local = tailnetInterfaceAddresses(interfaces);+ const addresses = status.addresses.filter((address) => local.includes(address.toLowerCase()));+ if (!reason || !status.dnsName || addresses.length === 0) return null;+ const origin = tailnetOrigin(status.dnsName, port);+ return {+ origin,+ env: { OMB_TAILNET_NAME: status.dnsName, OMB_TAILNET_ADDRESSES: addresses.join(",") },+ 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]}.`,+ };+}+/** Where a run that shares over Tailscale notes it, so the next start can turn off a share a crash left behind. */export const tailscaleMarker = (dataDir: string) => join(dataDir, "tailscale-serve.marker");diff --git a/server/testing/desktop-parent.mjs b/server/testing/desktop-parent.mjsindex 838227507f..1caa27330e 100644--- a/server/testing/desktop-parent.mjs+++ b/server/testing/desktop-parent.mjs@@ -2,6 +2,7 @@// the server runs as Electron's utility process, and only what the app itself would send crosses.// OMB_TEST_DESKTOP_OWNER_TOKEN (with OMB_DESKTOP_PARENT=1): the test's owner capability.// OMB_TEST_DESKTOP_PAGES_ACCESS: the published pages' access the app hands over for a signed-in MausBot account, as JSON.+// OMB_TEST_DESKTOP_TAILNET_SHARE: the share on the tailnet the app asks its server for, as JSON.// OMB_TEST_DESKTOP_CUA_CONNECTION: a file holding the app's driver record; the app hands it to its own server, and again// each time the file changes, as the real app does each time its driver changes.import { readFileSync, unwatchFile, watchFile } from "node:fs";@@ -9,6 +10,8 @@ import { readFileSync, unwatchFile, watchFile } from "node:fs";const token = process.env.OMB_TEST_DESKTOP_OWNER_TOKEN;const pages = process.env.OMB_TEST_DESKTOP_PAGES_ACCESS;const cuaFile = process.env.OMB_TEST_DESKTOP_CUA_CONNECTION;+const tailnetShare = process.env.OMB_TEST_DESKTOP_TAILNET_SHARE;+delete process.env.OMB_TEST_DESKTOP_TAILNET_SHARE;delete process.env.OMB_TEST_DESKTOP_OWNER_TOKEN;delete process.env.OMB_TEST_DESKTOP_PAGES_ACCESS;delete process.env.OMB_TEST_DESKTOP_CUA_CONNECTION;@@ -38,6 +41,7 @@ if (token || cuaFile) {if (token) queueMicrotask(() => listener({ data: { type: "openmausbot:desktop-mutation-token", token } }));if (pages) queueMicrotask(() => listener({ data: { type: "openmausbot:included-pages", access: JSON.parse(pages) } }));if (cuaFile) queueMicrotask(() => listener({ data: cuaGrant() }));+ if (tailnetShare) queueMicrotask(() => listener({ data: { type: "openmausbot:tailnet-share", share: JSON.parse(tailnetShare) } }));},postMessage() {},},