From 92a08f03253c33ced5b1d6b8d113c8e151fb4ba6 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 18 Oct 2026 17:26:13 +0200 Subject: [PATCH 1/4] =?UTF-8?q?test:=20reproduce=20#685=20=E2=80=94=20daem?= =?UTF-8?q?on.log,=20events.jsonl=20and=20instance.json=20are=20created=20?= =?UTF-8?q?world-readable=20(0644)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/instance-identity.test.ts | 19 +++++++++++ src/ports/daemon-launcher.test.ts | 27 +++++++++++++++- src/ports/logger.test.ts | 51 +++++++++++++++++++++++++++++- 3 files changed, 95 insertions(+), 2 deletions(-) diff --git a/src/core/instance-identity.test.ts b/src/core/instance-identity.test.ts index 11a959cf8..dc84329a3 100644 --- a/src/core/instance-identity.test.ts +++ b/src/core/instance-identity.test.ts @@ -123,6 +123,25 @@ describe("loadInstanceId on a real filesystem", () => { // Written once: the two that lost the race read the winner's file instead of writing. await expect(filesystem.readdir(home)).resolves.toEqual(["instance.json"]); }); + + it("creates instance.json owner-only", async () => { + // why: #685: `writeFileExclusive` links a temp file into place, and that temp file is written + // without a mode, so the identity the daemon stamps into every device root lands world- + // readable under the umask every real host starts from. A restrictive umask here would + // mask what the code asks for, so pin 022. + const previousUmask = process.umask(0o022); + try { + const filesystem = new NodeFilesystem(); + home = await mkdtemp(join(tmpdir(), "simlock-instance-identity-")); + const instancePath = join(home, "instance.json"); + + await loadInstanceId({ filesystem, idGenerator: sequence(), path: instancePath }); + + expect((await filesystem.stat(instancePath)).mode).toBe(0o600); + } finally { + process.umask(previousUmask); + } + }); }); /** Stands in for another daemon whose exclusive create landed first. */ diff --git a/src/ports/daemon-launcher.test.ts b/src/ports/daemon-launcher.test.ts index 9e69daac4..668260437 100644 --- a/src/ports/daemon-launcher.test.ts +++ b/src/ports/daemon-launcher.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { mkdtemp, readFile, readdir, rm } from "node:fs/promises"; +import { mkdtemp, readFile, readdir, rm, stat } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -45,6 +45,31 @@ describe("NodeDaemonLauncher", () => { } }); + it("creates the daemon log it hands the child owner-only", async () => { + // why: #685: when the CLI or MCP server auto-launches the daemon, this `open(path, "a")` is + // what first creates `daemon.log` -- the daemon's own sink only appends afterwards. A + // restrictive umask in the test environment would mask what the code asks for, so pin + // the one every real host starts from. + const previousUmask = process.umask(0o022); + const directory = await mkdtemp(join(tmpdir(), "simlock-launcher-")); + const logPath = join(directory, "daemon.log"); + const launcher = new NodeDaemonLauncher({ + args: ["-e", "console.log('out')"], + command: process.execPath, + logPath, + simlockHome: directory, + }); + try { + await launcher.launch(); + await expect.poll(async () => (await readFile(logPath, "utf8")).trim()).toBe("out"); + + expect((await stat(logPath)).mode & 0o777).toBe(0o600); + } finally { + process.umask(previousUmask); + await rm(directory, { force: true, recursive: true }); + } + }); + it("combines stdout and stderr in an append-only log", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-launcher-")); const logPath = join(directory, "daemon.log"); diff --git a/src/ports/logger.test.ts b/src/ports/logger.test.ts index f9589b9f3..5862b58fd 100644 --- a/src/ports/logger.test.ts +++ b/src/ports/logger.test.ts @@ -1,5 +1,5 @@ import { readdirSync } from "node:fs"; -import { mkdtemp, readFile, readdir, rename, rm, utimes, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, readdir, rename, rm, stat, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; @@ -132,6 +132,55 @@ async function tempDir(): Promise { } describe("NodeFileLogSink", () => { + it("creates every file it holds owner-only, the current file and every rotated generation alike", async () => { + // why: #685: `daemon.log` and `events.jsonl` are both sinks of this class, and a rotated + // generation is a file this class creates too (`openSync(path, "a")` after each + // rename). A restrictive umask in the test environment would mask what the code + // actually asks for, so pin the one every real host starts from. + const previousUmask = process.umask(0o022); + try { + const directory = await tempDir(); + // why: one sink at the daemon's `daemon.log` shape (single generation), one at the + // `events.jsonl` shape (numbered generations under retention) — the two shapes the + // daemon actually opens. + const paths = { + daemonLog: join(directory, "daemon.log"), + events: join(directory, "events.jsonl"), + }; + // why: the second write passes the 12-byte cap — that rotation is part of what this asserts. + const logSink = new NodeFileLogSink({ maxBytes: 12, path: paths.daemonLog }); + logSink.write("first"); + logSink.write("second"); + logSink.close(); + const eventSink = new NodeFileLogSink({ + clock: new FakeClock(1_000), + maxBytes: 12, + path: paths.events, + retentionMs: 1, + totalMaxBytes: 1_000, + }); + // why: the second write rotates this sink too, and the rotated generation is a file + // this class creates — its mode is part of the claim. + eventSink.write('{"timestamp":1000}'); + eventSink.write('{"timestamp":1000}'); + eventSink.close(); + + expect({ + daemonLog: (await stat(paths.daemonLog)).mode & 0o777, + daemonLogRotated: (await stat(`${paths.daemonLog}.1`)).mode & 0o777, + events: (await stat(paths.events)).mode & 0o777, + eventsRotated: (await stat(`${paths.events}.1`)).mode & 0o777, + }).toEqual({ + daemonLog: 0o600, + daemonLogRotated: 0o600, + events: 0o600, + eventsRotated: 0o600, + }); + } finally { + process.umask(previousUmask); + } + }); + it("appends one line per write to the target file", async () => { const directory = await tempDir(); const path = join(directory, "daemon.log"); From 0baa5a792132bad98084b0bf100c07601b1930af Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 18 Oct 2026 17:46:12 +0200 Subject: [PATCH 2/4] fix(ports,core): write daemon.log, events.jsonl and instance.json owner-only (#685) 3 failing -> 0 failing --- src/core/AGENTS.md | 3 ++- src/core/instance-identity.ts | 9 ++++++- src/ports/AGENTS.md | 3 ++- src/ports/daemon-launcher.ts | 5 +++- src/ports/filesystem.test.ts | 22 +++++++++++++++++ src/ports/filesystem.ts | 45 +++++++++++++++++++++++++++++------ src/ports/logger.ts | 10 ++++++-- 7 files changed, 84 insertions(+), 13 deletions(-) diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index 5420725df..b76ff2db6 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -103,7 +103,8 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic quarantine stalls (age > estimate × `stalledTransition.thresholdMultiplier`, unclaimed). 9. **Physical** — `PhysicalEnrollment.add` refuses Simlock's own devices, reads `inspectPhysical`, writes `ready` with `enrolledApps`, or re-enrols under `enrollment`; `remove` unenrols. Busy: `DeviceBusyError`. -10. **Ownership** — `loadInstanceId` creates `instance.json` once (exclusive create). `ensureOwnedRoot` +10. **Ownership** — `loadInstanceId` creates `instance.json` once (exclusive create, mode + `0600`). `ensureOwnedRoot` stages a root with `.simlock-owned.json` (instance id, platform), mode `0700`; doubt is `OwnedRootError`. 11. **Components** — `ComponentInstaller`, the only caller of `installComponent`/`removeComponent`. One FIFO per platform; a call for the same component joins. At the front: `stillNeeded` → diff --git a/src/core/instance-identity.ts b/src/core/instance-identity.ts index 39a47f3e6..88b9aadae 100644 --- a/src/core/instance-identity.ts +++ b/src/core/instance-identity.ts @@ -2,6 +2,11 @@ import { dirname } from "node:path"; import type { Filesystem, IdGenerator } from "../ports/index.js"; +/** why: Owner-only, like every other file the daemon keeps under `SIMLOCK_HOME` (`config.json`, + * `state.json`, `tokens.json`, `admin.token`): the trust boundary is the OS user, and the id this + * file holds is what every device root's ownership marker is checked against. */ +const INSTANCE_FILE_MODE = 0o600; + export interface InstanceIdentityOptions { readonly filesystem: Filesystem; readonly idGenerator: IdGenerator; @@ -45,7 +50,9 @@ export async function loadInstanceId(options: InstanceIdentityOptions): Promise< // land on top of an identity the winner had already stamped into its roots, and every // one of them would read `wrong-instance` from then on. Here the kernel picks the // winner and the loser is told so. - await options.filesystem.writeFileExclusive(options.path, serializeIdentity(generated)); + await options.filesystem.writeFileExclusive(options.path, serializeIdentity(generated), { + mode: INSTANCE_FILE_MODE, + }); } catch (error: unknown) { if (!isExistingPathError(error)) { throw new InstanceIdentityError( diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index 015f1a483..c3da70e34 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -30,7 +30,8 @@ Uses: nothing from other components. Imported by: every component that touches t | Paths | `paths.ts` | `resolveSimlockHome`, `resolveDaemonSocketPath` | — | `SIMLOCK_HOME` (default `~/.simlock`), socket path length | `productionHostLoadProbe` picks the Darwin or Linux probe. `NodeFileLogSink` rotates to -`.1`, or keeps numbered generations when given `retentionMs` or `totalMaxBytes`. +`.1`, or keeps numbered generations when given `retentionMs` or `totalMaxBytes`. The +files it opens, and the log `NodeDaemonLauncher` pre-creates, are opened mode `0600`. ## Rules diff --git a/src/ports/daemon-launcher.ts b/src/ports/daemon-launcher.ts index c2ad236e1..af7d12bab 100644 --- a/src/ports/daemon-launcher.ts +++ b/src/ports/daemon-launcher.ts @@ -37,7 +37,10 @@ export class NodeDaemonLauncher implements DaemonLauncher { async launch(): Promise { await mkdir(dirname(this.options.logPath), { recursive: true }); - const log = await open(this.options.logPath, "a"); + // why: 0600 at creation, like every other file under `SIMLOCK_HOME` (`#258`'s rule): this + // `open` is what first creates `daemon.log` for an auto-launched daemon -- the daemon's own + // sink only appends to the file this one made. + const log = await open(this.options.logPath, "a", 0o600); try { const child = spawn(this.options.command, this.options.args, { detached: true, diff --git a/src/ports/filesystem.test.ts b/src/ports/filesystem.test.ts index 437cf9333..52786055f 100644 --- a/src/ports/filesystem.test.ts +++ b/src/ports/filesystem.test.ts @@ -99,6 +99,28 @@ describe.each(implementations)("Filesystem contract: $name", ({ create, link }) await expect(filesystem.readFile(file)).resolves.toBe("first writer"); }); + it("creates an exclusively written file with the mode it is given, and Node's default without one", async () => { + // why: #685: the exclusive create publishes by hard-linking a temp file, so a mode that + // did not ride on that file's create would leave the winner's file world-readable. A + // restrictive umask here would mask what the code asks for, so pin the one a host starts + // from and pin both halves: the mode a caller asks for, and the default it gets for free. + const previousUmask = process.umask(0o022); + try { + const filesystem = create(); + const asked = `${temporaryDirectory}/asked.json`; + const unasked = `${temporaryDirectory}/unasked.json`; + + await filesystem.mkdirp(temporaryDirectory); + await filesystem.writeFileExclusive(asked, "{}", { mode: 0o600 }); + await filesystem.writeFileExclusive(unasked, "{}"); + + expect((await filesystem.stat(asked)).mode).toBe(0o600); + expect((await filesystem.stat(unasked)).mode).toBe(0o644); + } finally { + process.umask(previousUmask); + } + }); + it("moves a directory and everything under it in one step", async () => { const filesystem = create(); const staging = `${temporaryDirectory}/.ios.staging`; diff --git a/src/ports/filesystem.ts b/src/ports/filesystem.ts index 40cf784a2..afe47c166 100644 --- a/src/ports/filesystem.ts +++ b/src/ports/filesystem.ts @@ -37,6 +37,12 @@ export interface WriteFileAtomicOptions { readonly mode?: number; } +/** why: Same shape as {@link WriteFileAtomicOptions}: `writeFileExclusive` publishes through a + * hard-linked temp file, so the mode rides on that file's create and the link preserves it. */ +export interface WriteFileExclusiveOptions { + readonly mode?: number; +} + /** * What an un-followed `lstat` reports, narrowed to what ownership validation asks of a * path: what it really is, who owns it, and how exposed it is. Anything richer would be @@ -61,7 +67,11 @@ export interface Filesystem { * end up agreeing about what it says. The file appears with its full contents, never * empty, so a loser that reads it straight away reads what the winner wrote. */ - writeFileExclusive(path: string, contents: string): Promise; + writeFileExclusive( + path: string, + contents: string, + options?: WriteFileExclusiveOptions, + ): Promise; mkdirp(path: string): Promise; /** * Moves a path in one step, so what it names becomes visible complete or not at all. @@ -136,7 +146,11 @@ export class NodeFilesystem implements Filesystem { } } - async writeFileExclusive(path: string, contents: string): Promise { + async writeFileExclusive( + path: string, + contents: string, + options?: WriteFileExclusiveOptions, + ): Promise { // `writeFile` with the `wx` flag creates the file empty and fills it a moment later, so a // racer that loses the create can read it in between and find nothing. Write the contents // aside first and hard-link them into place: `link` fails `EEXIST` like `wx` does, but the @@ -145,7 +159,16 @@ export class NodeFilesystem implements Filesystem { dirname(path), `.${basename(path)}.${process.pid}.${crypto.randomUUID()}.tmp`, ); - await writeFile(temporaryPath, contents, { encoding: "utf8", flag: "wx" }); + // why: the mode rides on the temp file's create -- a hard link carries it over, so the + // published file is never world-readable even briefly. A `chmod` after the link is the + // window this port's own doc rules out. + await writeFile( + temporaryPath, + contents, + options?.mode === undefined + ? { encoding: "utf8", flag: "wx" } + : { encoding: "utf8", flag: "wx", mode: options.mode }, + ); try { await link(temporaryPath, path); } finally { @@ -267,8 +290,9 @@ const DEFAULT_MEMORY_MODE = 0o700; // A symlink cycle is a legitimate thing to model; resolving it forever is not. const MAX_SYMLINK_HOPS = 32; -/** Node's default for a plain file, kept as the default `writeFileAtomic` creates with so a - * caller that says nothing about permissions gets what it got before `mode` was an option. */ +/** why: Node's default for a plain file, kept as the default both `writeFileAtomic` and + * `writeFileExclusive` create with so a caller that says nothing about permissions gets what + * it got before `mode` was an option. */ const DEFAULT_FILE_MODE = 0o644; export class MemoryFilesystem implements Filesystem { @@ -314,7 +338,11 @@ export class MemoryFilesystem implements Filesystem { }); } - async writeFileExclusive(path: string, contents: string): Promise { + async writeFileExclusive( + path: string, + contents: string, + options?: WriteFileExclusiveOptions, + ): Promise { this.#failIfDefined(path); path = this.#underResolvedParent(path); @@ -323,7 +351,10 @@ export class MemoryFilesystem implements Filesystem { } this.#requireDirectory(parentPath(path)); - this.#entries.set(path, this.#newEntry({ kind: "file", contents })); + this.#entries.set(path, { + ...this.#newEntry({ kind: "file", contents }), + mode: options?.mode ?? DEFAULT_FILE_MODE, + }); } async mkdirp(path: string): Promise { diff --git a/src/ports/logger.ts b/src/ports/logger.ts index 19c7b7b28..8edd79165 100644 --- a/src/ports/logger.ts +++ b/src/ports/logger.ts @@ -144,6 +144,12 @@ function readTail(file: string): string { } } +// why: Owner-only, like every other file the daemon keeps under `SIMLOCK_HOME` (`config.json`, +// `state.json`, `tokens.json`, `admin.token`): the trust boundary is the OS user, and a shared +// runner's other users have no business reading a daemon's log or event stream. Set at each +// `open`, never a later `chmod`, so no generation is ever born world-readable. +const FILE_MODE = 0o600; + export interface NodeFileLogSinkOptions { /** One generation: the size at which the current file rotates. */ readonly maxBytes?: number; @@ -200,7 +206,7 @@ export class NodeFileLogSink implements LogSink { this.#totalMaxBytes = options.totalMaxBytes; this.#clock = options.clock ?? new SystemClock(); mkdirSync(dirname(this.#path), { recursive: true }); - this.#fd = openSync(this.#path, "a"); + this.#fd = openSync(this.#path, "a", FILE_MODE); this.#bytesWritten = fstatSync(this.#fd).size; this.#sweep(); } @@ -232,7 +238,7 @@ export class NodeFileLogSink implements LogSink { this.#shiftGenerations(); } renameSync(this.#path, `${this.#path}.1`); - this.#fd = openSync(this.#path, "a"); + this.#fd = openSync(this.#path, "a", FILE_MODE); this.#bytesWritten = 0; this.#sweep(); } From c71e2debfe8e7a24baff223b136c015b2e45d9c8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 18 Oct 2026 17:59:20 +0200 Subject: [PATCH 3/4] docs(docs,ports,core): scope the 0600 comments and the events.jsonl claim (#685) --- docs/internal/EVENTS.md | 2 +- src/core/instance-identity.ts | 2 +- src/ports/daemon-launcher.ts | 6 +++--- src/ports/logger.ts | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index eb52c1b2a..bb6cbc6f8 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -143,7 +143,7 @@ left behind (#79), each when there is one. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `daemon.started` | version, config snapshot (`gateway.token`, when set, reads `[redacted]`: the payload reaches the ring and `events.jsonl`, which are not guarded like `config.json`; masked rather than dropped so the keys stay the same, #170) | daemon finished startup + reconcile | DaemonServer | implemented | +| `daemon.started` | version, config snapshot (`gateway.token`, when set, reads `[redacted]`: the payload reaches the ring and `events.jsonl`, which are not a token's place the way `config.json` and `config.get` are; masked rather than dropped so the keys stay the same, #170) | daemon finished startup + reconcile | DaemonServer | implemented | | `daemon.stopping` | reason | graceful shutdown began | DaemonServer | implemented | | `disk.pressure-detected` | free bytes, threshold | free disk crossed under the configured threshold (edge-triggered: once per crossing, not once per tick while it persists) | CleanupReaper | implemented | | `cleanup.executed` | rule name, action, target, reason | cleanup executor committed a proposed action | CleanupExecutor | implemented | diff --git a/src/core/instance-identity.ts b/src/core/instance-identity.ts index 88b9aadae..65193e919 100644 --- a/src/core/instance-identity.ts +++ b/src/core/instance-identity.ts @@ -2,7 +2,7 @@ import { dirname } from "node:path"; import type { Filesystem, IdGenerator } from "../ports/index.js"; -/** why: Owner-only, like every other file the daemon keeps under `SIMLOCK_HOME` (`config.json`, +/** why: Owner-only, like the other files that hold secrets or state (`config.json`, * `state.json`, `tokens.json`, `admin.token`): the trust boundary is the OS user, and the id this * file holds is what every device root's ownership marker is checked against. */ const INSTANCE_FILE_MODE = 0o600; diff --git a/src/ports/daemon-launcher.ts b/src/ports/daemon-launcher.ts index af7d12bab..930a345b6 100644 --- a/src/ports/daemon-launcher.ts +++ b/src/ports/daemon-launcher.ts @@ -37,9 +37,9 @@ export class NodeDaemonLauncher implements DaemonLauncher { async launch(): Promise { await mkdir(dirname(this.options.logPath), { recursive: true }); - // why: 0600 at creation, like every other file under `SIMLOCK_HOME` (`#258`'s rule): this - // `open` is what first creates `daemon.log` for an auto-launched daemon -- the daemon's own - // sink only appends to the file this one made. + // why: 0600 at creation, like the other files that hold secrets or state under the home: + // this `open` is what first creates `daemon.log` for an auto-launched daemon -- the daemon's + // own sink only appends to the file this one made. const log = await open(this.options.logPath, "a", 0o600); try { const child = spawn(this.options.command, this.options.args, { diff --git a/src/ports/logger.ts b/src/ports/logger.ts index 8edd79165..43f3163d3 100644 --- a/src/ports/logger.ts +++ b/src/ports/logger.ts @@ -144,7 +144,7 @@ function readTail(file: string): string { } } -// why: Owner-only, like every other file the daemon keeps under `SIMLOCK_HOME` (`config.json`, +// why: Owner-only, like the other files that hold secrets or state (`config.json`, // `state.json`, `tokens.json`, `admin.token`): the trust boundary is the OS user, and a shared // runner's other users have no business reading a daemon's log or event stream. Set at each // `open`, never a later `chmod`, so no generation is ever born world-readable. From 1c123ae9eb352ec581274c1ce0ca181294c3932d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 18 Oct 2026 18:00:46 +0200 Subject: [PATCH 4/4] docs(core): keep the manual within its line budget (#685) --- src/core/AGENTS.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index b76ff2db6..9e4c6e5b1 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -103,8 +103,7 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic quarantine stalls (age > estimate × `stalledTransition.thresholdMultiplier`, unclaimed). 9. **Physical** — `PhysicalEnrollment.add` refuses Simlock's own devices, reads `inspectPhysical`, writes `ready` with `enrolledApps`, or re-enrols under `enrollment`; `remove` unenrols. Busy: `DeviceBusyError`. -10. **Ownership** — `loadInstanceId` creates `instance.json` once (exclusive create, mode - `0600`). `ensureOwnedRoot` +10. **Ownership** — `loadInstanceId` creates `instance.json` once (exclusive create, `0600`). `ensureOwnedRoot` stages a root with `.simlock-owned.json` (instance id, platform), mode `0700`; doubt is `OwnedRootError`. 11. **Components** — `ComponentInstaller`, the only caller of `installComponent`/`removeComponent`. One FIFO per platform; a call for the same component joins. At the front: `stillNeeded` →