Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(local-installation): move local services off ports another program holds
claude-opus-5-5-medium1e4487ff747b
diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.tsindex e5f1ade4..1725f9e4 100644--- a/apps/desktop/src/main/local-server.test.ts+++ b/apps/desktop/src/main/local-server.test.ts@@ -34,7 +34,6 @@ import {legacyMigrationResult,parseSetCookie,LocalServerUnverifiedError,- localIdentityProof,proveLocalServer,SignInRejectedError,signInFailure,@@ -42,6 +41,7 @@ import {type LocalServerIdentity,type LocalServerOptions,} from "./local-server.js";+import { localIdentityProof } from "@linger/local-installation/account";import type { DesktopConfig } from "./config.js";import { EventBus, type ModuleContext } from "./modules.js";import {diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.tsindex 2e737818..400793e3 100644--- a/apps/desktop/src/main/local-server.ts+++ b/apps/desktop/src/main/local-server.ts@@ -1,11 +1,5 @@import { spawn } from "node:child_process";-import {- createHash,- createHmac,- randomBytes,- randomUUID,- timingSafeEqual,-} from "node:crypto";+import { createHash, randomBytes, randomUUID } from "node:crypto";import { createReadStream, existsSync, readFileSync } from "node:fs";import {constants as fsConstants,@@ -28,6 +22,8 @@ import { setTimeout as delay } from "node:timers/promises";import { createZstdDecompress } from "node:zlib";import {+ LocalIdentityError,+ proveLocalIdentity,readLocalIdentity,readLocalLogin,} from "@linger/local-installation/account";@@ -3004,65 +3000,30 @@ const unverifiedReason = (error: unknown): string =>export const LOCAL_IDENTITY_TIMEOUT_MS = 5_000;-// What TeamHub answers a challenge with (internal/localidentity).-export const localIdentityProof = (- key: Uint8Array,- nonce: string,- origin: string,-): Buffer =>- createHmac("sha256", key)- .update(`linger-local-identity\n${nonce}\n${origin}`)- .digest();--// Asks TeamHub to prove it holds this installation's identity key, with a-// fresh nonce each time, so an earlier answer proves nothing. The challenge-// goes to TeamHub's own port: a program on the web port could pass it on to-// a TeamHub still running, but whatever answers on TeamHub's port and holds-// the key is TeamHub.+// Asks TeamHub to prove it holds this installation's identity key. The+// challenge goes to TeamHub's own port: a program on the web port could+// pass it on to a TeamHub still running, but whatever answers on TeamHub's+// port and holds the key is TeamHub.export const proveLocalServer = async (server: LocalServerIdentity,fetcher: typeof fetch = fetch,timeoutMs = LOCAL_IDENTITY_TIMEOUT_MS,): Promise<void> => {- const nonce = randomBytes(32).toString("base64url");- let proof: unknown;try {- const response = await fetcher(- new URL("/v0/local/identity", server.teamhub),- {- method: "POST",- headers: {- accept: "application/json",- "content-type": "application/json",- },- body: JSON.stringify({ nonce }),- redirect: "error",- signal: AbortSignal.timeout(timeoutMs),- },- );- if (!response.ok) {- await response.body?.cancel();- throw new LocalServerUnverifiedError(`status ${response.status}`);- }- proof = ((await response.json()) as { proof?: unknown } | null)?.proof;+ await proveLocalIdentity({+ url: new URL("/v0/local/identity", server.teamhub),+ origin: server.origin,+ key: server.key,+ signal: AbortSignal.timeout(timeoutMs),+ fetch: fetcher,+ });} catch (error) {- if (error instanceof LocalServerUnverifiedError) throw error;- throw new LocalServerUnverifiedError(- error instanceof SyntaxError ? "invalid answer" : "no answer",- { cause: error },- );+ if (error instanceof LocalIdentityError)+ throw new LocalServerUnverifiedError(error.reason, {+ cause: error.cause,+ });+ throw error;}- const expected = localIdentityProof(server.key, nonce, server.origin);- const actual =- typeof proof === "string" && /^[A-Za-z0-9_-]{43}$/.test(proof)- ? Buffer.from(proof, "base64url")- : undefined;- if (- !actual ||- actual.length !== expected.length ||- !timingSafeEqual(actual, expected)- )- throw new LocalServerUnverifiedError("wrong proof");};// Signs in to the local server with its owner and hands the session cookiesdiff --git a/apps/node-services/AGENTS.md b/apps/node-services/AGENTS.mdindex 81368d81..13238597 100644--- a/apps/node-services/AGENTS.md+++ b/apps/node-services/AGENTS.md@@ -19,7 +19,7 @@lifecycle, so other roles remain available and replacements can mount.- The `document` role keeps its own port (4321 by default) on its own workerthread (`src/document/main.ts`) because it installs jsdom globals and- replaces the global `Request`/`Response`. The `voice` role supervises separate ASR, recorder and Live child processes (ports 4324–4326); it does not run audio jobs on the main thread. Voice workers follow TeamHub's effective provider keys (`GET /internal/v1/voice/provider-keys` with the `voice-runtime` credential): a Soniox key runs ASR and recorder, an xAI key runs Live. The role reconciles at startup, on TeamHub's `POST /v1/voice/workers:reconcile` (`node-services-internal` bearer), and every 60 seconds, so workers start, drain, or restart with a new key without restarting node-services. The reconcile route answers `{ready}` only after every wanted worker's health port reports it registered with LiveKit, or after 20 seconds, so TeamHub answers a key save once a voice session can be dispatched. Keys reach a worker only through its environment; a failed key fetch leaves the running workers unchanged. Other roles run on the main thread+ replaces the global `Request`/`Response`. The `voice` role supervises separate ASR, recorder and Live child processes, each on a health port the system offers when it starts (`VOICE_WORKER_PORT`); it does not run audio jobs on the main thread. Voice workers follow TeamHub's effective provider keys (`GET /internal/v1/voice/provider-keys` with the `voice-runtime` credential): a Soniox key runs ASR and recorder, an xAI key runs Live. The role reconciles at startup, on TeamHub's `POST /v1/voice/workers:reconcile` (`node-services-internal` bearer), and every 60 seconds, so workers start, drain, or restart with a new key without restarting node-services. The reconcile route answers `{ready}` only after every wanted worker's health port reports it registered with LiveKit, or after 20 seconds, so TeamHub answers a key save once a voice session can be dispatched. Keys reach a worker only through its environment; a failed key fetch leaves the running workers unchanged. Other roles run on the main threadand must not install process globals.- `NODE_SERVICES_ROLES` selects roles as a comma-separated list. An unset orempty value starts every role; an unknown role fails startup. Selected rolesdiff --git a/apps/node-services/src/voice/service.ts b/apps/node-services/src/voice/service.tsindex a8f5b4a8..46a0d34c 100644--- a/apps/node-services/src/voice/service.ts+++ b/apps/node-services/src/voice/service.ts@@ -1,5 +1,6 @@import { spawn, type ChildProcess } from "node:child_process";import { randomBytes } from "node:crypto";+import { createServer, type AddressInfo } from "node:net";import path from "node:path";import { fileURLToPath } from "node:url";import { isRecord } from "@linger/service-kit";@@ -16,11 +17,6 @@ import { hasBearerToken } from "../service-bearer-auth.js";import { readVoiceConfig, type VoiceConfig } from "./config.js";export type VoiceWorker = "asr" | "recorder" | "live";-export const voiceWorkerPorts = {- asr: 4324,- recorder: 4325,- live: 4326,-} as const;const VOICE_WORKERS = ["asr", "recorder", "live"] as const;// LiveKit drains for 2 s, then allows jobs 68 s to save their final media.export const VOICE_DRAIN_MS = 72_000;@@ -101,12 +97,25 @@ async function fetchProviderKeys(};}+/** Each worker process gets a port the system offers, so another program on a+ * fixed port never keeps a worker from starting. */+function freeWorkerPort(): Promise<number> {+ return new Promise((resolve, reject) => {+ const server = createServer();+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => {+ const { port } = server.address() as AddressInfo;+ server.close((error) => (error ? reject(error) : resolve(port)));+ });+ });+}+/** A LiveKit agents worker answers 2xx on its health port only once it is* registered with LiveKit, so this is when it can take a dispatched job. */-async function probeVoiceWorker(worker: VoiceWorker): Promise<boolean> {+async function probeVoiceWorker(port: number): Promise<boolean> {try {return (- await fetch(`http://127.0.0.1:${voiceWorkerPorts[worker]}/`, {+ await fetch(`http://127.0.0.1:${port}/`, {signal: AbortSignal.timeout(1_000),})).ok;@@ -127,12 +136,14 @@ export async function startVoiceService(options: {spawnWorker?: (worker: VoiceWorker, spec: VoiceWorkerSpawn) => ChildProcess;installModels?: () => Promise<void>;fetch?: typeof fetch;- probeWorker?: (worker: VoiceWorker) => Promise<boolean>;+ probeWorker?: (port: number) => Promise<boolean>;+ allocatePort?: () => Promise<number>;}) {const env = options.environment ?? process.env;const config = readVoiceConfig(env);const fetchImpl = options.fetch ?? fetch;const probeWorker = options.probeWorker ?? probeVoiceWorker;+ const allocatePort = options.allocatePort ?? freeWorkerPort;// The VAD model's native package, when the runtime ships it separately: the// workers wait for its first download and find it on NODE_PATH.const models = modelPackageNames("voice");@@ -163,6 +174,8 @@ export async function startVoiceService(options: {child?: ChildProcess;/** The generation that started `child`; an older one is draining. */childGeneration?: number;+ /** The health port of `child`. */+ port?: number;exited?: Promise<void>;retry?: NodeJS.Timeout;failures: number;@@ -223,51 +236,57 @@ export async function startVoiceService(options: {}, restart);return;}- const workerEntry = fileURLToPath(- import.meta.resolve("@linger/voice-runtime/worker"),- );- let child: ChildProcess;- try {- // Keys travel only in the child's environment. Both provider variables- // are set explicitly, so a key inherited by node-services never wins.- child = launch(worker, {- args: [- ...(workerEntry.endsWith(".ts")- ? ["--import", "tsx"]- : ["--conditions=linger-production"]),- workerEntry,- "start",- ...(worker === "asr" ? [] : [`--${worker}`]),- ],- env: {- ...env,- ...modelPath,- SONIOX_API_KEY: "",- XAI_API_KEY: "",- [key.variable]: key.key,- TEAMHUB_BASE_URL: config.teamHubBaseUrl,- VOICE_WORKER_PORT: String(voiceWorkerPorts[worker]),- },+ allocatePort().then((port) => {+ if (current()) spawnWorker(port, key);+ }, restart);+ function spawnWorker(port: number, key: { variable: string; key: string }) {+ const workerEntry = fileURLToPath(+ import.meta.resolve("@linger/voice-runtime/worker"),+ );+ let child: ChildProcess;+ try {+ // Keys travel only in the child's environment. Both provider variables+ // are set explicitly, so a key inherited by node-services never wins.+ child = launch(worker, {+ args: [+ ...(workerEntry.endsWith(".ts")+ ? ["--import", "tsx"]+ : ["--conditions=linger-production"]),+ workerEntry,+ "start",+ ...(worker === "asr" ? [] : [`--${worker}`]),+ ],+ env: {+ ...env,+ ...modelPath,+ SONIOX_API_KEY: "",+ XAI_API_KEY: "",+ [key.variable]: key.key,+ TEAMHUB_BASE_URL: config.teamHubBaseUrl,+ VOICE_WORKER_PORT: String(port),+ },+ });+ } catch (error) {+ restart(error);+ return;+ }+ entry.child = child;+ entry.childGeneration = generation;+ entry.port = port;+ entry.exited = new Promise<void>((resolve) => {+ let settled = false;+ const finish = (error?: unknown) => {+ if (settled) return;+ settled = true;+ if (entry.child === child) entry.child = undefined;+ killGroup(child);+ resolve();+ restart(error);+ };+ child.once("error", finish);+ child.once("exit", (code, signal) => finish({ code, signal }));});- } catch (error) {- restart(error);- return;}- entry.child = child;- entry.childGeneration = generation;- entry.exited = new Promise<void>((resolve) => {- let settled = false;- const finish = (error?: unknown) => {- if (settled) return;- settled = true;- if (entry.child === child) entry.child = undefined;- killGroup(child);- resolve();- restart(error);- };- child.once("error", finish);- child.once("exit", (code, signal) => finish({ code, signal }));- });};const apply = (keys: ProviderKeys) => {const wanted = workerKeys(keys);@@ -293,7 +312,7 @@ export async function startVoiceService(options: {start(worker);continue;}- // The replacement binds the same port, so it waits for the old drain.+ // The replacement starts after the old worker drains its jobs.void drain(child, entry.exited).then(() => {if (generation === entry.generation) start(worker);});@@ -346,12 +365,12 @@ export async function startVoiceService(options: {await Promise.all(wantedWorkers().map(async (worker) => {const entry = entries.get(worker)!;- // A replaced worker answers on the same port until it exits, so- // only the child of the current generation counts.+ // A replaced worker may still answer until it exits, so only the+ // child of the current generation counts.return (Boolean(entry.child) &&entry.childGeneration === entry.generation &&- (await probeWorker(worker))+ (await probeWorker(entry.port!)));}),)diff --git a/apps/node-services/tests/voice-service.test.ts b/apps/node-services/tests/voice-service.test.tsindex 255e1439..ea580f8e 100644--- a/apps/node-services/tests/voice-service.test.ts+++ b/apps/node-services/tests/voice-service.test.ts@@ -61,6 +61,8 @@ async function harness(child: Worker;}[] = [];const health = { healthy: options.healthy ?? true };+ let nextPort = 40_000;+ const probed: number[] = [];const log = vi.fn();let route: HttpRoute | undefined;const unmount = vi.fn();@@ -75,7 +77,11 @@ async function harness(environment: { ...environment, ...options.env },fetch: fetchImpl as unknown as typeof fetch,installModels: async () => undefined,- probeWorker: async () => health.healthy,+ probeWorker: async (port) => {+ probed.push(port);+ return health.healthy;+ },+ allocatePort: async () => nextPort++,spawnWorker: (worker, spec) => {const child = new Worker();spawned.push({ worker, spec, child });@@ -100,6 +106,7 @@ async function harness(log,route: route!,unmount,+ probed,};}@@ -134,6 +141,11 @@ describe("voice worker reconcile", () => {expect(spec.args.join(" ")).not.toContain(SONIOX);}expect(of("recorder")[0]!.spec.args).toContain("--recorder");+ // Each process gets its own free health port, not a fixed one.+ expect(spawned.map(({ spec }) => spec.env.VOICE_WORKER_PORT)).toEqual([+ "40000",+ "40001",+ ]);teamHub.keys = { soniox_api_key: SONIOX, xai_api_key: XAI };await service.reconcile();expect(of("live")).toHaveLength(1);@@ -285,7 +297,7 @@ describe("voice worker reconcile", () => {});it("answers a reconcile once the wanted workers are registered", async () => {- const { route, teamHub, health, shutdown, of } = await harness({+ const { route, teamHub, health, shutdown, of, probed } = await harness({healthy: false,});teamHub.keys = { xai_api_key: XAI };@@ -303,6 +315,10 @@ describe("voice worker reconcile", () => {await vi.advanceTimersByTimeAsync(250);await answered;expect(answer).toEqual({ ready: true });+ // The probe asks the port the worker was started with.+ expect(new Set(probed)).toEqual(+ new Set([Number(of("live")[0]!.spec.env.VOICE_WORKER_PORT)]),+ );await shutdown();});diff --git a/apps/voice-runtime/README.md b/apps/voice-runtime/README.mdindex 89beebf7..855c19e0 100644--- a/apps/voice-runtime/README.md+++ b/apps/voice-runtime/README.md@@ -15,4 +15,4 @@ Commands, conventions and boundaries are in [AGENTS.md](./AGENTS.md).- `node dist/main.js start` starts the ASR worker; `start --recorder` starts the recording worker from the same image. Set the log level with the LiveKit CLI's `--log-level`; `start` defaults to `info`.- Required environment variables: `TEAMHUB_BASE_URL`, `LINGER_SECRET_SEED`. `LIVEKIT_URL`, `LIVEKIT_API_KEY` and `LIVEKIT_API_SECRET` are optional and have defaults. The transcription workers need `SONIOX_API_KEY`, and ASR uses Soniox only; the Live worker needs only `XAI_API_KEY`, and the user's captions come from Grok's own transcription, not from Soniox. Recording transcripts always separate speakers; dictation does not.-- The health port is fixed at `4324`: in the image (`NODE_ENV=production`) it listens on every interface, and when run directly on a machine only on loopback. Each worker takes at most 16 sessions. The LiveKit address and key pair come from `LIVEKIT_URL`, `LIVEKIT_API_KEY` and `LIVEKIT_API_SECRET`; unset, they default to the local deployment in `apps/teamhub/deployments/voice` (`ws://127.0.0.1:17880`, `devkey` and its development secret), the same as TeamHub's defaults. In Compose, `LIVEKIT_URL` is `ws://livekit:7880`. The Soniox model and language hints are code constants.+- The health port is `VOICE_WORKER_PORT` (`4324` when unset; node-services gives each worker a free port): in the image (`NODE_ENV=production`) it listens on every interface, and when run directly on a machine only on loopback. Each worker takes at most 16 sessions. The LiveKit address and key pair come from `LIVEKIT_URL`, `LIVEKIT_API_KEY` and `LIVEKIT_API_SECRET`; unset, they default to the local deployment in `apps/teamhub/deployments/voice` (`ws://127.0.0.1:17880`, `devkey` and its development secret), the same as TeamHub's defaults. In Compose, `LIVEKIT_URL` is `ws://livekit:7880`. The Soniox model and language hints are code constants.diff --git a/apps/web/src/test/static-host.test.ts b/apps/web/src/test/static-host.test.tsindex 88ad88b3..84be0baf 100644--- a/apps/web/src/test/static-host.test.ts+++ b/apps/web/src/test/static-host.test.ts@@ -9,6 +9,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {createServiceProxy,createStaticHost,+ listenOnHosts,serviceProxyRoutes,} from "../../static-host.mjs";@@ -173,6 +174,24 @@ describe("Web static host routing", () => {});});+describe("Web static host listening", () => {+ it("listens on every listed address and fails when one is taken", async () => {+ const servers = await listenOnHosts(+ () => createServer((_, response) => response.end("ok")),+ 0,+ "127.0.0.1",+ );+ const { port } = servers[0]!.address() as { port: number };+ // ::1 is skipped on a computer without IPv6.+ const both = await listenOnHosts(() => createServer(), 0, "127.0.0.1, ::1");+ expect(both.length).toBeGreaterThanOrEqual(1);+ await expect(+ listenOnHosts(() => createServer(), port, "127.0.0.1"),+ ).rejects.toMatchObject({ code: "EADDRINUSE" });+ for (const listening of [...servers, ...both]) listening.close();+ });+});+describe("Web static host cache policy", () => {it("serves fingerprinted Vite assets with immutable caching", async () => {const response = await fetch(`${baseUrl}/assets/app-abc123.js`, {diff --git a/apps/web/static-host.mjs b/apps/web/static-host.mjsindex daf143b9..dd8c1971 100644--- a/apps/web/static-host.mjs+++ b/apps/web/static-host.mjs@@ -247,17 +247,58 @@ if (isMainModule()) {// The production bundle calls TeamHub and the Document Runtime on the page// origin, so a host with these upstreams forwards them like the Vite proxy.const proxy = createServiceProxy(serviceProxyRoutes(process.env));- const server = createServer((request, response) => {- if (!proxy.request(request, response)) void staticHost(request, response);- });- server.on("upgrade", proxy.upgrade);-// Native binds loopback only; the container image listens on every address.- server.listen(port, process.env.HOST || "0.0.0.0", () => {- process.stdout.write(- `Web static host listening on http://localhost:${port}\n`,- );- });+ void listenOnHosts(+ () => {+ const server = createServer((request, response) => {+ if (!proxy.request(request, response))+ void staticHost(request, response);+ });+ server.on("upgrade", proxy.upgrade);+ return server;+ },+ port,+ process.env.HOST || "0.0.0.0",+ ).then(+ () =>+ process.stdout.write(+ `Web static host listening on http://localhost:${port}\n`,+ ),+ (error) => {+ process.stderr.write(`Web static host cannot listen: ${error.message}\n`);+ process.exit(1);+ },+ );+}++// `hosts` is a comma-separated address list. Native lists both loopback+// addresses: `localhost` resolves to ::1 first on macOS, so a program on ::1+// alone would otherwise answer for this origin. A computer without IPv6 has+// no IPv6 address to take.+export async function listenOnHosts(makeServer, port, hosts) {+ const servers = [];+ for (const host of hosts.split(",").map((value) => value.trim())) {+ const server = makeServer();+ try {+ await new Promise((resolveListen, rejectListen) => {+ server.once("error", rejectListen);+ server.listen(port, host, () => {+ server.off("error", rejectListen);+ resolveListen();+ });+ });+ servers.push(server);+ } catch (error) {+ if (+ host.includes(":") &&+ ["EADDRNOTAVAIL", "EAFNOSUPPORT"].includes(error.code)+ )+ continue;+ for (const listening of servers) listening.close();+ throw error;+ }+ }+ return servers;}function isMainModule() {diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.mdindex 54ed177a..22e68a6e 100644--- a/packages/local-installation/AGENTS.md+++ b/packages/local-installation/AGENTS.md@@ -35,6 +35,19 @@ voice key; without them, or when they fail to prepare, TeamHub gets`TEAMHUB_VOICE_MEDIA=off` and the install continues. The services' `voice`setting tracks only the tools, so a key change never restarts them throughit. A native process restarts when its generated environment changes.+Every port the installer chooses (`ports.ts`) must be free on both+127.0.0.1 and ::1 with nothing answering there: `localhost` resolves to ::1+first on macOS, and a program on ::1 alone would answer for a service that+bound 127.0.0.1 without an error. The web static host listens on both. Each+start re-checks a stopped service's ports and moves one another program took+to a free port, persisted in `instance.json` or `livekit.env`, so the service+restarts with the new environment. The web port is the product origin, which+the browser session, the desktop app and the Computer keep once the owner+account exists (or a database set aside from an older install marks it to be+made again); it moves only before that. The account step sends a password only+after the origin's `/v0/local/identity` proof, and a service that stops on a+taken port names the port, instead of a foreign server's answer or a bare+failure.Every update or recreate path stops node-services on its own, right beforeTeamHub restarts (natively: for a changed configuration) and while TeamHub isstill up, so its graceful shutdown requeues in-flight Agent Runs.diff --git a/packages/local-installation/src/account.test.ts b/packages/local-installation/src/account.test.tsindex 40bf276e..99813560 100644--- a/packages/local-installation/src/account.test.ts+++ b/packages/local-installation/src/account.test.ts@@ -9,7 +9,7 @@ import {import { tmpdir } from "node:os";import path from "node:path";import { afterEach, expect, it, vi } from "vitest";-import { ensureLocalAccount } from "./account.js";+import { ensureLocalAccount, localIdentityProof } from "./account.js";import type { Instance } from "./instance.js";const provisionOwner =@@ -23,22 +23,47 @@ afterEach(async () => {roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),);});-async function fixture() {+const identityKey = Buffer.alloc(32, 9);+async function fixture({ identity = true } = {}) {const root = await mkdtemp(path.join(tmpdir(), "linger-account-"));roots.push(root);const instance = { root, origin: "http://localhost:3000" } as Instance;+ if (identity)+ await writeFile(+ path.join(root, "local-identity.key"),+ `${identityKey.toString("base64")}\n`,+ { mode: 0o600 },+ );return {instance,file: path.join(root, "local-account.json"),signal: new AbortController().signal,};}+// This instance's server: it proves the origin before `handler` sees requests.+function stubFetch(+ handler: (url: string, init?: RequestInit) => Promise<Response>,+) {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string, init?: RequestInit) => {+ if (!url.endsWith("/v0/local/identity")) return handler(url, init);+ const { nonce } = JSON.parse(init?.body as string) as { nonce: string };+ return Response.json({+ proof: localIdentityProof(+ identityKey,+ nonce,+ "http://localhost:3000",+ ).toString("base64url"),+ });+ }),+ );+}it("creates the owner through stdin, confirms login and logs out before reusing private credentials", async () => {const f = await fixture();const requests: string[] = [];let created = false;- vi.stubGlobal(- "fetch",+ stubFetch(vi.fn(async (url: string) => {requests.push(new URL(url).pathname);return new Response(null, {@@ -75,7 +100,7 @@ it("creates the owner through stdin, confirms login and logs out before reusing.mock.calls.map(([url]) => new URL(url instanceof Request ? url.url : url).pathname,),- ).toEqual(["/v0/auth/login", "/v0/auth/logout"]);+ ).toEqual(["/v0/local/identity", "/v0/auth/login", "/v0/auth/logout"]);expect(provisionOwner).not.toHaveBeenCalled();expect(JSON.parse(await readFile(f.file, "utf8")).password === saved.password,@@ -93,8 +118,7 @@ it("recovers owner creation interrupted after commit using the saved password wi}),{ mode: 0o600 },);- vi.stubGlobal(- "fetch",+ stubFetch(vi.fn(async () =>new Response(null, {@@ -110,10 +134,7 @@ it("recovers owner creation interrupted after commit using the saved password wi});it("does not mark an existing owner provisioned when its saved password cannot log in", async () => {const f = await fixture();- vi.stubGlobal(- "fetch",- vi.fn(async () => new Response(null, { status: 401 })),- );+ stubFetch(vi.fn(async () => new Response(null, { status: 401 })));provisionOwner.mockResolvedValue(undefined);await expect(ensureLocalAccount(f.instance, f.signal, owner).then(() => "success"),@@ -124,8 +145,7 @@ it("does not mark an existing owner provisioned when its saved password cannot lit("confirms a committed owner after a command failure without exposing command diagnostics", async () => {const f = await fixture();let attempts = 0;- vi.stubGlobal(- "fetch",+ stubFetch(vi.fn(async () => new Response(null, { status: ++attempts === 1 ? 401 : 200 }),),@@ -137,10 +157,7 @@ it("confirms a committed owner after a command failure without exposing command});it("keeps credentials private when command creation and login both fail", async () => {const f = await fixture();- vi.stubGlobal(- "fetch",- vi.fn(async () => new Response(null, { status: 401 })),- );+ stubFetch(vi.fn(async () => new Response(null, { status: 401 })));provisionOwner.mockRejectedValue(new Error("private-server-secret"));const message = await ensureLocalAccount(f.instance, f.signal, owner).then(() => "success",@@ -152,8 +169,7 @@ it("keeps credentials private when command creation and login both fail", async});it("does not create an owner on an unexpected login error or leak server response secrets", async () => {const f = await fixture();- vi.stubGlobal(- "fetch",+ stubFetch(vi.fn(async () => new Response("private-server-secret", { status: 503 })),);await expect(@@ -189,10 +205,7 @@ it("does not expose credential text from malformed JSON or continue after cancel});it("accepts first-time custom credentials and reuses them without resetting", async () => {const f = await fixture();- vi.stubGlobal(- "fetch",- vi.fn(async () => new Response(null, { status: 200 })),- );+ stubFetch(vi.fn(async () => new Response(null, { status: 200 })));const expected = {email: "[email protected]",password: "custom-password-123",@@ -247,8 +260,7 @@ it("rejects invalid custom credentials before writing or calling the account serit("uses a source owner provisioner with saved credentials and confirms login", async () => {const f = await fixture();let attempts = 0;- vi.stubGlobal(- "fetch",+ stubFetch(vi.fn(async () => new Response(null, { status: ++attempts === 1 ? 401 : 200 }),),@@ -268,7 +280,7 @@ it("uses a source owner provisioner with saved credentials and confirms login",});it("reads the server identity from the private instance files", async () => {const { readLocalIdentity } = await import("./account.js");- const f = await fixture();+ const f = await fixture({ identity: false });const key = Buffer.alloc(32, 7);await expect(readLocalIdentity(f.instance)).rejects.toThrow("Linger on this computer has no server identity yet.",@@ -307,8 +319,7 @@ it("recreates a missing owner when the private file is already marked provisione) + "\n";await writeFile(f.file, saved, { mode: 0o600 });let created = false;- vi.stubGlobal(- "fetch",+ stubFetch(vi.fn(async (url: string) =>new Response(null, {@@ -333,7 +344,12 @@ it("recreates a missing owner when the private file is already marked provisione.mock.calls.map(([url]) => new URL(url instanceof Request ? url.url : url).pathname,),- ).toEqual(["/v0/auth/login", "/v0/auth/login", "/v0/auth/logout"]);+ ).toEqual([+ "/v0/local/identity",+ "/v0/auth/login",+ "/v0/auth/login",+ "/v0/auth/logout",+ ]);});it("keeps an existing provisioned owner ready after the user changes their password", async () => {const f = await fixture();@@ -343,8 +359,7 @@ it("keeps an existing provisioned owner ready after the user changes their passwprovisioned: true,});await writeFile(f.file, saved, { mode: 0o600 });- vi.stubGlobal(- "fetch",+ stubFetch(vi.fn(async () => new Response("server-private-secret", { status: 401 })),);provisionOwner.mockResolvedValue(undefined);@@ -356,7 +371,7 @@ it("keeps an existing provisioned owner ready after the user changes their passwfile: f.file,});expect(provisionOwner).toHaveBeenCalledOnce();- expect(fetch).toHaveBeenCalledTimes(2);+ expect(fetch).toHaveBeenCalledTimes(3);expect(await readFile(f.file, "utf8")).toBe(saved);});it("does not provision an already marked account when its login service fails", async () => {@@ -367,8 +382,7 @@ it("does not provision an already marked account when its login service fails",provisioned: true,});await writeFile(f.file, saved, { mode: 0o600 });- vi.stubGlobal(- "fetch",+ stubFetch(vi.fn(async () => new Response("server-private-secret", { status: 503 })),);await expect(ensureLocalAccount(f.instance, f.signal, owner)).rejects.toThrow(@@ -385,8 +399,7 @@ it("preserves a provisioned account and hides details on a network failure", asyprovisioned: true,});await writeFile(f.file, saved, { mode: 0o600 });- vi.stubGlobal(- "fetch",+ stubFetch(vi.fn(async () => {throw new Error("server-private-secret");}),@@ -406,8 +419,7 @@ it("does not trust a provisioned marker when owner confirmation and login both fprovisioned: true,});await writeFile(f.file, saved, { mode: 0o600 });- vi.stubGlobal(- "fetch",+ stubFetch(vi.fn(async () => new Response("server-private-secret", { status: 401 })),);provisionOwner.mockRejectedValue(new Error("private-owner-command-failure"));@@ -427,8 +439,7 @@ it.each([429, 503])(});await writeFile(f.file, saved, { mode: 0o600 });let calls = 0;- vi.stubGlobal(- "fetch",+ stubFetch(vi.fn(async () =>new Response(null, { status: ++calls === 1 ? 401 : status }),@@ -452,13 +463,35 @@ it("does not report an existing provisioned owner ready after cancellation", asyprovisioned: true,});await writeFile(f.file, saved, { mode: 0o600 });- vi.stubGlobal(- "fetch",- vi.fn(async () => new Response(null, { status: 401 })),- );+ stubFetch(vi.fn(async () => new Response(null, { status: 401 })));provisionOwner.mockImplementation(async () => controller.abort());await expect(ensureLocalAccount(f.instance, controller.signal, owner),).rejects.toThrow();expect(await readFile(f.file, "utf8")).toBe(saved);});++it("sends no password to another program answering at the origin", async () => {+ const f = await fixture();+ const requests: string[] = [];+ for (const answer of [+ () => Response.json({ proof: "forged" }),+ () => new Response("Not Found", { status: 404 }),+ ]) {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string) => {+ requests.push(new URL(url).pathname);+ return answer();+ }),+ );+ await expect(+ ensureLocalAccount(f.instance, f.signal, owner),+ ).rejects.toThrow(+ "Another program is answering at http://localhost:3000, so Linger cannot use port 3000.",+ );+ }+ expect(requests).toEqual(["/v0/local/identity", "/v0/local/identity"]);+ expect(provisionOwner).not.toHaveBeenCalled();+ expect(JSON.parse(await readFile(f.file, "utf8")).provisioned).toBe(false);+});diff --git a/packages/local-installation/src/account.ts b/packages/local-installation/src/account.tsindex 072fc6d8..56f4180d 100644--- a/packages/local-installation/src/account.ts+++ b/packages/local-installation/src/account.ts@@ -1,5 +1,5 @@import { windowsPrivatePath } from "./windows-private.js";-import { randomBytes } from "node:crypto";+import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";import { lstat, readFile } from "node:fs/promises";import path from "node:path";import { readLocalIdentityKey, type Instance } from "./instance.js";@@ -94,6 +94,18 @@ interface LocalAccount {provisioned: boolean;}+// Whether the owner account exists. Until it does, nothing outside the+// installer keeps the product origin. An unreadable file counts as existing.+export async function localAccountProvisioned(root: string): Promise<boolean> {+ const text = await readPrivate(path.join(root, "local-account.json"));+ if (text === undefined) return false;+ try {+ return (JSON.parse(text) as Partial<LocalAccount>).provisioned !== false;+ } catch {+ return true;+ }+}+// Blocks private login reads during database replacement until the account// step has established the owner in the new database.export async function unprovisionLocalAccount(root: string): Promise<void> {@@ -116,6 +128,103 @@ export async function unprovisionLocalAccount(root: string): Promise<void> {);}+// What TeamHub answers a challenge with (internal/localidentity).+export const localIdentityProof = (+ key: Uint8Array,+ nonce: string,+ origin: string,+): Buffer =>+ createHmac("sha256", key)+ .update(`linger-local-identity\n${nonce}\n${origin}`)+ .digest();++// The server did not prove it holds the key; says what failed, never with what.+export class LocalIdentityError extends Error {+ readonly reason: string;++ constructor(reason: string, options?: ErrorOptions) {+ super(`The local server did not prove its identity (${reason}).`, options);+ this.name = "LocalIdentityError";+ this.reason = reason;+ }+}++// Asks the server at `url` to prove it holds this installation's identity+// key for `origin`, with a fresh nonce each time, so an earlier answer+// proves nothing.+export async function proveLocalIdentity(options: {+ url: string | URL;+ origin: string;+ key: Uint8Array;+ signal: AbortSignal;+ fetch?: typeof fetch;+}): Promise<void> {+ const nonce = randomBytes(32).toString("base64url");+ let proof: unknown;+ try {+ const response = await (options.fetch ?? fetch)(options.url, {+ method: "POST",+ headers: {+ accept: "application/json",+ "content-type": "application/json",+ },+ body: JSON.stringify({ nonce }),+ redirect: "error",+ signal: options.signal,+ });+ if (!response.ok) {+ await response.body?.cancel();+ throw new LocalIdentityError(`status ${response.status}`);+ }+ proof = ((await response.json()) as { proof?: unknown } | null)?.proof;+ } catch (error) {+ if (error instanceof LocalIdentityError) throw error;+ throw new LocalIdentityError(+ error instanceof SyntaxError ? "invalid answer" : "no answer",+ { cause: error },+ );+ }+ const expected = localIdentityProof(options.key, nonce, options.origin);+ const actual =+ typeof proof === "string" && /^[A-Za-z0-9_-]{43}$/.test(proof)+ ? Buffer.from(proof, "base64url")+ : undefined;+ if (+ !actual ||+ actual.length !== expected.length ||+ !timingSafeEqual(actual, expected)+ )+ throw new LocalIdentityError("wrong proof");+}++const serviceUnavailable = () =>+ new Error(+ "The local account service is unavailable. Reopen Linger to retry; account credentials are preserved.",+ );+// The password goes only to a server that proves, through the origin, that+// it is this instance's TeamHub: another program can answer on `localhost`,+// which macOS tries on ::1 first.+async function proveOrigin(instance: Instance, signal: AbortSignal) {+ const key = await readLocalIdentityKey(instance.root);+ if (!key) throw new Error("The instance has no server identity key.");+ try {+ await proveLocalIdentity({+ url: `${instance.origin}/v0/local/identity`,+ origin: instance.origin,+ key: Buffer.from(key, "base64"),+ signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),+ });+ } catch (error) {+ signal.throwIfAborted();+ if (!(error instanceof LocalIdentityError) || error.reason === "no answer")+ throw serviceUnavailable();+ throw new Error(+ `Another program is answering at ${instance.origin}, so Linger cannot use port ${new URL(instance.origin).port}. Quit that program, then reopen Linger to retry; account credentials are preserved.`,+ { cause: error },+ );+ }+}+// Called under the instance lock. TeamHub owns deployment-owner creation;// its idempotent command never resets an existing account password.export async function ensureLocalAccount(@@ -173,6 +282,7 @@ export async function ensureLocalAccount(}const email = account.email;signal.throwIfAborted();+ await proveOrigin(instance, signal);async function post(route: string, body: unknown, cookie?: string) {let response: Response;try {@@ -188,9 +298,7 @@ export async function ensureLocalAccount(});} catch {signal.throwIfAborted();- throw new Error(- "The local account service is unavailable. Reopen Linger to retry; account credentials are preserved.",- );+ throw serviceUnavailable();}await response.body?.cancel();return response;diff --git a/packages/local-installation/src/instance.ts b/packages/local-installation/src/instance.tsindex 250a366b..bf08ddc2 100644--- a/packages/local-installation/src/instance.ts+++ b/packages/local-installation/src/instance.ts@@ -1,6 +1,5 @@import { createHash, randomBytes } from "node:crypto";import { chmod, lstat, readdir } from "node:fs/promises";-import net from "node:net";import { windowsPrivatePath } from "./windows-private.js";import {atomicPrivate,@@ -8,6 +7,7 @@ import {readPrivate,} from "./private-files.js";import { LEGACY_PROJECT_PREFIX, lingerHome } from "./home.js";+import { freePort, portFree } from "./ports.js";import path from "node:path";import { DatabaseSync } from "node:sqlite";import { parseEnv } from "node:util";@@ -159,16 +159,6 @@ export function validSourceDescriptor(instance: Instance): boolean {source.ports.web === instance.port,);}-async function available(port: number): Promise<number> {- return new Promise((resolve, reject) => {- const server = net.createServer();- server.once("error", reject);- server.listen(port, "127.0.0.1", () => {- const address = server.address() as net.AddressInfo;- server.close((error) => (error ? reject(error) : resolve(address.port)));- });- });-}export async function initializeInstance(options: InstanceOptions,): Promise<Instance> {@@ -220,19 +210,10 @@ export async function initializeInstance(}if (options.port !== undefined && reserved.has(options.port))throw new Error("Port is reserved by another instance");- let port: number;- try {- port = await available(- options.port ?? (reserved.has(3000) ? 0 : 3000),- );- } catch (error) {- if (options.port !== undefined)- throw new Error(`Port ${options.port} is occupied or unavailable`, {- cause: error,- });- port = await available(0);- }- while (reserved.has(port)) port = await available(0);+ if (options.port !== undefined && !(await portFree(options.port)))+ throw new Error(`Port ${options.port} is occupied or unavailable`);+ const port =+ options.port ?? (await freePort(reserved, { preferred: 3000 }));const releaseDir = options.releaseDir? path.resolve(options.releaseDir): "";diff --git a/packages/local-installation/src/native-livekit.ts b/packages/local-installation/src/native-livekit.tsindex 3d6380a9..288002ee 100644--- a/packages/local-installation/src/native-livekit.ts+++ b/packages/local-installation/src/native-livekit.ts@@ -1,10 +1,9 @@import { randomBytes } from "node:crypto";-import { createSocket } from "node:dgram";-import net from "node:net";import path from "node:path";import { parseEnv } from "node:util";import { setTimeout as delay } from "node:timers/promises";import { atomicPrivate, readPrivate } from "./instance.js";+import { freePort, portFree } from "./ports.js";import {inspectNativeListeners,inspectNativeProcess,@@ -55,56 +54,48 @@ export async function readLiveKitSettings(const text = await readPrivate(settingsFile(root));return text === undefined ? undefined : parseSettings(text);}-async function freeTcpPort(reserved: Set<number>): Promise<number> {- for (;;) {- const port = await new Promise<number>((resolve, reject) => {- const server = net.createServer();- server.once("error", reject);- server.listen(0, "127.0.0.1", () => {- const { port } = server.address() as net.AddressInfo;- server.close((error) => (error ? reject(error) : resolve(port)));- });- });- if (!reserved.has(port)) {- reserved.add(port);- return port;- }- }-}-async function freeUdpPort(reserved: Set<number>): Promise<number> {- for (;;) {- const port = await new Promise<number>((resolve, reject) => {- const socket = createSocket("udp4");- socket.once("error", reject);- socket.bind(0, "127.0.0.1", () => {- const { port } = socket.address();- socket.close(() => resolve(port));- });- });- if (!reserved.has(port)) {- reserved.add(port);- return port;- }- }-}/*** The instance's LiveKit ports and keys, made once and kept in the* owner-only livekit.env so services and LiveKit agree across restarts.- * `reserved` holds the ports other instances and services use.+ * `reserved` holds the ports other instances and services use. While+ * LiveKit is stopped, a port another program took since moves to a free one,+ * reported through `onMoved`.*/export async function prepareLiveKitSettings(root: string,reserved: Set<number>,+ onMoved?: (message: string) => void,): Promise<LiveKitSettings> {const existing = await readLiveKitSettings(root);- if (existing) return existing;- const settings: LiveKitSettings = {- httpPort: await freeTcpPort(reserved),- rtcPort: await freeUdpPort(reserved),- // LiveKit signs access tokens with the secret; it needs 32+ characters.- apiKey: `API${randomBytes(6).toString("hex")}`,- apiSecret: randomBytes(32).toString("hex"),- };+ let settings: LiveKitSettings;+ if (!existing)+ settings = {+ httpPort: await freePort(reserved),+ rtcPort: await freePort(reserved, { protocol: "udp" }),+ // LiveKit signs access tokens with the secret; it needs 32+ characters.+ apiKey: `API${randomBytes(6).toString("hex")}`,+ apiSecret: randomBytes(32).toString("hex"),+ };+ else if ((await inspectNativeProcess(root, "livekit")).running)+ return existing;+ else {+ settings = { ...existing };+ for (const [name, protocol] of [+ ["httpPort", "tcp"],+ ["rtcPort", "udp"],+ ] as const) {+ if (await portFree(existing[name], protocol)) continue;+ settings[name] = await freePort(reserved, { protocol });+ onMoved?.(+ `Port ${existing[name]} is in use by another program; Linger's livekit uses port ${settings[name]} instead.\n`,+ );+ }+ if (+ settings.httpPort === existing.httpPort &&+ settings.rtcPort === existing.rtcPort+ )+ return existing;+ }await atomicPrivate(settingsFile(root),[diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.tsindex 1550aac1..c0ed0ef2 100644--- a/packages/local-installation/src/native-source-flow.test.ts+++ b/packages/local-installation/src/native-source-flow.test.ts@@ -14,10 +14,12 @@ import {mkdir,mkdtemp,readFile,+ readdir,realpath,rm,writeFile,} from "node:fs/promises";+import net from "node:net";import path from "node:path";import os from "node:os";import { afterEach, expect, test, vi } from "vitest";@@ -26,6 +28,7 @@ import {installNativeSource,stopNativeSource,} from "./native-source.js";+import { localIdentityProof } from "./account.js";import { runProcess } from "./process.js";import {installAppleDeveloperTools,@@ -164,16 +167,40 @@ async function fixture() {});vi.stubGlobal("fetch",- vi.fn(- async (url) =>- new Response("{}", {- status:- String(url).endsWith("/v0/auth/login") && !provisioned ? 401 : 200,- }),+ vi.fn(async (url, init?: RequestInit) =>+ String(url).endsWith("/v0/local/identity")+ ? identityProof(home, String(url), init)+ : new Response("{}", {+ status:+ String(url).endsWith("/v0/auth/login") && !provisioned+ ? 401+ : 200,+ }),),);return { home, repo, running };}+// The instance's TeamHub answering at its origin (see account.ts).+async function identityProof(home: string, url: string, init?: RequestInit) {+ const origin = new URL(url).origin;+ const { nonce } = JSON.parse(init?.body as string) as { nonce: string };+ for (const name of await readdir(path.join(home, "instances"))) {+ const root = path.join(home, "instances", name);+ const instance = JSON.parse(+ await readFile(path.join(root, "instance.json"), "utf8"),+ ) as { origin: string };+ if (instance.origin !== origin) continue;+ const key = await readFile(path.join(root, "local-identity.key"), "utf8");+ return Response.json({+ proof: localIdentityProof(+ Buffer.from(key.trim(), "base64"),+ nonce,+ origin,+ ).toString("base64url"),+ });+ }+ return new Response(null, { status: 404 });+}test("native services and owner creation continue while selected Runtime authentication is pending", async () => {const f = await fixture();vi.mocked(prepareRuntime).mockResolvedValue({@@ -671,6 +698,51 @@ test("a full disk ends startup at once instead of at the deadline", async () =>);});+test("a service that stops because another program took its port names the port", async () => {+ const f = await fixture();+ vi.mocked(prepareRuntime).mockResolvedValue({+ code: 0,+ state: "ready",+ message: "ready",+ });+ // Another program takes TeamHub's port after Linger chose it, so TeamHub+ // exits at once.+ const holder = net.createServer();+ let port: number | undefined;+ vi.mocked(startNativeProcess).mockImplementation(async (options) => {+ if (options.name !== "teamhub") {+ f.running.add(options.name);+ return { running: true, pid: 100 };+ }+ const instance = JSON.parse(+ await readFile(+ path.join(f.home, "instances", "native-flow", "instance.json"),+ "utf8",+ ),+ ) as { source: { ports: { teamhub: number } } };+ port = instance.source.ports.teamhub;+ await new Promise<void>((resolve) =>+ holder.listen(port, "127.0.0.1", resolve),+ );+ return { running: false };+ });+ try {+ const result = await installNativeSource({+ ...f,+ name: "native-flow",+ setupChoice: "pi",+ signal: new AbortController().signal,+ onEvent: () => {},+ });+ expect(result).toMatchObject({ code: 1 });+ expect(result.message).toContain(+ `Native teamhub cannot listen on port ${port}: another program is using it.`,+ );+ } finally {+ await new Promise((resolve) => holder.close(resolve));+ }+});+test("a port an earlier TeamHub still holds fails startup instead of passing its health check", async () => {const f = await fixture();vi.mocked(prepareRuntime).mockResolvedValue({diff --git a/packages/local-installation/src/native-source.test.ts b/packages/local-installation/src/native-source.test.tsindex 2a6f1435..52d22553 100644--- a/packages/local-installation/src/native-source.test.ts+++ b/packages/local-installation/src/native-source.test.ts@@ -1,4 +1,6 @@import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";+import { createSocket } from "node:dgram";+import net from "node:net";import { tmpdir } from "node:os";import path from "node:path";import { parseEnv } from "node:util";@@ -14,10 +16,37 @@ import {} from "./native-source.js";const roots: string[] = [];+const listeners: (() => Promise<void>)[] = [];afterEach(async () => {+ await Promise.all(listeners.splice(0).map((close) => close()));for (const root of roots.splice(0))await rm(root, { recursive: true, force: true });});+// Another program takes `port`, on ::1 alone when the computer has it.+async function occupy(port: number, protocol: "tcp" | "udp" = "tcp") {+ for (const host of ["::1", "127.0.0.1"])+ try {+ if (protocol === "udp") {+ const socket = createSocket(host === "::1" ? "udp6" : "udp4");+ await new Promise<void>((resolve, reject) => {+ socket.once("error", reject);+ socket.bind(port, host, resolve);+ });+ listeners.push(() => new Promise((done) => socket.close(() => done())));+ } else {+ const server = net.createServer((socket) => socket.end());+ await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen({ port, host }, resolve);+ });+ listeners.push(() => new Promise((done) => server.close(() => done())));+ }+ return;+ } catch {+ // No ::1 here; take IPv4 loopback instead.+ }+ throw new Error(`Cannot occupy port ${port}`);+}async function fixture() {const home = await mkdtemp(path.join(tmpdir(), "native-source-"));roots.push(home);@@ -181,3 +210,65 @@ test("an owned native instance follows a new checkout and keeps its data", asyncexpect(saved?.releaseDir).toBe(next);expect(saved?.source).toEqual(moved.instance.source);});+test("a resumed instance moves off ports another program took", async () => {+ const f = await fixture();+ const options = { home: f.home, name: "native-test" };+ const first = await prepareNativeConfiguration(f.repo, options);+ const before = first.instance.source!.ports;+ const livekit = (await readLiveKitSettings(first.instance.root))!;+ await occupy(before.web);+ await occupy(before.teamhub);+ await occupy(before.postgres);+ await occupy(livekit.httpPort);+ await occupy(livekit.rtcPort, "udp");++ const second = await prepareNativeConfiguration(f.repo, options);+ const after = second.instance.source!.ports;+ for (const name of ["web", "teamhub", "postgres"] as const)+ expect(after[name]).not.toBe(before[name]);+ expect(after.nodeServices).toBe(before.nodeServices);+ expect(after.document).toBe(before.document);+ // Without an owner account nothing keeps the origin yet, so it moves too.+ expect(second.instance.port).toBe(after.web);+ expect(second.instance.origin).toBe(`http://localhost:${after.web}`);+ expect(await loadInstance(options)).toEqual(second.instance);+ expect(second.env.WEB_PUBLIC_ORIGIN).toBe(second.instance.origin);+ expect(second.env.TEAMHUB_HTTP_ADDRESS).toBe(`127.0.0.1:${after.teamhub}`);+ expect(second.env.TEAMHUB_DATABASE_URL).toContain(+ `:${after.postgres}/simplexai`,+ );+ const moved = (await readLiveKitSettings(first.instance.root))!;+ expect(moved.httpPort).not.toBe(livekit.httpPort);+ expect(moved.rtcPort).not.toBe(livekit.rtcPort);+ expect(moved.apiSecret).toBe(livekit.apiSecret);+ expect(second.env.LIVEKIT_URL).toBe(`ws://127.0.0.1:${moved.httpPort}`);+ expect(second.warnings.join("")).toContain(+ `Port ${before.teamhub} is in use by another program; Linger's teamhub uses port ${after.teamhub} instead.`,+ );+ expect(second.warnings).toHaveLength(5);++ // Once the owner account exists, the browser session and the desktop app+ // keep the origin: the web port stays and its service reports the program.+ await writeFile(+ path.join(first.instance.root, "local-account.json"),+ JSON.stringify({ provisioned: true }),+ { mode: 0o600 },+ );+ await occupy(after.web);+ const third = await prepareNativeConfiguration(f.repo, options);+ expect(third.instance.port).toBe(after.web);+ expect(third.instance.source!.ports).toEqual(after);+ expect(third.warnings).toEqual([]);++ // A database set aside from an older install marks the account to be made+ // again, but that install's desktop still keeps the origin.+ await writeFile(+ path.join(first.instance.root, "local-account.json"),+ JSON.stringify({ provisioned: false }),+ { mode: 0o600 },+ );+ await mkdir(path.join(first.instance.root, "simplex-backup-earlier"));+ const fourth = await prepareNativeConfiguration(f.repo, options);+ expect(fourth.instance.port).toBe(after.web);+ expect(fourth.warnings).toEqual([]);+});diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.tsindex 1acc5038..29a4c872 100644--- a/packages/local-installation/src/native-source.ts+++ b/packages/local-installation/src/native-source.ts@@ -1,4 +1,5 @@import { prepareFoundationServices } from "./foundation-services.js";+import { portFree } from "./ports.js";import { prepareModelGateway, stopModelGateway } from "./model-gateway.js";import { createHash } from "node:crypto";import { constants } from "node:fs";@@ -156,17 +157,18 @@ export async function checkNativeSourceEnvironment(options: {}}}-export async function probeNativeSourceServices(- instance: Instance,- signal?: AbortSignal,-) {- const source = requireNative(instance);- const endpoints = [+const probeEndpoints = (source: NonNullable<Instance["source"]>) =>+ [["web", "web", source.ports.web, "/healthz"],["teamhub", "teamhub", source.ports.teamhub, "/healthz"],["node-services", "node-services", source.ports.nodeServices, "/readyz"],["document-runtime", "node-services", source.ports.document, "/readyz"],] as const;+export async function probeNativeSourceServices(+ instance: Instance,+ signal?: AbortSignal,+) {+ const endpoints = probeEndpoints(requireNative(instance));const states = await inspectNativeListeners(instance.root,endpoints.map(([, name, port]) => ({ name, port })),@@ -298,10 +300,17 @@ async function waitHealthy(const failure = await startupFailure(instance, ends);if (failure) throw new Error(failure);for (const name of watchedServices)- if (!(await inspectNativeProcess(instance.root, name)).running)+ if (!(await inspectNativeProcess(instance.root, name)).running) {+ // With the service gone, whatever holds its port is another program.+ for (const [, owner, port] of probeEndpoints(instance.source!))+ if (owner === name && !(await portFree(port)))+ throw new Error(+ `Native ${name} cannot listen on port ${port}: another program is using it. Quit that program, then try again.`,+ );throw new Error(`Native ${name} stopped during startup. Inspect ${path.join(instance.root, "native/logs", `${name}.log`)}.`,);+ }if (Date.now() >= deadline) {const waiting = checks.filter((row) => !row.ready)diff --git a/packages/local-installation/src/ports.test.ts b/packages/local-installation/src/ports.test.tsnew file mode 100644index 00000000..f0b34dea--- /dev/null+++ b/packages/local-installation/src/ports.test.ts@@ -0,0 +1,73 @@+import { createSocket } from "node:dgram";+import net from "node:net";+import { afterEach, expect, it } from "vitest";+import { freePort, portFree } from "./ports.js";++const open: (() => Promise<void>)[] = [];+afterEach(async () => {+ await Promise.all(open.splice(0).map((close) => close()));+});+// Another program's listener on one address only; undefined when the+// computer has no such address.+async function listen(host: string, port = 0): Promise<number | undefined> {+ const server = net.createServer((socket) => socket.end());+ try {+ await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen({ port, host }, resolve);+ });+ } catch {+ return undefined;+ }+ open.push(() => new Promise((resolve) => server.close(() => resolve())));+ return (server.address() as net.AddressInfo).port;+}++it("treats a port taken on IPv4 loopback only as used", async () => {+ const port = (await listen("127.0.0.1"))!;+ expect(await portFree(port)).toBe(false);+});++it("treats a port taken on IPv6 loopback only as used", async (context) => {+ const port = await listen("::1");+ if (port === undefined) return context.skip("This computer has no ::1.");+ expect(await portFree(port)).toBe(false);+});++it("finds a port that is free on both loopback addresses", async () => {+ const port = await freePort(new Set());+ expect(await portFree(port)).toBe(true);+ // Both addresses accept it, so nothing else answers on `localhost`.+ expect(await listen("127.0.0.1", port)).toBe(port);+});++it("keeps the preferred port when it is free and moves off it when it is taken", async () => {+ const preferred = await freePort(new Set());+ const reserved = new Set<number>();+ expect(await freePort(reserved, { preferred })).toBe(preferred);+ expect(reserved).toEqual(new Set([preferred]));++ const taken = (await listen("::1")) ?? (await listen("127.0.0.1"))!;+ const moved = await freePort(reserved, { preferred: taken });+ expect(moved).not.toBe(taken);+ expect(moved).not.toBe(preferred);+ expect(reserved.has(moved)).toBe(true);+});++it("never returns a reserved port", async () => {+ const preferred = await freePort(new Set());+ expect(await freePort(new Set([preferred]), { preferred })).not.toBe(+ preferred,+ );+});++it("checks UDP ports separately", async () => {+ const socket = createSocket("udp4");+ await new Promise<void>((resolve) => socket.bind(0, "127.0.0.1", resolve));+ open.push(() => new Promise((resolve) => socket.close(() => resolve())));+ const { port } = socket.address();+ expect(await portFree(port, "udp")).toBe(false);+ const moved = await freePort(new Set(), { preferred: port, protocol: "udp" });+ expect(moved).not.toBe(port);+ expect(await portFree(moved, "udp")).toBe(true);+});diff --git a/packages/local-installation/src/ports.ts b/packages/local-installation/src/ports.tsnew file mode 100644index 00000000..4b648fd2--- /dev/null+++ b/packages/local-installation/src/ports.ts@@ -0,0 +1,117 @@+import { createSocket } from "node:dgram";+import net from "node:net";++// The addresses a loopback service can be reached on. The product origin is+// `http://localhost:<port>`, which macOS resolves to ::1 first, so a program+// listening on ::1 alone would answer in place of a service that bound+// 127.0.0.1 without an error. A port is free only when both can be bound and+// neither answers.+const LOOPBACK = ["127.0.0.1", "::1"] as const;+// A computer without IPv6 has no ::1; nothing can listen there either.+const NO_IPV6 = new Set(["EADDRNOTAVAIL", "EAFNOSUPPORT", "EINVAL"]);++type Protocol = "tcp" | "udp";++function bindable(+ port: number,+ host: string,+ protocol: Protocol,+): Promise<boolean> {+ const ipv6 = host.includes(":");+ return new Promise((resolve) => {+ const failed = (error: NodeJS.ErrnoException) =>+ resolve(ipv6 && NO_IPV6.has(error.code ?? ""));+ if (protocol === "udp") {+ const socket = createSocket(ipv6 ? "udp6" : "udp4");+ socket.once("error", (error) => {+ try {+ socket.close();+ } catch {+ // A socket that never bound is already closed.+ }+ failed(error);+ });+ socket.bind(port, host, () => socket.close(() => resolve(true)));+ return;+ }+ const server = net.createServer();+ server.once("error", failed);+ server.listen({ port, host, exclusive: true }, () =>+ server.close(() => resolve(true)),+ );+ });+}++// macOS lets a program bind one address under another program's listener on+// every address, so a successful bind does not prove nobody answers there.+function answers(port: number, host: string): Promise<boolean> {+ return new Promise((resolve) => {+ const socket = net.connect({ port, host, timeout: 500 });+ const done = (value: boolean) => {+ socket.destroy();+ resolve(value);+ };+ socket.once("connect", () => done(true));+ socket.once("error", () => done(false));+ socket.once("timeout", () => done(false));+ });+}++/** Whether no program uses `port` on IPv4 or IPv6 loopback. */+export async function portFree(+ port: number,+ protocol: Protocol = "tcp",+): Promise<boolean> {+ for (const host of LOOPBACK)+ if (!(await bindable(port, host, protocol))) return false;+ if (protocol === "udp") return true;+ const answered = await Promise.all(+ LOOPBACK.map((host) => answers(port, host)),+ );+ return !answered.includes(true);+}++function ephemeral(protocol: Protocol): Promise<number> {+ return new Promise((resolve, reject) => {+ if (protocol === "udp") {+ const socket = createSocket("udp4");+ socket.once("error", reject);+ socket.bind(0, "127.0.0.1", () => {+ const { port } = socket.address();+ socket.close(() => resolve(port));+ });+ return;+ }+ const server = net.createServer();+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => {+ const { port } = server.address() as net.AddressInfo;+ server.close((error) => (error ? reject(error) : resolve(port)));+ });+ });+}++/**+ * `preferred` when it is free, else a free port the system offers, never one+ * in `reserved` (the ports this home's instances keep); adds it to `reserved`.+ */+export async function freePort(+ reserved: Set<number>,+ options: { preferred?: number; protocol?: Protocol } = {},+): Promise<number> {+ const protocol = options.protocol ?? "tcp";+ let port = options.preferred;+ for (let attempt = 0; ; attempt++) {+ if (+ port !== undefined &&+ !reserved.has(port) &&+ (await portFree(port, protocol))+ ) {+ reserved.add(port);+ return port;+ }+ if (attempt >= 100)+ throw new Error("No free local port is available on this computer.");+ port = await ephemeral(protocol);+ }+}diff --git a/packages/local-installation/src/source-checkout.ts b/packages/local-installation/src/source-checkout.tsindex 612d72c1..4a53b916 100644--- a/packages/local-installation/src/source-checkout.ts+++ b/packages/local-installation/src/source-checkout.ts@@ -1,5 +1,4 @@import { lstat, readFile, readdir, realpath } from "node:fs/promises";-import net from "node:net";import path from "node:path";import { parseEnv } from "node:util";import {@@ -16,6 +15,14 @@ import {readLiveKitSettings,} from "./native-livekit.js";import { readUserEnvironment } from "./user-environment.js";+import { localAccountProvisioned } from "./account.js";+import { latestLegacyBackup } from "./legacy-database.js";+import {+ inspectNativeProcess,+ reclaimNativeOrphans,+ type NativeService,+} from "./native-process.js";+import { freePort, portFree } from "./ports.js";import type { SetupChoice } from "./setup-plan.js";import type { InstallerEvent } from "./events.js";@@ -74,22 +81,6 @@ export async function validateSourceRepository(}return repo;}-async function allocatePort(reserved: Set<number>): Promise<number> {- for (;;) {- const port = await new Promise<number>((resolve, reject) => {- const server = net.createServer();- server.once("error", reject);- server.listen(0, "127.0.0.1", () => {- const port = (server.address() as net.AddressInfo).port;- server.close((error) => (error ? reject(error) : resolve(port)));- });- });- if (!reserved.has(port)) {- reserved.add(port);- return port;- }- }-}// Points an instance at another checkout of the same source; its data and// ports stay.function rebind(instance: Instance, repo: string): void {@@ -120,6 +111,17 @@ export async function saveSourceBinding(instance: Instance): Promise<void> {JSON.stringify(stored, null, 2) + "\n",);}+// Which native service listens on each of the instance's ports.+const portOwners = {+ web: "web",+ teamhub: "teamhub",+ nodeServices: "node-services",+ document: "node-services",+ postgres: "postgres",+} as const satisfies Record<+ keyof NonNullable<Instance["source"]>["ports"],+ NativeService+>;export async function prepareSourceConfiguration(repository: string,options: {@@ -180,6 +182,8 @@ export async function prepareSourceConfiguration(if (livekit) reserved.add(livekit.httpPort).add(livekit.rtcPort);}}+ const livekit = await readLiveKitSettings(instance.root);+ if (livekit) reserved.add(livekit.httpPort).add(livekit.rtcPort);return reserved;};if (!instance.source) {@@ -188,10 +192,10 @@ export async function prepareSourceConfiguration(repo,ports: {web: instance.port,- teamhub: await allocatePort(reserved),- nodeServices: await allocatePort(reserved),- document: await allocatePort(reserved),- postgres: await allocatePort(reserved),+ teamhub: await freePort(reserved),+ nodeServices: await freePort(reserved),+ document: await freePort(reserved),+ postgres: await freePort(reserved),},};await atomicPrivate(@@ -199,6 +203,50 @@ export async function prepareSourceConfiguration(JSON.stringify(instance, null, 2) + "\n",);}+ const warnings: string[] = [];+ // A port another program took since it was chosen moves to a free one+ // while the service that listens there is stopped; the services then+ // restart because their environment names the new port. The web port is+ // the product origin, which the browser session, the desktop app and the+ // Computer keep once the account exists, so it moves only before that;+ // after it, the web service reports the program on its port. A database+ // set aside from an older install marks the account to be made again, but+ // that install's desktop still keeps the origin.+ const keepsOrigin =+ (await localAccountProvisioned(instance.root)) ||+ (await latestLegacyBackup(instance.root)) !== undefined;+ const movable = Object.entries(portOwners).filter(+ ([name]) => !keepsOrigin || name !== "web",+ ) as [keyof typeof portOwners, NativeService][];+ let reserved: Set<number> | undefined;+ for (const [name, owner] of movable) {+ const port = instance.source.ports[name];+ if (+ (await inspectNativeProcess(instance.root, owner)).running ||+ (await portFree(port))+ )+ continue;+ // On Windows the program may be one an earlier run left behind.+ await reclaimNativeOrphans(instance.root, {+ ports: [port],+ paths: [path.resolve(instance.root, "../.."), instance.root, repo],+ });+ if (await portFree(port)) continue;+ reserved ??= await reservedPorts();+ const next = await freePort(reserved);+ instance.source.ports[name] = next;+ if (name === "web") {+ instance.port = next;+ instance.origin = `http://localhost:${next}`;+ }+ await atomicPrivate(+ path.join(instance.root, "instance.json"),+ JSON.stringify(instance, null, 2) + "\n",+ );+ warnings.push(+ `Port ${port} is in use by another program; Linger's ${owner} uses port ${next} instead.\n`,+ );+ }const envFile = path.join(instance.root, "native.env");// The desktop installs from a source package that each update replaces,// so only the instance's user.env configures it; a developer's checkout@@ -223,7 +271,6 @@ export async function prepareSourceConfiguration(});}}- const warnings: string[] = [];const user = await readUserEnvironment(instance.root, (message) =>warnings.push(message),);@@ -257,11 +304,16 @@ export async function prepareSourceConfiguration(AGENT_HOME: path.join(instance.root, "data/agent"),COMPUTER_RELEASE_DIR: path.join(instance.root, "native/computer-release"),PORT: String(ports.web),- HOST: "127.0.0.1",+ // Both loopback addresses, so no other program answers for the origin.+ HOST: "127.0.0.1,::1",// Native runs its own LiveKit on loopback with this instance's ports// and keys....liveKitEnvironment(- await prepareLiveKitSettings(instance.root, await reservedPorts()),+ await prepareLiveKitSettings(+ instance.root,+ await reservedPorts(),+ (message) => warnings.push(message),+ ),),};const quote = (value: string) => {diff --git a/packages/local-installation/src/windows-state-security.test.ts b/packages/local-installation/src/windows-state-security.test.tsindex 6797c32b..39c93ded 100644--- a/packages/local-installation/src/windows-state-security.test.ts+++ b/packages/local-installation/src/windows-state-security.test.ts@@ -6,7 +6,11 @@ vi.mock("./windows-private.js", () => ({windowsPrivatePath: vi.fn().mockResolvedValue(undefined),}));import { windowsPrivatePath } from "./windows-private.js";-import { readLocalLogin, ensureLocalAccount } from "./account.js";+import {+ ensureLocalAccount,+ localIdentityProof,+ readLocalLogin,+} from "./account.js";import { prepareLocalEnrollment } from "./local-enrollment.js";import { readPrivate, type Instance } from "./instance.js";let root: string;@@ -51,9 +55,24 @@ it("uses Windows SID/DACL validation for existing local account reads and reuse"}),{ mode: 0o644 },);+ const key = Buffer.alloc(32, 9);+ await writeFile(+ path.join(root, "local-identity.key"),+ `${key.toString("base64")}\n`,+ { mode: 0o644 },+ );vi.stubGlobal("fetch",- vi.fn(async () => new Response(null, { status: 200 })),+ vi.fn(async (url: string, init?: RequestInit) => {+ if (!url.endsWith("/v0/local/identity"))+ return new Response(null, { status: 200 });+ const { nonce } = JSON.parse(init?.body as string) as { nonce: string };+ return Response.json({+ proof: localIdentityProof(key, nonce, instance.origin).toString(+ "base64url",+ ),+ });+ }),);const provisionOwner = vi.fn<() => Promise<void>>();expect((await readLocalLogin(instance)).email).toBe("[email protected]");@@ -65,7 +84,7 @@ it("uses Windows SID/DACL validation for existing local account reads and reuse").email,).toBe("[email protected]");expect(windowsPrivatePath).toHaveBeenCalledWith(file, "file");- expect(fetch).toHaveBeenCalledOnce();+ expect(fetch).toHaveBeenCalledTimes(2);expect(provisionOwner).not.toHaveBeenCalled();});it("checks the ACL before reusing a saved enrollment token", async () => {diff --git a/scripts/env-inventory.json b/scripts/env-inventory.jsonindex 399142b2..f397355c 100644--- a/scripts/env-inventory.json+++ b/scripts/env-inventory.json@@ -34,7 +34,7 @@},"web": {"owner": "code-default",- "description": "Port and allowed hosts read by the Vite dev server, and the address and port of the static host that serves the production build to Native. Code defaults apply, so it is not listed in .env.example.",+ "description": "Port and allowed hosts read by the Vite dev server, and the comma-separated addresses and port of the static host that serves the production build to Native. Code defaults apply, so it is not listed in .env.example.","names": ["HOST", "PORT", "WEB_ALLOWED_DEV_HOSTS"]},"teamhub-tools": {