fix(daemon): refuse an unsafe state directory before first use
fix(daemon): admit the state root, repairing an owned one the umask left open
Summary
Every state-directory write used to trust the directory it was handed: the launcher chmod'd a loose root into place at launch, and session-script-writer and provider-lease-expiry re-created or re-chmod'd their directories per write. An account that could plant a name on that route steered where the daemon's record, log and recordings went (#4649).
One rule now answers every question about that directory: admitPrivateRoot in packages/host-kit/src/internal/script-destination.ts — the walker that already judges a caller-named script destination (one walker, not two) — asked by admitDaemonStateRoot in packages/daemon-contracts/src/daemon-resolution.ts. Four call sites, one per route that reaches the root:
readRegisteredDaemoninpackages/daemon-client/src/daemon-client-metadata.ts, in repair mode, as its first statement. That function is the client's ONE reader ofdaemon.lockanddaemon.json, and a public export ofpackages/daemon-client/src/index.ts: the ensured transport the CLI and the MCP server use, the AI SDK tools,createAgentDeviceClient,ensureDaemonand an attach client all reach it, and none of them passsrc/cli.ts.src/cli.ts, in repair mode, where the invocation resolves itsDaemonPaths— kept because the connection defaults read, and the upgrade notifier writes, that directory before any client exists, and because a refusal must land with the command's own exit handling rather than inside a client.launchDaemonProcess, in establish mode, before it opensdaemon.log.daemon-runtime.ts, in establish mode, which is also the entry an embeddedstartAgentDeviceand a foreign-build daemon take.
Nothing is memoized. An absent root is admitted (a repair creates nothing), so a verdict cannot be carried to the next read: a long-lived MCP server whose root sits under a shared sticky parent must not skip the walk after an outside account plants a link there.
An owned root is repaired, not refused. A root this user owns that is a real directory with safe ancestry, but open through its own group or other bits, is brought to 0700 by one chmod and admitted, in both modes and judged with lstat. The update-check cache, the process lock, the log directory and every root an older build left behind create it under the host's umask, so a mkdir under a wide umask cannot decide whether a command runs (#4649). Only a chmod the host refuses ends it, as not-private. A symbolic link at the root, a foreign owner, a shared or world-writable ancestor, a .. step and a non-directory still refuse, in both modes, with details.reason: "daemon_state_root_unsafe" and { stateDir, component, problem, fix }. The reason is a member of DAEMON_STATE_ROOT_REASONS (as const satisfies Record<string, string>), not a literal at the throw site, so R89 sees a published vocabulary and website/docs/docs/configuration.md words every member.
Establish creates the root on every platform, Windows included, where it creates it recursively after the shape rule and asks no privacy question. Nothing is created below the root: sessions/ and sessions/remote-scripts/ are judged where they stand (link and owner) and the daemon makes each of its own names when it first needs it, so an empty state directory stays empty and a report-only command leaves it absent.
$ AGENT_DEVICE_STATE_DIR=$HOME/.agent-device agent-device daemon status
$ agent-device daemon status --json | jq .error.details.problem # "not-private" | "symlink" | ...
Deletions: repairStateMode and MODE_REPAIR_SKIPPED_CODES; the Windows log-reset reopen route (now one 'w' handle); the launcher's mkdirSync and its per-path chmodSync; chmodSync(filePath, 0o600) after publishFileSync in provider-lease-expiry (which now asks exactMode); the lease writer's recursive mkdirSync; the duplicate inspect calls in daemon-client-attach.ts, daemon-client-lifecycle.ts and src/cli/commands/daemon.ts.
Reverted as scope creep, suggested follow-up: publishFileSync in src/cli/auth-session.ts and src/cli/connection/generated-config.ts still writes a sensitive file in place.
Review round 1
- 0755 roots.
admitDirectorycloses an owned real directory's own group/other bits with onechmodbefore it can be a refusal, inadmitPrivateRoot, the one place the rule lives. Covered bya root a plain mkdir leaves at the umask default is repaired by the next establish(amkdirSyncunderumask 022— the production order CI hit),an owned root at mode 0755 or 0770 is repaired to 0700, and nothing is created below it, and the live run below.repairmode never creates, and neither mode refuses an owned open root. - Windows.
admitDaemonStateRootcreates the root recursively on win32 after the shape check, in establish mode, which covers both the launcher'sopenSync(logPath, 'a')anddaemon-runtime.ts.on a Windows host establish creates a missing root recursively and repair creates nothingruns on a mocked win32 host with an absent root and then opensdaemon.logat the absolute name the launcher uses, so the test fails on ENOENT if the create is dropped. - Admission seams. One site per route (see Summary). The three later inspects are deleted:
daemon-client-attach.ts,daemon-client-lifecycle.tsandsrc/cli/commands/daemon.tsare back tomain. - Also fixed:
DaemonStateRootProblemand the problem/exposure tables are module-private;resolveStateDirsplits on/on POSIX and on both separators on win32, so a POSIX directory nameda\bis a name, not a traversal;connect,authandconnection-runtimeare covered by thesrc/cli.tsadmission (proved live:auth statuson a planted link refuses withproblem: "symlink"before reading the connection state). - Complexity.
admitPrivateRootis split intoadmitDirectoryandverdictForAncestryFaultand is inside the thresholds; no Fallow allowlist or baseline entry was added.
Review round 2
R89 — the reason is published from its table. DAEMON_STATE_ROOT_REASONS.unsafe replaces the literal in unsafeStateRoot, so the throw site reads a declared table and R89 defers it. The layering scan is clean:
$ node --experimental-strip-types scripts/layering/check.ts
Layering guard: OK … and every wire-published reason literal names a value its file published at the merge-base (383 sites in 193 file(s) against 383 in 193).
Fallow, and the two steps CI skipped. fallow audit --base origin/main and check:production-exports both pass at this head — the unused-exports gate reports ✓ No issues found over 720 entry points. The one number the report shows, parseCliInputOrExit cognitive 16, is inherited from main and is not introduced here: main's own src/cli.ts:256 reports 13 cyclomatic · 16 ! cognitive for the same function, and git diff origin/main -- src/cli.ts changes only the two-line admission and one collapsed local. The audit gate exits 0 and names it an inherited finding; no baseline row was added. Round 1's extraction to src/cli/help-request.ts was reverted, because it paid 19 net lines for a finding this branch does not own; src/cli.ts stays at the max-lines limit of 1000.
No verdict is remembered. repairedStateRoots is gone, in both directions: an absent root no longer banks a pass, and no passed root does either, because the ground under a name can change between two reads of it. Two regressions cover it — a repair re-judges the root on every call, so a link planted after one cannot be read (contract) and a client that admitted an absent root refuses a link planted at it before its next read (the public readRegisteredDaemon). ADR 0016 now states the rule as "asks it again at the next one: a verdict is never remembered". The walk costs ~10 µs, so nothing needed memoizing.
The client admission moved to readRegisteredDaemon. It is now the first statement, before inspectProcessLock, and observeLocalDaemon no longer admits. Audit of the remaining client-side state reads, all of which follow an admission on every route:
daemon-client-metadata.ts—inspectProcessLockandreadDaemonRecordare insidereadRegisteredDaemon, after the admission.readDaemonInfoand thegetDaemonMetadataStateexists-checks indaemon-lifecycle-errors.tstake an already-resolved path.daemon-client-startup.ts— the threeinspectProcessLockcalls,readDaemonInfoand the log tail all sit on the startup path: afterreadReusableLocalDaemon(admitted), or afterstartDaemon→launchDaemonProcess, which admits in establish mode before it opensdaemon.log.daemon-client-attach.ts,daemon-client-lifecycle.ts,src/cli/commands/daemon.ts,src/mcp— no direct state-directory reads at all.
The planted-link client test now measures the route the client walks. It watches the SPELLED paths (<stateDir>/daemon.json and <stateDir>/daemon.lock) across readFileSync, openSync, lstatSync, statSync, existsSync and readdirSync, and it watches both transports: net.createConnection for the socket and http.request for HTTP (loadNodeHttpRequester resolves that same module object, so the probe goes through the spy). It runs once per transport.
Failing-before evidence, from the same test file with only admitDaemonStateRoot({ paths, mode: 'repair' }) removed from readRegisteredDaemon. The client reached the planted record on the spelled path in both transports, and the planted pid/port were in hand:
FAIL |unit-core| …daemon-client-startup-state-root.test.ts > a local client refuses a planted link … (socket)
FAIL |unit-core| …daemon-client-startup-state-root.test.ts > a local client refuses a planted link … (http)
AssertionError: Expected values to be strictly deep-equal:
+ [
+ 'lstatSync:/private/tmp/…/state/daemon.lock',
+ 'readFileSync:/private/tmp/…/state/daemon.json',
+ 'existsSync:/private/tmp/…/state/daemon.json',
+ 'existsSync:/private/tmp/…/state/daemon.lock'
+ ]
- []
FAIL … > a client refuses a state root another account owns before it reads the record there
AssertionError: Expected values to be strictly equal:
+ 'daemon-record-unreadable'
- 'daemon_state_root_unsafe'
FAIL … > a client that admitted an absent root refuses a link planted at it before its next read
Error: expected a refusal
Tests 4 failed (4)
A refused chmod no longer recommends the step that just failed. not-private keeps its refusal and its problem kind; its fix is one string naming both ways out: Run `chmod 700 <dir>`, or point AGENT_DEVICE_STATE_DIR at a private directory you own if that is refused. configuration.md words the same two steps.
remoteScriptPath keeps its chmod. Restored as it stands on main, with main's comment: that call creates sessions/remote-scripts itself, mkdir's mode is masked by the umask, and admission only ever judges names — it creates none of them. So an owner-bit umask such as 0o200 still leaves a usable directory.
Validation
Android Smoke and iOS Smoke are green at this head — see the checks on this PR. pnpm typecheck, pnpm lint, pnpm format, the eager-closure gate (913), the layering scan, check:production-exports and fallow audit --base origin/main pass.
- Live, root pre-created at 0755 by a non-admitting writer, re-run at this head:
The root went 755 → 700 and$ T=$(mktemp -d) && mkdir -m 755 $T/state && stat -f %Lp $T/state 755 $ AGENT_DEVICE_STATE_DIR=$T/state node bin/agent-device.mjs daemon status --json | head -3 { "success": true, "data": { $ stat -f %Lp $T/state && ls -A $T/state 700ls -Aprinted nothing: the repair created nothing below it. - Live, planted link, refused before the record is read:
The same refusal answers$ mkdir -m 700 $T/outside && echo '{"pid":4242,"port":42424,"httpPort":42424,"token":"planted"}' > $T/outside/daemon.json $ ln -s $T/outside $T/state $ AGENT_DEVICE_STATE_DIR=$T/state node bin/agent-device.mjs devices --json "reason": "daemon_state_root_unsafe", … "problem": "symlink"daemon status,devicesandauth status, on the CLI route and on the client route. - win32 host, absent root:
on a Windows host establish creates a missing root recursively and repair creates nothing—repaircreates nothing,establishcreates the nested root, and the launcher'sopenSync(…'daemon.log', 'a')then succeeds. - Suites: full
--project unit-core— 2091 files, 20149 tests, 0 failures.--project provider-integration test/integration/provider-scenarios/session-close-leak-oracle.test.tspasses; the leak oracle sees no straysessions/residue, because admission creates nothing below the root. - LOC: production (non-test under
srcandpackages/*/src) +215 / −66, net +149, within the +150 budget for the whole PR. - Docs: ADR 0016's admission section carries the ancestry-before-mode-change order, the per-route admission points including
readRegisteredDaemon, and the no-memo rule;website/docs/docs/configuration.md,commands.md,installation.mdandagent-setup.mdmatch;docs/agents/security.mdsays the daemon admits its state directory.
Unresolved risks: the check reads owner and mode bits, not ACLs or mount provenance (ADR 0016 says so); historical exposure of files already inside an admitted root is out of scope by design.