diff --git a/docs/internal/adr/0003-one-typed-daemon-contract-behind-every-frontend.md b/docs/internal/adr/0003-one-typed-daemon-contract-behind-every-frontend.md index 6ce088b23..b2a5b3a9a 100644 --- a/docs/internal/adr/0003-one-typed-daemon-contract-behind-every-frontend.md +++ b/docs/internal/adr/0003-one-typed-daemon-contract-behind-every-frontend.md @@ -123,6 +123,12 @@ docs say this plainly. Records written before this field exist load with `ownerId` equal to `requesterId`. +**Amendment, 2026-10-30 (maintainer-authorized 2026-10-30).** On Windows the +endpoint is a named pipe whose name is derived from the data directory, and no +directory mode guards it. Another local account can create that pipe first and +receive the hello, and any token with it. Windows hosts are supported on +single-user machines only. + ### 5. Admin authority comes from a credential in the handshake, never from the socket `hello` carries the protocol range, capabilities, the principal, and an diff --git a/src/cli/environment.ts b/src/cli/environment.ts index 8aa9f049b..6df470e25 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -220,11 +220,8 @@ async function isStoppingRefusal(error: unknown): Promise { * the name check picks the candidate and `instanceof` against the real class proves it. */ async function isUnavailable(error: unknown): Promise { if (!(error instanceof Error) || error.name !== "IpcError") return false; - const { IpcError } = await import("../ports/index.js"); - return ( - error instanceof IpcError && - (error.code === "connection-refused" || error.code === "endpoint-not-found") - ); + const { isEndpointAbsent } = await import("../ports/index.js"); + return isEndpointAbsent(error); } async function moduleConfigEntries(): Promise { @@ -320,7 +317,9 @@ export function buildCliEnvironment( // Every consumer of this path is behind a command already inside `runCli`'s own try, where // that throw becomes the single structured error line the CLI reference promises instead of a // raw stack trace, and `simlock --help` (which needs no socket at all) never resolves it. - const connection = await connector.connect(resolveDaemonSocketPath(dataDirectory)); + const connection = await connector.connect( + resolveDaemonSocketPath(dataDirectory, ports.hostPlatform), + ); const credential = await resolveCredential(); return connectSimlockAdmin({ connection, @@ -373,8 +372,17 @@ export function buildCliEnvironment( connectAdmin: (resolveCredential, options) => autoLaunch.connect(resolveCredential, options), connectExistingAdmin: (resolveCredential) => connect(ipc, resolveCredential), daemonEndpointPresent: async () => { - const { resolveDaemonSocketPath } = await import("../ports/index.js"); - return filesystem.exists(resolveDaemonSocketPath(dataDirectory)); + const { isEndpointAbsent, isPipeEndpoint, resolveDaemonSocketPath } = + await import("../ports/index.js"); + const endpoint = resolveDaemonSocketPath(dataDirectory, ports.hostPlatform); + if (!isPipeEndpoint(endpoint)) return filesystem.exists(endpoint); + // why: `stat` on a live named pipe throws `EBUSY`, so a pipe is present exactly when something answers it. + try { + await (await ipc.connect(endpoint)).close(); + return true; + } catch (error: unknown) { + return !isEndpointAbsent(error); + } }, ...(env.SIMLOCK_ADMIN_TOKEN === undefined ? {} diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index ec1ddf99b..171517b69 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1590,6 +1590,7 @@ describe("CLI: admin credential resolution (ADR 0003 §5)", () => { daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), }); const exitCode = await runCli( @@ -1625,6 +1626,7 @@ describe("CLI: admin credential resolution (ADR 0003 §5)", () => { daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), }); const exitCode = await runCli(["daemon", "start"], output.environmentWith()); @@ -1658,6 +1660,7 @@ describe("CLI: admin credential resolution (ADR 0003 §5)", () => { daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), }); const exitCode = await runCli( @@ -1703,6 +1706,7 @@ describe("CLI: auto-launch's startup deadline (#663)", () => { daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), }; return { clock, ports }; @@ -1822,6 +1826,7 @@ describe("CLI: auto-launch's failed start (#672)", () => { daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), }); let settled = false; @@ -1871,6 +1876,7 @@ describe("CLI: auto-launch's daemon that exits while starting (#760)", () => { daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), }); let settled = false; @@ -1913,6 +1919,7 @@ describe("CLI: auto-launch's daemon that exits while starting (#760)", () => { daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), }); let settled = false; @@ -1976,6 +1983,7 @@ describe("CLI: auto-launch's daemon that lost the socket to another daemon (#760 daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), }); let settled = false; @@ -2021,6 +2029,7 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), }); let settled = false; @@ -7600,7 +7609,7 @@ describe("CLI: the daemon endpoint check", () => { it("buildCliEnvironment reports the daemon endpoint present only while its socket file exists", async () => { const filesystem = new MemoryFilesystem(); const environment = buildCliEnvironment(realCliEnvironmentPorts(filesystem), {}); - const socketPath = resolveDaemonSocketPath("/simlock"); + const socketPath = resolveDaemonSocketPath("/simlock", "linux"); expect(await environment.daemonEndpointPresent()).toBe(false); await filesystem.mkdirp("/simlock"); @@ -7609,6 +7618,37 @@ describe("CLI: the daemon endpoint check", () => { await filesystem.rm(socketPath); expect(await environment.daemonEndpointPresent()).toBe(false); }); + + it("on Windows reports the named pipe present while something answers it, and not after it closes", async () => { + const ipc = new MemoryIpcTransport(); + const environment = buildCliEnvironment( + { ...realCliEnvironmentPorts(), ipc, hostPlatform: "win32" }, + {}, + ); + + expect(await environment.daemonEndpointPresent()).toBe(false); + const listener = await ipc.listen( + resolveDaemonSocketPath("/simlock", "win32"), + () => undefined, + ); + expect(await environment.daemonEndpointPresent()).toBe(true); + await listener.close(); + expect(await environment.daemonEndpointPresent()).toBe(false); + }); + + it("on Windows counts a pipe that does not answer in time as present, since only a refused or missing one proves it gone", async () => { + const connector: IpcConnector = { + connect: async () => { + throw new IpcError("connection-timeout", "timed out", undefined); + }, + }; + const environment = buildCliEnvironment( + { ...realCliEnvironmentPorts(), ipc: connector, hostPlatform: "win32" }, + {}, + ); + + expect(await environment.daemonEndpointPresent()).toBe(true); + }); }); describe("CLI: requester id from the agent session", () => { @@ -8342,6 +8382,7 @@ function outputCapture(ports?: CliEnvironmentPorts, env: NodeJS.ProcessEnv = {}) requesterId: "test-requester", homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), filesystem: new MemoryFilesystem(), connectAdmin: async () => fakeClient(), @@ -8640,6 +8681,7 @@ function realCliEnvironmentPorts( daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), }; } @@ -9790,6 +9832,7 @@ describe("CLI: daemon install (#830)", () => { daemonHome: { role: options.role, dataDirectory, gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), service: { manager: serviceManager, @@ -10206,6 +10249,7 @@ describe("CLI: a start goes through the service (#830)", () => { daemonHome: { role: "worker", dataDirectory: root, gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), }); @@ -10266,6 +10310,7 @@ describe("CLI: a start through a service that fails (#830)", () => { daemonHome: { role: "worker", dataDirectory: directory, gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), }); let settled = false; @@ -10358,6 +10403,7 @@ describe("CLI: a service manager call fails, or the platform has none (#830)", ( daemonHome: { role: "worker", dataDirectory: root, gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), service: { manager, diff --git a/src/cli/lazy-loading.test.ts b/src/cli/lazy-loading.test.ts index 74e464286..3289a1105 100644 --- a/src/cli/lazy-loading.test.ts +++ b/src/cli/lazy-loading.test.ts @@ -61,6 +61,7 @@ async function environment(): Promise { daemonHome: { role: "worker", dataDirectory: home, gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), filesystem: new MemoryFilesystem(), ipc: new MemoryIpcTransport(), diff --git a/src/cli/lazy-parent-watch.test.ts b/src/cli/lazy-parent-watch.test.ts index 359b3f08b..9e5141d05 100644 --- a/src/cli/lazy-parent-watch.test.ts +++ b/src/cli/lazy-parent-watch.test.ts @@ -44,6 +44,7 @@ describe("the default parent watch", () => { clock: new FakeClock(0), homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), daemonHome: { role: "worker", diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 77f7fd250..f0e719577 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -55,7 +55,7 @@ Its stdout lines move the state; a failed line, a non-zero exit or a failed laun ## Connection (`server.ts`) -1. **Claim** — `DaemonEndpointHost.start`: creates the socket's directory `0700` when missing (an existing one keeps its mode); a live peer → `DaemonAlreadyRunningError`; a dead socket file is removed and claimed. Default `/daemon.sock`. +1. **Claim** — `DaemonEndpointHost.start`: creates the socket's directory `0700` when missing (an existing one keeps its mode); a live peer → `DaemonAlreadyRunningError`; a dead socket file is removed and claimed. Default `/daemon.sock`. On Windows the endpoint is a named pipe (`\\.\pipe\simlock-`): none of the file steps run, since a pipe has no directory and no stale entry, and a live one fails the bind with `address-in-use`. 2. **Hello** — first frame must be `hello`, else `HANDSHAKE_REQUIRED` and close. Role: the uplink connection is `admin` by acceptance; otherwise the resolver. Principal: `hello.principal`, else `SIMLOCK_AGENT_ID`, else the daemon's pid. Both are fixed for the connection's life. 3. **Version** — ranges overlap → highest common version. `PROTOCOL_VERSION_RANGE` @@ -110,7 +110,7 @@ Security model: cooperative identity, not a hostile-process boundary. - Every socket peer is the same OS user; file modes are the real boundary: the data directory is created `0700` (`DATA_DIRECTORY_MODE`) by whoever makes it first (the daemon, `NodeDaemonLauncher`, `config set`, service install), and its files are `0600`. - An existing directory is never chmod'ed; the daemon warns when group or others can reach it. + An existing directory is never chmod'ed; the daemon warns when group or others can reach it. On Windows the endpoint is a named pipe no directory guards: see [ports](../ports/AGENTS.md). - A `hello.principal` is a claim. Ownership checks stop accidents, not attacks. - Admin comes only from a credential at `hello`, never from the socket itself. - A worker that joins a fleet grants its gateway `admin` over itself. @@ -136,7 +136,7 @@ Security model: cooperative identity, not a hostile-process boundary. `eventLog.maxBytes` (256 MiB); usage rows are kept `metrics.retention` (90 days). `onSocketClaimed` starts it in both modes with the role and `metrics.retention`; `dispose` stops it last. A file that fails costs only history. A start the history refuses (a newer stored projection version, a failed migration) stops the daemon with reason `history-refused` and exit 1. `status.get` carries its `history`, also while starting. `inbox.get` (worker mode) runs `inboxItems` over its own `worker.list` view, `lease.list` and its queue. `usage.get` (both dispatchers, `usageAnswer` in `dispatch.ts`) reads the same file's usage rows through `core/usage` on a read thread; `main.ts` passes `historyPath` in both modes, and `dispose` stops the thread. `history.status().opened` false → `HISTORY_UNAVAILABLE`; a window ending before the oldest row → `HISTORY_NOT_KEPT`. -- SIGTERM to a running daemon runs `stop("signal")` and exits 0; one that arrives before the start finishes exits 0 at once (one handler in `main.ts`, the entry). A start that finds a daemon answering logs `Daemon already running` at `info` to the role's `daemon.log` and exits 0. A start that throws is logged by a fallback logger to the role's `daemon.log`; exit 1. An entry argument other than none or `--gateway` is logged to `/daemon.log` as "Daemon failed to start"; exit 1. +- SIGTERM to a running daemon runs `stop("signal")` and exits 0; one that arrives before the start finishes exits 0 at once (one handler in `main.ts`, the entry). A start that finds a daemon answering, or a connect to its endpoint timing out (`connection-timeout`: a pipe whose every instance is busy), logs `Daemon already running` at `info` to the role's `daemon.log` and exits 0. A start that throws is logged by a fallback logger to the role's `daemon.log`; exit 1. An entry argument other than none or `--gateway` is logged to `/daemon.log` as "Daemon failed to start"; exit 1. ## Rules diff --git a/src/daemon/connection-host.test.ts b/src/daemon/connection-host.test.ts index e1d0a9eb8..ee17d9ba1 100644 --- a/src/daemon/connection-host.test.ts +++ b/src/daemon/connection-host.test.ts @@ -88,6 +88,50 @@ describe("DaemonEndpointHost", () => { ); }); + it("claims a named pipe without touching the filesystem, which has nothing to make or remove", async () => { + const pipe = String.raw`\\.\pipe\simlock-0123456789abcdef`; + const untouchable = new Proxy(new MemoryFilesystem(), { + get: (_target, method) => () => { + throw new Error(`a pipe endpoint must not call filesystem.${String(method)}`); + }, + }); + const ipc = new MemoryIpcTransport(); + const host = new DaemonEndpointHost({ + connector: ipc, + endpoint: pipe, + filesystem: untouchable, + listenerFactory: ipc, + }); + + await host.start(() => undefined); + await expect((await ipc.connect(pipe)).close()).resolves.toBeUndefined(); + await host.stop(); + + await expect(ipc.connect(pipe)).rejects.toMatchObject({ code: "endpoint-not-found" }); + }); + + it("refuses a second claim of a live named pipe", async () => { + const pipe = String.raw`\\.\pipe\simlock-0123456789abcdef`; + const ipc = new MemoryIpcTransport(); + const first = new DaemonEndpointHost({ + connector: ipc, + endpoint: pipe, + filesystem: new MemoryFilesystem(), + listenerFactory: ipc, + }); + await first.start(() => undefined); + + await expect( + new DaemonEndpointHost({ + connector: ipc, + endpoint: pipe, + filesystem: new MemoryFilesystem(), + listenerFactory: ipc, + }).start(() => undefined), + ).rejects.toBeInstanceOf(DaemonAlreadyRunningError); + await first.stop(); + }); + it("is one-shot after stopping", async () => { const filesystem = new MemoryFilesystem(); const ipc = new MemoryIpcTransport(); diff --git a/src/daemon/connection-host.ts b/src/daemon/connection-host.ts index e0c93e3e8..3b099d487 100644 --- a/src/daemon/connection-host.ts +++ b/src/daemon/connection-host.ts @@ -7,7 +7,7 @@ import type { IpcListenerFactory, Logger, } from "../ports/index.js"; -import { DATA_DIRECTORY_MODE, IpcError, NoopLogger } from "../ports/index.js"; +import { DATA_DIRECTORY_MODE, IpcError, isPipeEndpoint, NoopLogger } from "../ports/index.js"; export interface ConnectionHost { readonly endpoint: string; @@ -25,6 +25,8 @@ export class DaemonAlreadyRunningError extends Error { /** * why: a second daemon must learn a daemon runs before it opens `state.db`, which migrates the * live daemon's file. A socket nobody answers is left for `DaemonEndpointHost.start` to recover. + * A connect that times out found a server holding the endpoint (a Windows pipe whose every + * instance is busy), so it refuses too. */ export async function refuseWhenDaemonAnswers(options: { readonly connector: IpcConnector; @@ -35,7 +37,7 @@ export async function refuseWhenDaemonAnswers(options: { await live.close(); } catch (error: unknown) { if (error instanceof IpcError && isUnavailable(error)) return; - throw error; + if (!(error instanceof IpcError) || error.code !== "connection-timeout") throw error; } throw new DaemonAlreadyRunningError(options.endpoint); } @@ -76,26 +78,33 @@ export class DaemonEndpointHost implements ConnectionHost { this.#logger = options.logger ?? new NoopLogger(); } - // fallow-ignore-next-line complexity -- endpoint claim, stale recovery, and bind form one lifecycle transaction. + // why: a named pipe is no file, so it has no directory to make and no stale entry to remove: it is gone when its server is, and a live one makes `listen` fail `address-in-use`. + get #isFile(): boolean { + return !isPipeEndpoint(this.endpoint); + } + + async #claimSocketFile(): Promise { + await this.options.filesystem.mkdirp(dirname(this.endpoint), { mode: DATA_DIRECTORY_MODE }); + if (!(await this.options.filesystem.exists(this.endpoint))) return; + try { + const live = await this.options.connector.connect(this.endpoint); + await live.close(); + throw new DaemonAlreadyRunningError(this.endpoint); + } catch (error: unknown) { + if (error instanceof DaemonAlreadyRunningError) throw error; + if (!(error instanceof IpcError) || !isUnavailable(error)) throw error; + this.#logger.warn("Recovered stale daemon socket", { + endpoint: this.endpoint, + reason: error.code, + }); + await this.options.filesystem.rm(this.endpoint); + } + } + async start(accept: (connection: IpcConnection) => void): Promise { if (this.#listener !== undefined || this.#stopped) throw new Error("Daemon endpoint host has already been started"); - await this.options.filesystem.mkdirp(dirname(this.endpoint), { mode: DATA_DIRECTORY_MODE }); - if (await this.options.filesystem.exists(this.endpoint)) { - try { - const live = await this.options.connector.connect(this.endpoint); - await live.close(); - throw new DaemonAlreadyRunningError(this.endpoint); - } catch (error: unknown) { - if (error instanceof DaemonAlreadyRunningError) throw error; - if (!(error instanceof IpcError) || !isUnavailable(error)) throw error; - this.#logger.warn("Recovered stale daemon socket", { - endpoint: this.endpoint, - reason: error.code, - }); - await this.options.filesystem.rm(this.endpoint); - } - } + if (this.#isFile) await this.#claimSocketFile(); try { this.#listener = await this.options.listenerFactory.listen(this.endpoint, accept); this.#ownsEndpoint = true; @@ -115,7 +124,7 @@ export class DaemonEndpointHost implements ConnectionHost { this.#listener = undefined; if (this.#ownsEndpoint) { this.#ownsEndpoint = false; - await this.options.filesystem.rm(this.endpoint); + if (this.#isFile) await this.options.filesystem.rm(this.endpoint); this.#logger.info("Released daemon socket", { endpoint: this.endpoint }); } } diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index f0f188985..b9038a2d4 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -50,8 +50,10 @@ import { type ServiceState, FakeSystemStats, FakeTcpProbe, + IpcError, JsonLinesLogger, MemoryFilesystem, + MemoryIpcTransport, MemoryLogSink, NodeFilesystem, NodeSqliteOpener, @@ -4447,6 +4449,18 @@ describe("startDaemon state.db", () => { expect(await readFile(join(directory, "state.db"))).toEqual(bytesBefore); }); + it("refuses to start as already running when connecting to its endpoint times out, as a Windows pipe whose every instance is busy does", async () => { + const memory = new MemoryIpcTransport(); + const ipc = { + connect: async () => { + throw new IpcError("connection-timeout", "timed out", undefined); + }, + listen: memory.listen.bind(memory), + }; + + await expect(start({ ipc })).rejects.toMatchObject({ name: "DaemonAlreadyRunningError" }); + }); + it("a SIMLOCK_DRIVERS_MODULE without a deviceDataTables export fails start naming it", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-main-no-tables-")); temporaryDirectories.push(directory); diff --git a/src/mcp/main.test.ts b/src/mcp/main.test.ts index 162dc78c7..51a1af54c 100644 --- a/src/mcp/main.test.ts +++ b/src/mcp/main.test.ts @@ -329,6 +329,7 @@ describe("MCP stdio lifecycle", () => { daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + hostPlatform: "linux", runTool: async () => ({ outcome: "not-found" }), filesystem: new MemoryFilesystem(), ipc: new MemoryIpcTransport(), diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index be4678885..84fc03655 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -20,7 +20,7 @@ Uses: nothing from other components. Imported by: every component that touches t | `UpdaterLauncher` | `updater-launcher.ts` | `NodeUpdaterLauncher` | `FakeUpdaterLauncher` | `launch` spawns the built entry of `src/updater/main.ts` detached with the Node that runs it: stdout a pipe (`lines`), stderr appended to the log, `exited` the exit code | | `ServiceManager` | `service-manager.ts` | `LaunchdServiceManager`, `SystemdServiceManager` (`productionServiceManager(platform)`: `darwin`, `linux`; `undefined` elsewhere) | `FakeServiceManager` | A per-user service for one role: `state` (`not-installed`, `installed`, `not-loaded`, `broken`), `install`, `uninstall`, `start` (kickstart); every `launchctl`/`plutil`/`systemctl --user` call has a 10 s limit; systemd writes `$XDG_CONFIG_HOME/systemd/user/.service` (absolute only, else `~/.config`); `serviceDefinition` builds the name, path, command and saved variables | | (factory) | `service-launcher.ts` | `launcherFor` | — | The one start choice for the CLI and the MCP server: kickstart a loaded service (`readOutput` is `daemon.log` since the start), else notice and spawn through `NodeDaemonLauncher`; `startTimeoutMessage` adds those lines at the deadline | -| `IpcConnector`, `IpcListenerFactory` | `ipc.ts` | `NodeIpcTransport` | `MemoryIpcTransport` | The daemon's unix socket | +| `IpcConnector`, `IpcListenerFactory` | `ipc.ts` | `NodeIpcTransport` | `MemoryIpcTransport` | The daemon's unix socket, or a named pipe on Windows | | `UplinkConnector`, `UplinkListenerFactory` | `uplink.ts` | `WebSocketUplinkConnector`, `WebSocketUplinkListenerFactory` | `MemoryUplinkTransport` | A worker's uplink to its gateway | | `LeaseSocket` | `lease-socket.ts` | the upgrade router (`upgrade-router.ts`): `/v1/uplink` to the uplink, `/v1/leases/{id}/` to the app's lease socket resolution, else 404; a ping every 15 s, no pong ends the socket | `MemoryLeaseSocket` | A module's end of a lease WebSocket: `send`, `close(code, reason)`, `onMessage`, `onClose` | | `Logger`, `LogSink` | `logger.ts` | `JsonLinesLogger`, `NodeFileLogSink` | `NoopLogger`, `MemoryLogSink` | JSON-line logs, `child(module)`, rotation | @@ -37,6 +37,8 @@ Uses: nothing from other components. Imported by: every component that touches t | `TokenSecrets` | `token-secrets.ts` | `CryptoTokenSecrets` | none; tests inline one | New secret, its hash | | Paths | `paths.ts` | `resolveSimlockHome`, `daemonDataDirectory`, `DATA_DIRECTORY_MODE` (`0700`), `resolveDaemonHome`, `resolveDaemonSocketPath` | — | `SIMLOCK_HOME` (test root; default `~/.simlock`), a gateway in `/gateway`, socket path length; `resolveDaemonHome` picks the folder from the flag (`gateway`, `local`) or, with none, the gateway only when `/gateway/{instance,config}.json` exists and `/instance.json` does not | +On Windows `resolveDaemonSocketPath` answers a named pipe, `\\.\pipe\simlock-`, because Node cannot listen on a file path there; `isPipeEndpoint` recognises it, and a pipe is never `stat`ed, removed or given a directory (`stat` on a live one fails `EBUSY`). +No directory guards a pipe: the default pipe ACL lets other accounts only read (a client requires read and write access), and libuv's first-instance flag makes a second listener fail `address-in-use`. The name is predictable, so another local account that creates it before the daemon starts receives the CLI's `hello` (any `--token` or `SIMLOCK_ADMIN_TOKEN` with it) and answers in the daemon's place: a known gap, accepted for single-user machines only in the 2026-10-30 amendment to ADR 0003 section 4. `productionHostLoadProbe` picks the Darwin or Linux probe. `NodeFileLogSink` rotates to `.1` and keeps that one generation; the files it opens, and the log `NodeDaemonLauncher` pre-creates, are opened mode `0600`; so is a database file `NodeSqliteOpener` opens for writing (SQLite gives `-wal` and `-shm` its mode). `sqlite.ts` is the only file that names `node:sqlite`, diff --git a/src/ports/daemon-launcher.ts b/src/ports/daemon-launcher.ts index 7bf4c053d..0b9372d00 100644 --- a/src/ports/daemon-launcher.ts +++ b/src/ports/daemon-launcher.ts @@ -121,6 +121,8 @@ export class NodeDaemonLauncher implements DaemonLauncher { // auto-launched it, and must be told the home this one already resolved. env: { ...process.env, SIMLOCK_HOME: this.options.simlockHome }, stdio: ["ignore", log.fd, log.fd], + // why: on Windows a detached child gets a console window of its own, and closing it ends the daemon. + windowsHide: true, }); const exited = new Promise((resolve) => { child.once("exit", (code, signal) => resolve({ code, signal })); diff --git a/src/ports/index.ts b/src/ports/index.ts index ae9e3fd0c..7b35a19cb 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -12,6 +12,7 @@ export { type DaemonRole, type DaemonFlag, type DaemonHome, + isPipeEndpoint, resolveDaemonHome, resolveDaemonSocketPath, resolveSimlockHome, @@ -32,6 +33,7 @@ export { type IpcConnector, IpcError, type IpcListenerFactory, + isEndpointAbsent, MemoryIpcTransport, NodeIpcTransport, } from "./ipc.js"; diff --git a/src/ports/ipc.test.ts b/src/ports/ipc.test.ts index 85079399d..8bcb7d1ab 100644 --- a/src/ports/ipc.test.ts +++ b/src/ports/ipc.test.ts @@ -1,8 +1,10 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; +import { createServer, Socket } from "node:net"; import { join } from "node:path"; +import { IpcError, resolveDaemonSocketPath } from "./index.js"; import { MemoryIpcTransport, NodeIpcTransport } from "./ipc.js"; const implementations = [ @@ -92,3 +94,42 @@ describe.each(implementations)("IpcTransport contract: $name", ({ create }) => { await expect(ipc.connect(endpoint)).rejects.toMatchObject({ code: "endpoint-not-found" }); }); }); + +describe("NodeIpcTransport", () => { + it("gives up on a connect that never completes with connection-timeout, and destroys its socket", async () => { + const socket = new Socket(); + const transport = new NodeIpcTransport({ connectTimeoutMs: 20, socketFor: () => socket }); + + const failure = await transport.connect("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/never/answers").catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(IpcError); + expect(failure).toMatchObject({ code: "connection-timeout" }); + expect(socket.destroyed).toBe(true); + }); + + // why: a Windows pipe closes on `end()` whatever the peer does; only a socket can be held half-open. + it.skipIf(process.platform === "win32")( + "close() destroys a connection whose peer never ends its side, once the grace has passed", + async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-ipc-")); + const endpoint = resolveDaemonSocketPath(directory); + const held: Socket[] = []; + const server = createServer({ allowHalfOpen: true }, (socket) => { + held.push(socket); + socket.resume(); + }); + await new Promise((resolve) => server.listen(endpoint, resolve)); + try { + const connection = await new NodeIpcTransport({ closeGraceMs: 50 }).connect(endpoint); + + await connection.close(); + + expect(connection.closed).toBe(true); + } finally { + for (const socket of held) socket.destroy(); + await new Promise((resolve) => server.close(() => resolve())); + await rm(directory, { force: true, recursive: true }); + } + }, + ); +}); diff --git a/src/ports/ipc.ts b/src/ports/ipc.ts index 79de034ca..8a6489fe1 100644 --- a/src/ports/ipc.ts +++ b/src/ports/ipc.ts @@ -4,6 +4,7 @@ export type IpcErrorCode = | "address-in-use" | "connection-refused" | "endpoint-not-found" + | "connection-timeout" | "unknown"; export class IpcError extends Error { @@ -17,6 +18,14 @@ export class IpcError extends Error { } } +/** why: only a refused or missing endpoint proves nothing listens there; any other failure cannot prove it. */ +export function isEndpointAbsent(error: unknown): boolean { + return ( + error instanceof IpcError && + (error.code === "connection-refused" || error.code === "endpoint-not-found") + ); +} + export interface IpcConnection { readonly closed: boolean; onData(listener: (chunk: string) => void): () => void; @@ -38,10 +47,33 @@ export interface IpcListenerFactory { listen(endpoint: string, accept: (connection: IpcConnection) => void): Promise; } -/** Node's Unix-domain socket adapter. Kept at the infrastructure boundary. */ +// why: a local socket or pipe answers in milliseconds; past this, a Windows pipe whose every +// instance is busy, or a peer that never ends its side, would hold the caller forever. +const CONNECT_TIMEOUT_MS = 10_000; +const CLOSE_GRACE_MS = 2_000; + +export interface NodeIpcTransportOptions { + readonly connectTimeoutMs?: number; + readonly closeGraceMs?: number; + /** why: a test needs a socket that never connects, which no real endpoint gives reliably. */ + readonly socketFor?: (endpoint: string) => Socket; +} + +/** why: one adapter serves both endpoint kinds, a Unix-domain socket path and a Windows named pipe. */ export class NodeIpcTransport implements IpcConnector, IpcListenerFactory { + readonly #connectTimeoutMs: number; + readonly #closeGraceMs: number; + readonly #socketFor: (endpoint: string) => Socket; + + constructor(options: NodeIpcTransportOptions = {}) { + this.#connectTimeoutMs = options.connectTimeoutMs ?? CONNECT_TIMEOUT_MS; + this.#closeGraceMs = options.closeGraceMs ?? CLOSE_GRACE_MS; + this.#socketFor = options.socketFor ?? ((endpoint) => connect(endpoint)); + } + async connect(endpoint: string): Promise { - const socket = connect(endpoint); + const socket = this.#socketFor(endpoint); + let timer: NodeJS.Timeout | undefined; try { await new Promise((resolve, reject) => { const onConnect = () => { @@ -54,19 +86,34 @@ export class NodeIpcTransport implements IpcConnector, IpcListenerFactory { }; socket.once("connect", onConnect); socket.once("error", onError); + timer = setTimeout(() => { + socket.off("connect", onConnect); + socket.off("error", onError); + reject( + new IpcError( + "connection-timeout", + `Timed out connecting to ${endpoint} after ${this.#connectTimeoutMs} ms`, + undefined, + ), + ); + }, this.#connectTimeoutMs); }); } catch (error: unknown) { socket.destroy(); throw error; + } finally { + clearTimeout(timer); } - return new NodeIpcConnection(socket); + return new NodeIpcConnection(socket, this.#closeGraceMs); } async listen( endpoint: string, accept: (connection: IpcConnection) => void, ): Promise { - const server = createServer((socket) => accept(new NodeIpcConnection(socket))); + const server = createServer((socket) => + accept(new NodeIpcConnection(socket, this.#closeGraceMs)), + ); try { await new Promise((resolve, reject) => { const onError = (error: Error) => reject(normalizeIpcError(error)); @@ -87,7 +134,10 @@ export class NodeIpcTransport implements IpcConnector, IpcListenerFactory { class NodeIpcConnection implements IpcConnection { #closed = false; - constructor(private readonly socket: Socket) { + constructor( + private readonly socket: Socket, + private readonly closeGraceMs: number, + ) { socket.setEncoding("utf8"); socket.once("close", () => { this.#closed = true; @@ -127,7 +177,12 @@ class NodeIpcConnection implements IpcConnection { close(): Promise { if (this.closed) return Promise.resolve(); return new Promise((resolve) => { - this.socket.once("close", resolve); + // why: a peer that never ends its side never lets the socket close; after the grace it is destroyed, so no caller waits on the peer. + const grace = setTimeout(() => this.socket.destroy(), this.closeGraceMs); + this.socket.once("close", () => { + clearTimeout(grace); + resolve(); + }); // why: a connection nobody read from is paused, so it never sees the peer's end and never closes -- which would hang its listener's close. this.socket.resume(); this.socket.end(); diff --git a/src/ports/paths.test.ts b/src/ports/paths.test.ts index 75bb61b27..5f7a9e860 100644 --- a/src/ports/paths.test.ts +++ b/src/ports/paths.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from "vitest"; import { MemoryFilesystem } from "./filesystem.js"; import { + isPipeEndpoint, resolveDaemonHome, resolveDaemonSocketPath, resolveSimlockHome, @@ -60,6 +61,40 @@ describe("resolveDaemonSocketPath", () => { expect(() => resolveDaemonSocketPath(home, "darwin")).toThrow(SocketPathTooLongError); expect(resolveDaemonSocketPath(home, "linux")).toBe(`${home}/daemon.sock`); }); + + describe("on Windows", () => { + const home = String.raw`C:\Users\me\.simlock`; + + it("listens on a named pipe, the only endpoint Node can listen on there", () => { + const endpoint = resolveDaemonSocketPath(home, "win32"); + + expect(endpoint).toMatch(/^\\\\\.\\pipe\\simlock-[0-9a-f]{16}$/); + expect(isPipeEndpoint(endpoint)).toBe(true); + }); + + it("gives one data directory one name, whatever its case, and two directories two", () => { + const endpoint = resolveDaemonSocketPath(home, "win32"); + + expect(resolveDaemonSocketPath(home.toUpperCase(), "win32")).toBe(endpoint); + expect(resolveDaemonSocketPath(String.raw`C:\Users\me\.other`, "win32")).not.toBe(endpoint); + }); + + it("has no length limit, since the name does not grow with the directory", () => { + const endpoint = resolveDaemonSocketPath(`C:\\${"x".repeat(300)}`, "win32"); + + expect(isPipeEndpoint(endpoint)).toBe(true); + }); + }); +}); + +describe("isPipeEndpoint", () => { + it.each([ + [String.raw`\\.\pipe\simlock-0123456789abcdef`, true], + ["/tmp/simlock-home/daemon.sock", false], + [String.raw`C:\Users\me\.simlock\daemon.sock`, false], + ] as const)("recognises %s as a pipe: %s", (endpoint, expected) => { + expect(isPipeEndpoint(endpoint)).toBe(expected); + }); }); describe("resolveSimlockHome", () => { diff --git a/src/ports/paths.ts b/src/ports/paths.ts index d1e984adf..1bbf63e0e 100644 --- a/src/ports/paths.ts +++ b/src/ports/paths.ts @@ -1,10 +1,11 @@ +import { createHash } from "node:crypto"; import { homedir } from "node:os"; -import { join, resolve } from "node:path"; +import { join, posix, resolve } from "node:path"; import type { Filesystem } from "./filesystem.js"; /** - * why: Resolves simlock's data directory (config.json, state.db, daemon.sock, daemon.log, + * why: Resolves simlock's data directory (config.json, state.db, daemon.sock (a named pipe instead on Windows, so no file), daemon.log, * and the device roots under `devices/`). `SIMLOCK_HOME` overrides the default * `~/.simlock` -- used by tests that need an isolated data directory per daemon instance, * and by anyone running multiple independent simlock installs on one machine. @@ -23,14 +24,35 @@ export function resolveSimlockHome(env: NodeJS.ProcessEnv = process.env): string /** * why: The longest AF_UNIX socket path the kernel accepts, in bytes, excluding the trailing - * NUL: `sun_path` is 104 bytes on macOS and the BSDs and 108 on Linux. Windows named - * pipes have no such limit. + * NUL: `sun_path` is 104 bytes on macOS and the BSDs and 108 on Linux. Windows has no such + * limit because it listens on a named pipe, not a socket file. */ -function maxSocketPathLength(platform: NodeJS.Platform = process.platform): number { - if (platform === "win32") return Number.POSITIVE_INFINITY; +function maxSocketPathLength(platform: NodeJS.Platform): number { return (platform === "linux" ? 108 : 104) - 1; } +// why: `String.raw` cannot end in a backslash (it escapes the closing backtick), so the prefix is written out. +const PIPE_PREFIX = "\\\\.\\pipe\\"; + +/** + * why: Node on Windows listens only on a named pipe, and `listen` on a file path there fails + * with `EACCES`. A pipe is not a file: `stat` on a live one fails with `EBUSY`, it cannot be + * removed, and it is gone when its server closes, so callers must not treat it as one. + */ +export function isPipeEndpoint(endpoint: string): boolean { + return endpoint.startsWith(PIPE_PREFIX); +} + +/** + * why: Pipe names share one machine-wide namespace, so the name is derived from the data + * directory: two daemons with different `SIMLOCK_HOME`s never collide. Lower-cased because + * Windows paths are case-insensitive and one directory must keep one name. + */ +function windowsPipeName(dataDirectory: string): string { + const digest = createHash("sha256").update(dataDirectory.toLowerCase()).digest("hex"); + return `${PIPE_PREFIX}simlock-${digest.slice(0, 16)}`; +} + export class SocketPathTooLongError extends Error { constructor( readonly path: string, @@ -45,15 +67,18 @@ export class SocketPathTooLongError extends Error { } /** - * why: Where the daemon listens under a data directory. Checked here, once, for every process - * that derives it: a path past the kernel's limit otherwise fails on connect as a bare - * `EINVAL`, which says nothing about `SIMLOCK_HOME` being the cause. + * why: Where the daemon listens under a data directory: `/daemon.sock`, or a named + * pipe on Windows. Checked here, once, for every process that derives it: a path past the + * kernel's limit otherwise fails on connect as a bare `EINVAL`, which says nothing about + * `SIMLOCK_HOME` being the cause. */ export function resolveDaemonSocketPath( dataDirectory: string, platform: NodeJS.Platform = process.platform, ): string { - const socketPath = join(dataDirectory, "daemon.sock"); + if (platform === "win32") return windowsPipeName(dataDirectory); + // why: past the pipe, the platform is POSIX, so the path is too, whatever host computes it. + const socketPath = posix.join(dataDirectory, "daemon.sock"); const maxLength = maxSocketPathLength(platform); if (Buffer.byteLength(socketPath) > maxLength) { throw new SocketPathTooLongError(socketPath, maxLength); diff --git a/src/ports/updater-launcher.ts b/src/ports/updater-launcher.ts index e76cbcaab..550876f6f 100644 --- a/src/ports/updater-launcher.ts +++ b/src/ports/updater-launcher.ts @@ -46,6 +46,8 @@ export class NodeUpdaterLauncher implements UpdaterLauncher { detached: true, env: { ...process.env, SIMLOCK_HOME: options.simlockHome }, stdio: ["ignore", "pipe", log.fd], + // why: on Windows a detached child gets a console window of its own, and closing it ends the update. + windowsHide: true, }, ); const exited = new Promise((resolve) => { diff --git a/src/updater/probe.ts b/src/updater/probe.ts index 1c44b482d..45657fd62 100644 --- a/src/updater/probe.ts +++ b/src/updater/probe.ts @@ -1,7 +1,7 @@ import { connectSimlockAdmin } from "../admin/index.js"; import { NodeIpcTransport, - IpcError, + isEndpointAbsent, resolveDaemonSocketPath, type Filesystem, type IpcConnector, @@ -20,8 +20,7 @@ export async function socketHeld(ipc: IpcConnector, endpoint: string): Promise\.simlock`). - `principal` is your requester id. Leases you take belong to it, and by default it can hold one lease at a time (see `lease.maxPerRequester`). Give every agent or worker process its own value. Without it, every client that leaves it out shares the daemon's own default id, and with it one lease. One client is one connection. It does not reconnect: if the daemon stops, every call in progress fails with `DAEMON_CONNECTION_LOST`, and you connect again. Your lease is not released by a lost connection. diff --git a/website/src/content/docs/docs/worker/running-the-daemon.mdx b/website/src/content/docs/docs/worker/running-the-daemon.mdx index 31bc175f3..c317f7eff 100644 --- a/website/src/content/docs/docs/worker/running-the-daemon.mdx +++ b/website/src/content/docs/docs/worker/running-the-daemon.mdx @@ -139,7 +139,7 @@ Everything the worker keeps is under `~/.simlock`: | `state.db` | Devices, leases, enrolled physical devices, the warm pool's memory and HTTP tokens. | | `history.db` | The event history and usage figures behind `simlock events` and `simlock stats`. | | `daemon.log`, `daemon.log.1` | The daemon's log, and the one older file kept after it rotates. | -| `daemon.sock` | The local socket the CLI and agents connect to. | +| `daemon.sock` | The local socket the CLI and agents connect to. On Windows there is no such file: the daemon listens on a named pipe instead (see below). | | `admin.token` | The secret the CLI uses to connect as an admin. | | `devices/ios`, `devices/android` | The simulators and emulators Simlock made. These take the most space. See [Cleanup](/simlock/docs/worker/cleanup#where-devices-live). | @@ -147,6 +147,8 @@ A gateway on the same machine keeps its own files in `~/.simlock/gateway`, with Simlock creates `~/.simlock` (and `~/.simlock/gateway`) so only your user can open it, because anyone who can reach `daemon.sock` can lease devices as an agent. It does not change the permissions of a folder that already exists. If other users can open it, the daemon log says `data directory is accessible to other users (mode ); run chmod 700 ` at each start: run that command to close it. +On Windows the daemon listens on a named pipe, `\\.\pipe\simlock-<16 hex characters>`, not on a file in that folder, so the folder's permissions do not guard it. Other accounts cannot connect to the daemon's pipe. But the pipe's name is predictable: another account that creates it before the daemon starts would receive the CLI's connection, with any admin token the CLI sends. Run Simlock on Windows only on a machine that one user account uses. + To run a separate install on the same account, set `SIMLOCK_HOME` to another folder. Every command and the daemon it starts use that folder instead of `~/.simlock`. Keep the path short: the socket path must fit the system limit (104 bytes on macOS, 108 on Linux), and a longer one fails with `Point SIMLOCK_HOME at a shorter directory.`