Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 16 additions & 8 deletions src/cli/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,11 +220,8 @@ async function isStoppingRefusal(error: unknown): Promise<boolean> {
* the name check picks the candidate and `instanceof` against the real class proves it. */
async function isUnavailable(error: unknown): Promise<boolean> {
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<readonly ModuleConfigEntry[]> {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return true;
} catch (error: unknown) {
return !isEndpointAbsent(error);
}
},
...(env.SIMLOCK_ADMIN_TOKEN === undefined
? {}
Expand Down
48 changes: 47 additions & 1 deletion src/cli/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1590,6 +1590,7 @@ describe("CLI: admin credential resolution (ADR 0003 §5)", () => {
daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false },
homeDirectory: "/home/operator",
workingDirectory: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
});
const exitCode = await runCli(
Expand Down Expand Up @@ -1625,6 +1626,7 @@ describe("CLI: admin credential resolution (ADR 0003 §5)", () => {
daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false },
homeDirectory: "/home/operator",
workingDirectory: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
});
const exitCode = await runCli(["daemon", "start"], output.environmentWith());
Expand Down Expand Up @@ -1658,6 +1660,7 @@ describe("CLI: admin credential resolution (ADR 0003 §5)", () => {
daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false },
homeDirectory: "/home/operator",
workingDirectory: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
});
const exitCode = await runCli(
Expand Down Expand Up @@ -1703,6 +1706,7 @@ describe("CLI: auto-launch's startup deadline (#663)", () => {
daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false },
homeDirectory: "/home/operator",
workingDirectory: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
};
return { clock, ports };
Expand Down Expand Up @@ -1822,6 +1826,7 @@ describe("CLI: auto-launch's failed start (#672)", () => {
daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false },
homeDirectory: "/home/operator",
workingDirectory: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
});
let settled = false;
Expand Down Expand Up @@ -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: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
});
let settled = false;
Expand Down Expand Up @@ -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: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
});
let settled = false;
Expand Down Expand Up @@ -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: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
});
let settled = false;
Expand Down Expand Up @@ -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: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
});
let settled = false;
Expand Down Expand Up @@ -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");
Expand All @@ -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", () => {
Expand Down Expand Up @@ -8342,6 +8382,7 @@ function outputCapture(ports?: CliEnvironmentPorts, env: NodeJS.ProcessEnv = {})
requesterId: "test-requester",
homeDirectory: "/home/operator",
workingDirectory: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
filesystem: new MemoryFilesystem(),
connectAdmin: async () => fakeClient(),
Expand Down Expand Up @@ -8640,6 +8681,7 @@ function realCliEnvironmentPorts(
daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false },
homeDirectory: "/home/operator",
workingDirectory: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
};
}
Expand Down Expand Up @@ -9790,6 +9832,7 @@ describe("CLI: daemon install (#830)", () => {
daemonHome: { role: options.role, dataDirectory, gatewayPresent: false },
homeDirectory: "/home/operator",
workingDirectory: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
service: {
manager: serviceManager,
Expand Down Expand Up @@ -10206,6 +10249,7 @@ describe("CLI: a start goes through the service (#830)", () => {
daemonHome: { role: "worker", dataDirectory: root, gatewayPresent: false },
homeDirectory: "/home/operator",
workingDirectory: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
});

Expand Down Expand Up @@ -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: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
});
let settled = false;
Expand Down Expand Up @@ -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: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
service: {
manager,
Expand Down
1 change: 1 addition & 0 deletions src/cli/lazy-loading.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ async function environment(): Promise<CliEnvironment> {
daemonHome: { role: "worker", dataDirectory: home, gatewayPresent: false },
homeDirectory: "/home/operator",
workingDirectory: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
filesystem: new MemoryFilesystem(),
ipc: new MemoryIpcTransport(),
Expand Down
1 change: 1 addition & 0 deletions src/cli/lazy-parent-watch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ describe("the default parent watch", () => {
clock: new FakeClock(0),
homeDirectory: "/home/operator",
workingDirectory: "/work/project",
hostPlatform: "linux",
runTool: async () => ({ outcome: "not-found" }),
daemonHome: {
role: "worker",
Expand Down
6 changes: 3 additions & 3 deletions src/daemon/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<data dir>/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 `<data dir>/daemon.sock`. On Windows the endpoint is a named pipe (`\\.\pipe\simlock-<hash of the data directory>`): 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`
Expand Down Expand Up @@ -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.
Expand All @@ -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 `<root>/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 `<root>/daemon.log` as "Daemon failed to start"; exit 1.

## Rules

Expand Down
44 changes: 44 additions & 0 deletions src/daemon/connection-host.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading
Loading