From 6ae302fdfc8f857ea9f9b3fe3097b915befa8e8a Mon Sep 17 00:00:00 2001 From: Xavier Date: Thu, 29 Oct 2026 21:09:56 -0300 Subject: [PATCH 1/8] fix(ports): the daemon listens on a named pipe on Windows Node on Windows can only listen on a named pipe, so `listen` on `/daemon.sock` failed with EACCES and every command timed out with `connect ENOENT`. On win32 `resolveDaemonSocketPath` now answers `\.\pipe\simlock-`, lower-cased so one directory keeps one name and two `SIMLOCK_HOME`s never share a pipe. A pipe is not a file: `stat` on a live one fails EBUSY, it cannot be removed, and it is gone when its server closes. So `DaemonEndpointHost` skips the directory, stale-file and removal steps for it (a live pipe already fails the bind with `address-in-use`), and `daemon stop` waits for the pipe to stop answering instead of checking for a file. Part of #1051. Co-Authored-By: Claude Opus 5.5 --- src/cli/environment.ts | 14 ++++++++-- src/daemon/AGENTS.md | 2 +- src/daemon/connection-host.test.ts | 44 +++++++++++++++++++++++++++++ src/daemon/connection-host.ts | 45 +++++++++++++++++------------- src/ports/AGENTS.md | 3 +- src/ports/index.ts | 1 + src/ports/paths.test.ts | 35 +++++++++++++++++++++++ src/ports/paths.ts | 38 ++++++++++++++++++++----- 8 files changed, 152 insertions(+), 30 deletions(-) diff --git a/src/cli/environment.ts b/src/cli/environment.ts index aaa7c27d7..1282fd091 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -372,8 +372,18 @@ 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 { IpcError, isPipeEndpoint, resolveDaemonSocketPath } = + await import("../ports/index.js"); + const endpoint = resolveDaemonSocketPath(dataDirectory); + 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) { + if (!(error instanceof IpcError)) return true; + return error.code !== "connection-refused" && error.code !== "endpoint-not-found"; + } }, ...(env.SIMLOCK_ADMIN_TOKEN === undefined ? {} diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 77f7fd250..03b0982fd 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` 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..d28d17f8c 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; @@ -76,26 +76,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 +122,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/ports/AGENTS.md b/src/ports/AGENTS.md index be4678885..a2826fa6a 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,7 @@ 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`). `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/index.ts b/src/ports/index.ts index ae9e3fd0c..113f29a96 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, 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..8beb0885a 100644 --- a/src/ports/paths.ts +++ b/src/ports/paths.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import { homedir } from "node:os"; import { join, resolve } from "node:path"; @@ -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,14 +67,16 @@ 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 { + if (platform === "win32") return windowsPipeName(dataDirectory); const socketPath = join(dataDirectory, "daemon.sock"); const maxLength = maxSocketPathLength(platform); if (Buffer.byteLength(socketPath) > maxLength) { From c4581c345356055b0c145daacb03b4f19f48fd9f Mon Sep 17 00:00:00 2001 From: Xavier Date: Thu, 29 Oct 2026 21:47:32 -0300 Subject: [PATCH 2/8] fix(ports): bound IPC connect and close `daemon stop` probes a Windows pipe by connecting and closing until nothing answers. `NodeIpcTransport.connect` had no timeout, and `close()` waited for the socket's `close`, which never comes when the peer keeps its end open, so the loop could miss its 300 s deadline. Connecting now gives up after 10 s, and `close()` destroys the socket 2 s after ending it. Both are adapter options for tests. The daemon manual records what guards the pipe on Windows, and the squatting gap its predictable name leaves on a shared machine. Addresses CodeRabbit review on #1052. Co-Authored-By: Claude Opus 5.5 --- src/daemon/AGENTS.md | 5 +++++ src/ports/ipc.test.ts | 30 ++++++++++++++++++++++++++ src/ports/ipc.ts | 50 +++++++++++++++++++++++++++++++++++++++---- 3 files changed, 81 insertions(+), 4 deletions(-) diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 03b0982fd..3a3dfde4e 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -111,6 +111,11 @@ Security model: cooperative identity, not a hostile-process boundary. 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. +- On Windows the endpoint is a named pipe, which no directory guards: the default pipe ACL lets + other accounts only read (a client needs read and write), and libuv's first-instance flag makes + a second listener fail `address-in-use`. Its 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. Single-user machines only. - 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. diff --git a/src/ports/ipc.test.ts b/src/ports/ipc.test.ts index 85079399d..37c8fe78d 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, type Socket } from "node:net"; import { join } from "node:path"; +import { resolveDaemonSocketPath } from "./index.js"; import { MemoryIpcTransport, NodeIpcTransport } from "./ipc.js"; const implementations = [ @@ -92,3 +94,31 @@ describe.each(implementations)("IpcTransport contract: $name", ({ create }) => { await expect(ipc.connect(endpoint)).rejects.toMatchObject({ code: "endpoint-not-found" }); }); }); + +describe("NodeIpcTransport", () => { + // 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..af5996b00 100644 --- a/src/ports/ipc.ts +++ b/src/ports/ipc.ts @@ -38,10 +38,29 @@ export interface IpcListenerFactory { listen(endpoint: string, accept: (connection: IpcConnection) => void): Promise; } +// 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; +} + /** Node's Unix-domain socket adapter. Kept at the infrastructure boundary. */ export class NodeIpcTransport implements IpcConnector, IpcListenerFactory { + readonly #connectTimeoutMs: number; + readonly #closeGraceMs: number; + + constructor(options: NodeIpcTransportOptions = {}) { + this.#connectTimeoutMs = options.connectTimeoutMs ?? CONNECT_TIMEOUT_MS; + this.#closeGraceMs = options.closeGraceMs ?? CLOSE_GRACE_MS; + } + async connect(endpoint: string): Promise { const socket = connect(endpoint); + let timer: NodeJS.Timeout | undefined; try { await new Promise((resolve, reject) => { const onConnect = () => { @@ -54,19 +73,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( + "unknown", + `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 +121,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 +164,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(); From 0274a83dc5c0d2aaa930a87feb67854a76a3ac38 Mon Sep 17 00:00:00 2001 From: Xavier Date: Thu, 29 Oct 2026 22:04:52 -0300 Subject: [PATCH 3/8] fix(ports): hide the console window of a detached daemon on Windows Node gives a detached child on Windows a console window of its own (https://nodejs.org/api/child_process.html#optionsdetached), so the daemon `simlock daemon start` or an auto-launch spawns, and the updater, would each open one on the desktop, and closing it ends the process. Both launchers now pass `windowsHide: true`; elsewhere it does nothing. Co-Authored-By: Claude Opus 5.5 --- src/ports/daemon-launcher.ts | 2 ++ src/ports/updater-launcher.ts | 2 ++ 2 files changed, 4 insertions(+) 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/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) => { From 7f00b843f4a1fdeb2a73b6c9408e231373d994a8 Mon Sep 17 00:00:00 2001 From: Xavier Date: Thu, 29 Oct 2026 22:15:47 -0300 Subject: [PATCH 4/8] docs(agents): keep the daemon manual within its 150 lines The Windows pipe's security note moves to the ports manual, beside the pipe it describes; the daemon manual points there from the line it had. Co-Authored-By: Claude Opus 5.5 --- src/daemon/AGENTS.md | 7 +------ src/ports/AGENTS.md | 1 + 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 3a3dfde4e..f00503dab 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -110,12 +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. -- On Windows the endpoint is a named pipe, which no directory guards: the default pipe ACL lets - other accounts only read (a client needs read and write), and libuv's first-instance flag makes - a second listener fail `address-in-use`. Its 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. Single-user machines only. + 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. diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index a2826fa6a..b52c34a2f 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -38,6 +38,7 @@ Uses: nothing from other components. Imported by: every component that touches t | 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 needs read and write), 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, for single-user machines only. `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`, From e87152640144cf35a283af2c717cdb3c57e31d77 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 30 Oct 2026 12:53:31 +0100 Subject: [PATCH 5/8] refactor(ports): share one endpoint-absent check; amend ADR 0003 for the Windows pipe gap --- ...ne-typed-daemon-contract-behind-every-frontend.md | 6 ++++++ src/cli/environment.ts | 12 ++++-------- src/ports/AGENTS.md | 2 +- src/ports/index.ts | 1 + src/ports/ipc.ts | 10 +++++++++- src/ports/paths.ts | 2 +- src/updater/probe.ts | 5 ++--- 7 files changed, 24 insertions(+), 14 deletions(-) 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 1282fd091..f2ba77d0b 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 { @@ -372,7 +369,7 @@ export function buildCliEnvironment( connectAdmin: (resolveCredential, options) => autoLaunch.connect(resolveCredential, options), connectExistingAdmin: (resolveCredential) => connect(ipc, resolveCredential), daemonEndpointPresent: async () => { - const { IpcError, isPipeEndpoint, resolveDaemonSocketPath } = + const { isEndpointAbsent, isPipeEndpoint, resolveDaemonSocketPath } = await import("../ports/index.js"); const endpoint = resolveDaemonSocketPath(dataDirectory); if (!isPipeEndpoint(endpoint)) return filesystem.exists(endpoint); @@ -381,8 +378,7 @@ export function buildCliEnvironment( await (await ipc.connect(endpoint)).close(); return true; } catch (error: unknown) { - if (!(error instanceof IpcError)) return true; - return error.code !== "connection-refused" && error.code !== "endpoint-not-found"; + return !isEndpointAbsent(error); } }, ...(env.SIMLOCK_ADMIN_TOKEN === undefined diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index b52c34a2f..1c94e6537 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -38,7 +38,7 @@ Uses: nothing from other components. Imported by: every component that touches t | 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 needs read and write), 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, for single-user machines only. +No directory guards a pipe: the default pipe ACL lets other accounts only read (a client needs read and write), 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/index.ts b/src/ports/index.ts index 113f29a96..7b35a19cb 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -33,6 +33,7 @@ export { type IpcConnector, IpcError, type IpcListenerFactory, + isEndpointAbsent, MemoryIpcTransport, NodeIpcTransport, } from "./ipc.js"; diff --git a/src/ports/ipc.ts b/src/ports/ipc.ts index af5996b00..3bc277a56 100644 --- a/src/ports/ipc.ts +++ b/src/ports/ipc.ts @@ -17,6 +17,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; @@ -48,7 +56,7 @@ export interface NodeIpcTransportOptions { readonly closeGraceMs?: number; } -/** Node's Unix-domain socket adapter. Kept at the infrastructure boundary. */ +/** 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; diff --git a/src/ports/paths.ts b/src/ports/paths.ts index 8beb0885a..f5218d74b 100644 --- a/src/ports/paths.ts +++ b/src/ports/paths.ts @@ -5,7 +5,7 @@ import { join, 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. 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 Date: Fri, 30 Oct 2026 09:36:07 -0300 Subject: [PATCH 6/8] fix(daemon): a pipe connect that times out means a daemon already runs A Windows pipe whose every instance is busy makes the start probe's connect time out. The timeout was an `unknown` IpcError, so a second daemon failed to start (exit 1) instead of exiting 0 as already running. The timeout now has its own code, `connection-timeout`, and `refuseWhenDaemonAnswers` takes it as a daemon holding the endpoint. Also fixes the grammar of the pipe ACL sentence in the ports manual. Addresses CodeRabbit review on #1052. Co-Authored-By: Claude Opus 5.5 --- src/daemon/AGENTS.md | 2 +- src/daemon/connection-host.test.ts | 37 +++++++++++++++++++++++++++++- src/daemon/connection-host.ts | 4 +++- src/ports/AGENTS.md | 2 +- src/ports/ipc.ts | 3 ++- 5 files changed, 43 insertions(+), 5 deletions(-) diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index f00503dab..f0e719577 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -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 ee17d9ba1..3e52278f5 100644 --- a/src/daemon/connection-host.test.ts +++ b/src/daemon/connection-host.test.ts @@ -16,7 +16,11 @@ import { type IpcConnector, type IpcListenerFactory, } from "../ports/index.js"; -import { DaemonAlreadyRunningError, DaemonEndpointHost } from "./connection-host.js"; +import { + DaemonAlreadyRunningError, + DaemonEndpointHost, + refuseWhenDaemonAnswers, +} from "./connection-host.js"; const endpoint = "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/simlock/daemon.sock"; @@ -187,6 +191,37 @@ describe("DaemonEndpointHost", () => { }); }); +describe("refuseWhenDaemonAnswers", () => { + const failingWith = (code: "connection-timeout" | "endpoint-not-found" | "unknown") => ({ + connect: async (): Promise => { + throw new IpcError(code, code, undefined); + }, + }); + + it("refuses when the endpoint accepts a connection", async () => { + const ipc = new MemoryIpcTransport(); + await ipc.listen(endpoint, () => undefined); + await expect(refuseWhenDaemonAnswers({ connector: ipc, endpoint })).rejects.toBeInstanceOf( + DaemonAlreadyRunningError, + ); + }); + + it("refuses when connecting times out, since a held endpoint has a live server", async () => { + await expect( + refuseWhenDaemonAnswers({ connector: failingWith("connection-timeout"), endpoint }), + ).rejects.toBeInstanceOf(DaemonAlreadyRunningError); + }); + + it("passes a missing endpoint and propagates an unknown failure", async () => { + await expect( + refuseWhenDaemonAnswers({ connector: failingWith("endpoint-not-found"), endpoint }), + ).resolves.toBeUndefined(); + await expect( + refuseWhenDaemonAnswers({ connector: failingWith("unknown"), endpoint }), + ).rejects.toThrow("unknown"); + }); +}); + function hostFor( filesystem: MemoryFilesystem, connector: IpcConnector, diff --git a/src/daemon/connection-host.ts b/src/daemon/connection-host.ts index d28d17f8c..3b099d487 100644 --- a/src/daemon/connection-host.ts +++ b/src/daemon/connection-host.ts @@ -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); } diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index 1c94e6537..84fc03655 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -38,7 +38,7 @@ Uses: nothing from other components. Imported by: every component that touches t | 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 needs read and write), 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. +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/ipc.ts b/src/ports/ipc.ts index 3bc277a56..a6301c1c3 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 { @@ -86,7 +87,7 @@ export class NodeIpcTransport implements IpcConnector, IpcListenerFactory { socket.off("error", onError); reject( new IpcError( - "unknown", + "connection-timeout", `Timed out connecting to ${endpoint} after ${this.#connectTimeoutMs} ms`, undefined, ), From eb7032b46c86099e4747550ecddeeae65580ae41 Mon Sep 17 00:00:00 2001 From: Xavier Date: Fri, 30 Oct 2026 09:36:07 -0300 Subject: [PATCH 7/8] fix(cli): the endpoint check takes the host platform as a port `daemonEndpointPresent` resolved the endpoint with the host's `process.platform`, so its test asserted a socket file on Windows and no test reached the named-pipe branch. The CLI environment now takes `platform` as a port (set in the composition root), and the socket-file path is joined with POSIX rules, since it is only used off Windows. New tests cover the pipe branch: present while something answers, absent once it closes, and present when the connect times out. Addresses blind review R1 on #1052. Co-Authored-By: Claude Opus 5.5 --- src/cli/environment.ts | 6 ++-- src/cli/index.test.ts | 48 ++++++++++++++++++++++++++++++- src/cli/index.ts | 1 + src/cli/lazy-loading.test.ts | 1 + src/cli/lazy-parent-watch.test.ts | 1 + src/cli/types.ts | 2 ++ src/mcp/main.test.ts | 1 + src/ports/paths.ts | 5 ++-- 8 files changed, 60 insertions(+), 5 deletions(-) diff --git a/src/cli/environment.ts b/src/cli/environment.ts index f2ba77d0b..b3afd4f57 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -317,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.platform), + ); const credential = await resolveCredential(); return connectSimlockAdmin({ connection, @@ -371,7 +373,7 @@ export function buildCliEnvironment( daemonEndpointPresent: async () => { const { isEndpointAbsent, isPipeEndpoint, resolveDaemonSocketPath } = await import("../ports/index.js"); - const endpoint = resolveDaemonSocketPath(dataDirectory); + const endpoint = resolveDaemonSocketPath(dataDirectory, ports.platform); 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 { diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index cee171482..835a497fc 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1391,6 +1391,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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), }); const exitCode = await runCli( @@ -1426,6 +1427,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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), }); const exitCode = await runCli(["daemon", "start"], output.environmentWith()); @@ -1459,6 +1461,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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), }); const exitCode = await runCli( @@ -1504,6 +1507,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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), }; return { clock, ports }; @@ -1623,6 +1627,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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), }); let settled = false; @@ -1672,6 +1677,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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), }); let settled = false; @@ -1714,6 +1720,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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), }); let settled = false; @@ -1777,6 +1784,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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), }); let settled = false; @@ -1822,6 +1830,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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), }); let settled = false; @@ -7497,7 +7506,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"); @@ -7506,6 +7515,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, platform: "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, platform: "win32" }, + {}, + ); + + expect(await environment.daemonEndpointPresent()).toBe(true); + }); }); describe("CLI: requester id from the agent session", () => { @@ -8236,6 +8276,7 @@ function outputCapture(ports?: CliEnvironmentPorts, env: NodeJS.ProcessEnv = {}) requesterId: "test-requester", homeDirectory: "/home/operator", workingDirectory: "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/work/project", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), filesystem: new MemoryFilesystem(), connectAdmin: async () => fakeClient(), @@ -8534,6 +8575,7 @@ function realCliEnvironmentPorts( daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), }; } @@ -9684,6 +9726,7 @@ describe("CLI: daemon install (#830)", () => { daemonHome: { role: options.role, dataDirectory, gatewayPresent: false }, homeDirectory: "/home/operator", workingDirectory: "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/work/project", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), service: { manager: serviceManager, @@ -10100,6 +10143,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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), }); @@ -10160,6 +10204,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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), }); let settled = false; @@ -10252,6 +10297,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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), service: { manager, diff --git a/src/cli/index.ts b/src/cli/index.ts index 09283b876..d963d24c5 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -147,6 +147,7 @@ async function buildDefaultEnvironment(flag: DaemonFlag): Promise { const { toolRunner } = await import("../instructions/index.js"); return toolRunner(new NodeProcessRunner())(bin, args, options); diff --git a/src/cli/lazy-loading.test.ts b/src/cli/lazy-loading.test.ts index 74e464286..755a58c59 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", + platform: "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..f8991172a 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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), daemonHome: { role: "worker", diff --git a/src/cli/types.ts b/src/cli/types.ts index 119f3ee2f..e1a97d053 100644 --- a/src/cli/types.ts +++ b/src/cli/types.ts @@ -102,6 +102,8 @@ export interface CliEnvironmentPorts { readonly homeDirectory: string; readonly workingDirectory: string; readonly codexHome?: string | undefined; + /** why: on `win32` the daemon's endpoint is a named pipe, not a socket file. */ + readonly platform: NodeJS.Platform; readonly runTool: RunTool; readonly service?: ServiceSetup; readonly parentWatch?: ParentWatch; diff --git a/src/mcp/main.test.ts b/src/mcp/main.test.ts index 162dc78c7..e0662cbd8 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", + platform: "linux", runTool: async () => ({ outcome: "not-found" }), filesystem: new MemoryFilesystem(), ipc: new MemoryIpcTransport(), diff --git a/src/ports/paths.ts b/src/ports/paths.ts index f5218d74b..1bbf63e0e 100644 --- a/src/ports/paths.ts +++ b/src/ports/paths.ts @@ -1,6 +1,6 @@ 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"; @@ -77,7 +77,8 @@ export function resolveDaemonSocketPath( platform: NodeJS.Platform = process.platform, ): string { if (platform === "win32") return windowsPipeName(dataDirectory); - const socketPath = join(dataDirectory, "daemon.sock"); + // 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); From 5ad46114adaeeb8c7afde7016468a1740001df6e Mon Sep 17 00:00:00 2001 From: Xavier Date: Fri, 30 Oct 2026 10:04:15 -0300 Subject: [PATCH 8/8] fix(ports): test the connect timeout where it matters; document the Windows pipe - `NodeIpcTransport` takes an optional `socketFor`, so a test can hand it a socket that never connects; the test proves the connect gives up with `connection-timeout` and destroys the socket. - The timeout refusal is tested at `startDaemon`, its real seam, in place of direct tests of `refuseWhenDaemonAnswers`. - The website says that on Windows the endpoint is a named pipe, how a programmatic client names it, and that Simlock on Windows is for single-user machines only. Addresses blind review R2, R3 and R4 on #1052. Co-Authored-By: Claude Opus 5.5 --- src/daemon/connection-host.test.ts | 37 +------------------ src/daemon/main.test.ts | 14 +++++++ src/ports/ipc.test.ts | 15 +++++++- src/ports/ipc.ts | 6 ++- .../using-devices/programmatic-client.mdx | 2 +- .../docs/docs/worker/running-the-daemon.mdx | 4 +- 6 files changed, 37 insertions(+), 41 deletions(-) diff --git a/src/daemon/connection-host.test.ts b/src/daemon/connection-host.test.ts index 3e52278f5..ee17d9ba1 100644 --- a/src/daemon/connection-host.test.ts +++ b/src/daemon/connection-host.test.ts @@ -16,11 +16,7 @@ import { type IpcConnector, type IpcListenerFactory, } from "../ports/index.js"; -import { - DaemonAlreadyRunningError, - DaemonEndpointHost, - refuseWhenDaemonAnswers, -} from "./connection-host.js"; +import { DaemonAlreadyRunningError, DaemonEndpointHost } from "./connection-host.js"; const endpoint = "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/simlock/daemon.sock"; @@ -191,37 +187,6 @@ describe("DaemonEndpointHost", () => { }); }); -describe("refuseWhenDaemonAnswers", () => { - const failingWith = (code: "connection-timeout" | "endpoint-not-found" | "unknown") => ({ - connect: async (): Promise => { - throw new IpcError(code, code, undefined); - }, - }); - - it("refuses when the endpoint accepts a connection", async () => { - const ipc = new MemoryIpcTransport(); - await ipc.listen(endpoint, () => undefined); - await expect(refuseWhenDaemonAnswers({ connector: ipc, endpoint })).rejects.toBeInstanceOf( - DaemonAlreadyRunningError, - ); - }); - - it("refuses when connecting times out, since a held endpoint has a live server", async () => { - await expect( - refuseWhenDaemonAnswers({ connector: failingWith("connection-timeout"), endpoint }), - ).rejects.toBeInstanceOf(DaemonAlreadyRunningError); - }); - - it("passes a missing endpoint and propagates an unknown failure", async () => { - await expect( - refuseWhenDaemonAnswers({ connector: failingWith("endpoint-not-found"), endpoint }), - ).resolves.toBeUndefined(); - await expect( - refuseWhenDaemonAnswers({ connector: failingWith("unknown"), endpoint }), - ).rejects.toThrow("unknown"); - }); -}); - function hostFor( filesystem: MemoryFilesystem, connector: IpcConnector, diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 5320edac9..c7496a25f 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, @@ -4554,6 +4556,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/ports/ipc.test.ts b/src/ports/ipc.test.ts index 37c8fe78d..8bcb7d1ab 100644 --- a/src/ports/ipc.test.ts +++ b/src/ports/ipc.test.ts @@ -1,10 +1,10 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { createServer, type Socket } from "node:net"; +import { createServer, Socket } from "node:net"; import { join } from "node:path"; -import { resolveDaemonSocketPath } from "./index.js"; +import { IpcError, resolveDaemonSocketPath } from "./index.js"; import { MemoryIpcTransport, NodeIpcTransport } from "./ipc.js"; const implementations = [ @@ -96,6 +96,17 @@ describe.each(implementations)("IpcTransport contract: $name", ({ create }) => { }); 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", diff --git a/src/ports/ipc.ts b/src/ports/ipc.ts index a6301c1c3..8a6489fe1 100644 --- a/src/ports/ipc.ts +++ b/src/ports/ipc.ts @@ -55,20 +55,24 @@ 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) => { diff --git a/website/src/content/docs/docs/using-devices/programmatic-client.mdx b/website/src/content/docs/docs/using-devices/programmatic-client.mdx index 091e1d9fb..5717c1865 100644 --- a/website/src/content/docs/docs/using-devices/programmatic-client.mdx +++ b/website/src/content/docs/docs/using-devices/programmatic-client.mdx @@ -37,7 +37,7 @@ const client = await connectSimlock({ }); ``` -- `endpoint` is the daemon's socket: `~/.simlock/daemon.sock`. If you set `SIMLOCK_HOME`, it is `$SIMLOCK_HOME/daemon.sock`. A gateway's socket is `~/.simlock/gateway/daemon.sock`. +- `endpoint` is the daemon's socket: `~/.simlock/daemon.sock`. If you set `SIMLOCK_HOME`, it is `$SIMLOCK_HOME/daemon.sock`. A gateway's socket is `~/.simlock/gateway/daemon.sock`. On Windows the endpoint is a named pipe instead: `\\.\pipe\simlock-` followed by the first 16 hex characters of the SHA-256 of the data folder's full path in lower case (for `~/.simlock`, of `c:\users\\.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 52cde0906..9ee8338d3 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.`