Skip to content

fix(daemon): stop malformed control and hello frames killing the daemon - #17848

Closed
klaidliadon wants to merge 4 commits into
stablyai:mainfrom
klaidliadon:fix/daemon-malformed-control-frame
Closed

klaidliadon wants to merge 4 commits into
stablyai:mainfrom
klaidliadon:fix/daemon-malformed-control-frame

Conversation

@klaidliadon

@klaidliadon klaidliadon commented Sep 1, 2026 •

Copy link
Copy Markdown

ELI5

The terminal daemon is the process kept alive on purpose so your terminals survive
restarts and updates. One badly-formed message on its control socket killed it —
and every terminal on the machine with it. This makes it drop the bad message
instead.

What Changed

Four guards across two frame paths, plus tests that drive a real daemon over a real
socket.

The pre-auth one is the most serious, and was found during review of this PR:

  • daemon-client-connections.ts, handleFirstMessage — the hello handler
    carried the same unchecked cast one frame earlier: const hello = message as HelloMessage; if (hello.type !== 'hello'). JSON.parse('null') is a valid
    frame, so .type threw. Two things make this worse than the control-frame case:
    the throw is synchronous inside the socket's data handler — onRecord is
    invoked outside the try that wraps JSON.parse in
    main-process-ndjson-framer.ts — so it is an uncaught exception rather than a
    rejection; and it runs before the token comparison, so it needs no
    credentials. Anything that can open the socket could end every terminal on the
    host with one null\n. It is now rejected exactly as any other unusable first
    frame is: Expected hello, then destroy.

  • daemon-client-connections.ts — new isDispatchableRequest() at the NDJSON
    boundary. createNdjsonParser hands through any parsed JSON, null included,
    and the callback asserted as DaemonRequest over it without checking anything.
    Frames with no usable id are now dropped and logged as control-frame-dropped
    with the client id.

  • daemon-server.ts, dispatch site — void this.handleRequest(...) now
    carries a .catch that logs control-request-failed.

  • daemon-server.ts, handleRequest — the request.id read is guarded with
    typeof, so the defect cannot return via a caller that bypasses the parser.

An unknown method still gets a proper error reply. That path was never broken.
Only an unroutable frame is dropped, and dropping is the only correlatable
answer available: a reply needs the id the frame did not carry.

Why

handleRequest read request.id one line above a try/catch that was already
there:

const isNotify = request.id.startsWith(NOTIFY_PREFIX)   // outside the try
try { ... }

On a frame without an id, that throws a TypeError. It escaped as an unhandled
rejection, reached the daemon's uncaughtException handler, and was rethrown
because it is not a native PTY error. One malformed frame, every terminal gone.

Why three guards and not one: each of the three independently allowed it, and the
one that actually threw is the least likely to be the one a future caller hits.
Fixing only the parser would leave handleRequest throwing for anyone who calls
it directly; fixing only handleRequest would leave every other rejection in that
async chain still fatal, because reaching uncaughtException at all is what turns
a routine error into a host-wide outage.

Linked Issue

Fixes #17841

Visual Proof

N/A — daemon-internal protocol handling. No UI or interaction surface; the
user-visible effect is the absence of a crash.

Testing

src/main/daemon/daemon-server-malformed-frame.test.ts starts a real
DaemonServer on a real unix socket, writes each malformed shape, and asserts the
daemon is still alive and still answers a well-formed request afterwards.

Confirmed to fail against the pre-fix code before it was kept — the test was
written against the unpatched server first and observed to take the daemon down,
so it is guarding the actual defect rather than restating the fix.

Platforms: developed and reproduced on Linux (Synology DSM). The code path is
platform-neutral — it is JSON parsing and promise handling, with no platform
branch. Not separately exercised on macOS or Windows.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Claude Opus 5 wrote the commits and this description. I reviewed them and ran the
verification on my own hardware.

Review

  • Cross-platform: no platform branches added or touched. Unix-socket vs named
    pipe transport is unchanged; the guards sit above the transport.
  • SSH/remote/local: the control socket is local to the host. A remote client
    reaching the daemon through the relay goes through the same dispatch, so it gets
    the same protection.
  • Agents/integrations: none. No agent-specific or provider-specific behaviour.
  • Performance: one typeof check and one property read per control frame,
    against a code path that already parses JSON per frame. The .catch allocates
    only on rejection. Not measurable.
  • UI: none.
  • Security: the hello-frame case above was an unauthenticated denial of
    service against every terminal on the host — it precedes the token check, so
    socket reachability was the only requirement. The control-frame case needs an
    authenticated client. Both are closed. Drops are logged with the client id, a
    generated identifier rather than user content; the malformed payload itself is
    never logged.
  • Backwards compatibility: a well-formed frame behaves identically. The only
    behaviour change is for frames that previously crashed the process.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Disjoint from my other open PRs — this touches only src/main/daemon/.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

A control frame whose `id` was missing or not a string took the daemon down,
and with it every terminal on the host — the one process deliberately kept
alive so terminals outlive the runtime, the supervisor and an update.

The read that threw sat one line above a try/catch that was already there:

    const isNotify = request.id.startsWith(NOTIFY_PREFIX)   // outside the try
    try { ... }

`request.id` on a frame without one throws a TypeError, which escaped as an
unhandled rejection, reached the daemon's uncaughtException handler, and was
rethrown because it is not a native PTY error. One malformed frame, every
terminal gone.

Fixed at the three places that each independently allowed it:

- **The NDJSON boundary.** `createNdjsonParser` hands through any parsed JSON,
  `null` included, and the callback asserted `as DaemonRequest` over it without
  checking. `isDispatchableRequest` now gates it. Dropping is the only
  correlatable answer available — a reply needs the `id` the frame did not
  carry — so the drop is logged with the client id instead.
- **The dispatch site.** `void this.handleRequest(...)` let any rejection escape.
  It now carries a `.catch` that logs, because reaching the uncaughtException
  handler at all is what makes a routine error fatal.
- **The id read itself.** Guarded with `typeof`, so the defect cannot come back
  through a caller that bypasses the parser.

An unknown *method* still gets an error reply; that path was never the problem.
Only an unroutable frame is dropped.

The test drives a real `DaemonServer` over a real socket and asserts the daemon
survives each malformed shape and still answers a well-formed request
afterwards. Confirmed to fail against the pre-fix code before it was kept.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UacRCfD4XPe29bD3ZWNc57
@greptile-apps

greptile-apps Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR hardens daemon control-frame handling so malformed or unroutable messages cannot terminate the terminal daemon.

  • Validates parsed control frames before dispatch and rejects non-object hello frames.
  • Contains asynchronous request failures at the dispatch boundary.
  • Adds real-socket coverage proving malformed frames are dropped while the daemon remains responsive.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
src/main/daemon/daemon-client-connections.ts Adds runtime validation at the hello and authenticated control-frame boundaries before protocol data is accessed or dispatched.
src/main/daemon/daemon-server.ts Guards direct request handling against invalid IDs and catches rejected request promises before they become process-fatal.
src/main/daemon/daemon-server-malformed-frame.test.ts Exercises malformed frames through an authenticated real socket and confirms the same daemon connection remains operational.

Reviews (2): Last reviewed commit: "fix(daemon): stop a non-object hello fra..." | Re-trigger Greptile

klaidliadon and others added 2 commits September 1, 2026 09:09
Review pointed out the coverage gap and it was real: every malformed frame was
handed to `handleRequest` directly, so the `isDispatchableRequest` gate on the
NDJSON boundary — the guard that actually stands between a hostile frame and the
daemon — was only ever exercised as a pure function. The test proved the third
guard twice and the first one not at all.

The frames are now written as raw bytes to an authenticated control socket, so
they arrive through `createNdjsonParser` exactly as a client's would, and the
proof of life is a `ping` round-trip on that same connection: it needs the
parser, the router and the reply write, and it cannot pass against a daemon that
has already exited.

Confirmed the socket path catches the original defect — against the pre-fix code
this fails with `TypeError: request.id.startsWith is not a function` raised from
`main-process-ndjson-framer.ts` through `daemon-client-connections.ts`, which is
the stack the old test never reached.

The direct-call case is kept, narrowed to what it is really for: `handleRequest`
has in-process callers the parser cannot gate, which is why the id read carries
its own guard.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UacRCfD4XPe29bD3ZWNc57
The same unchecked cast this branch already fixed on the control parser sits one
frame earlier, on the hello handler, and it is the worse of the two:

    const hello = message as HelloMessage
    if (hello.type !== 'hello') {

`JSON.parse('null')` is a perfectly valid frame, so `message` can be `null` and
the `.type` read throws. That throw is *synchronous*, inside the socket's `data`
handler, because `createNdjsonParser` does not wrap `onRecord` — so it is an
uncaught exception rather than a rejection, and it reaches the daemon's
uncaughtException handler by the same route. One `null\n` and every terminal on
the host is gone.

It also runs before the token comparison, so unlike the control-frame case it
needs no credentials at all: anything that can open the socket can use it.

Guarded where the existing shape checks already are, and answered the way the
handler already answers an unusable first frame — reject with "Expected hello"
and destroy. Nothing new is invented for it.

Confirmed against the pre-fix code: `TypeError: Cannot read properties of null
(reading 'type')` at `handleFirstMessage`, reported by vitest as an Uncaught
Exception, not a rejection.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UacRCfD4XPe29bD3ZWNc57
@klaidliadon

Copy link
Copy Markdown
Author

Thanks — the coverage gap Greptile flagged was real, and chasing it turned up a second live crash. Both are pushed.

1. The test now goes through the real parser (9d7f486)

The criticism was correct and worth more than it looked. Every malformed frame was handed to handleRequest directly, so isDispatchableRequest — the guard on the NDJSON boundary, the one thing actually standing between a hostile frame and the daemon — was only exercised as a pure function. The test proved the third guard twice and the first one not at all.

The frames are now written as raw bytes to an authenticated control socket, so they arrive through createNdjsonParser exactly as a client's would. The proof of life is a ping round-trip on that same connection: it needs the parser, the router and the reply write, and it cannot pass against a daemon that has already exited.

Checked it catches the original defect rather than assuming it does. Against the pre-fix code:

TypeError: request.id.startsWith is not a function
 ❯ DaemonServer.handleRequest src/main/daemon/daemon-server.ts:260:33
 ❯ Object.onControlRequest src/main/daemon/daemon-server.ts:127:19
 ❯ src/main/daemon/daemon-client-connections.ts:200:33
 ❯ src/shared/main-process-ndjson-framer.ts:296:18
 ❯ Socket.<anonymous> src/main/daemon/daemon-client-connections.ts:204:41

That is the stack the old test never reached.

2. A second, worse instance of the same defect (f6e32f0)

Writing the socket test meant reading the hello path, which has the identical unchecked cast one frame earlier:

const hello = message as HelloMessage
if (hello.type !== hello) {

JSON.parse('null') is a valid frame, so message can be null and the .type read throws. createNdjsonParser does not wrap onRecord, so that throw is synchronous inside the socket's data handler — an uncaught exception rather than a rejection, reaching the daemon's uncaughtException handler by the same route. Confirmed against pre-fix code:

TypeError: Cannot read properties of null (reading 'type')
 ❯ DaemonClientConnections.handleFirstMessage daemon-client-connections.ts:108:15
 ❯ src/shared/main-process-ndjson-framer.ts:296:18
 ❯ Socket.<anonymous> src/main/daemon/daemon-client-connections.ts:69:41

Reported by vitest as an Uncaught Exception, not a rejection. It also runs before the token comparison, so unlike the control-frame case it needs no credentials — anything that can open the socket can send null\n and take every terminal on the host with it. Guarded where the existing shape checks already are, answered the way the handler already answers an unusable first frame (reject with "Expected hello", destroy). Happy to split it into its own PR if you'd rather keep this one to the id read, but it is the same defect at the same boundary and leaving it felt worse.

On the three guards, since it may come up: each independently allowed the crash and they are not redundant. The parser gate cannot protect handleRequest from its in-process callers; the id-read guard cannot protect the hello handler, which never reaches it; and the .catch on the dispatch site is what stops any future escaping rejection from being fatal, not just this one. The third test in the file now says explicitly which caller each guard is for.

Unroutable frames are still dropped rather than error-replied — a reply has to be correlated against the id the frame did not carry. Unknown methods still get error replies; that path was never broken.

Verification: src/main/daemon/daemon-server-malformed-frame.test.ts 13/13 pass. Full src/main/daemon suite: 1738 passed, 16 failed — all 16 in six terminal-emulator/xterm-snapshot files (terminal-snapshot-*, headless-emulator-*, repro-13767-*), and I checked out the merge base and got the identical 16 failures there, so they are pre-existing in my environment and not from this change. I could not run pnpm lint/typecheck — oxlint/oxfmt are not installed in this checkout — so CI is the authority on those.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one coverage gap worth closing, and a nitpick.

Reviewed changes

  • Boundary guard — isDispatchableRequest() drops control frames without a non-empty string id at the NDJSON boundary and logs control-frame-dropped with the client id.
  • Dispatch-site catch — onControlRequest now routes handleRequest rejections to a control-request-failed log instead of the daemon's fatal uncaughtException path.
  • handleRequest guard — a typeof request?.id !== 'string' early return closes the same hole for callers that bypass the parser.
  • Tests — a real-socket DaemonServer integration test plus a unit block pinning isDispatchableRequest.

ℹ️ Nitpicks

  • isDispatchableRequest's predicate declares message is DaemonRequest after checking only id, so a frame like { id: 'abc' } (no type/payload) is narrowed to DaemonRequest even though it isn't one. Harmless today because the router's switch (request.type) falls through to the Unknown request type error reply, but the narrowing over-promises to future readers.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…a reply

Review flagged that `isDispatchableRequest` narrows to `DaemonRequest` after
checking only `id`, so `{ id: 'abc' }` is narrowed to a type it does not satisfy.
The narrowing is deliberate, but nothing said so and nothing held it in place.

Stopping at `id` is the whole point of the split: `type` belongs to
`DaemonRequestRouter.route`, which ends its switch with

    throw new Error(`Unknown request type: ${...}`)

and that throw is caught by `handleRequest`, which writes an `ok: false` reply.
So a frame with a usable id and a nonsense method is *answered*. Moving the
`type` check up to the boundary would demote that answer to a silent drop — the
one outcome a client cannot debug — which is why the guard deliberately does not
do it.

That was an assumption about a file the guard does not live in, so it is now a
test: two frames with real ids and no usable method, written over the control
socket, asserted to come back `ok: false` with `Unknown request type`.

Verified it is a real ratchet rather than decoration — adding
`typeof message.type === 'string'` to the predicate fails this test and only
this test (1 failed | 13 passed).

The declared type is left as it is. The only way to weaken it is to return
`message is { id: string }` and cast at the call site, which puts the bare
`as DaemonRequest` back on the exact line whose unchecked cast caused this bug.
The docblock now states the contract instead.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UacRCfD4XPe29bD3ZWNc57
@klaidliadon

Copy link
Copy Markdown
Author

@pullfrog — the coverage point was already addressed in 9d7f486 (replied on the thread; your review was written against 825d5a2 and says so). The nitpick is worth a real answer, and it produced a commit.

On isDispatchableRequest narrowing to DaemonRequest after checking only id

You are right that it over-promises, and I checked your reasoning rather than taking it: DaemonRequestRouter.route does end its switch with throw new Error(Unknown request type: ${...}), and that throw is caught by handleRequest, which writes an ok: false reply. So { id: 'abc' } is answered, exactly as you said.

I am keeping the declared type, for a specific reason. The only way to weaken it is message is { id: string } plus a cast at the call site — which puts the bare as DaemonRequest back on the exact line whose unchecked cast caused this bug. That trades an over-promising predicate for a re-armed footgun in the place a future reader is most likely to copy.

What your comment correctly identified is that nothing said the narrowing was deliberate, and nothing held it in place. Both are fixed in 85a4165:

  • The docblock now states the contract: the narrowing asserts routability, not method validity; type belongs to the router, and checking it at the boundary would demote an error reply to a silent drop — the one outcome a client cannot debug.
  • It is now a test rather than an assumption about a file the guard does not live in. Two frames with real ids and no usable method ({ id: 'unknown-method', type: 'nope' }, { id: 'no-method' }) go over the control socket and must come back ok: false / Unknown request type.

And I checked that test is a ratchet rather than decoration: adding typeof message.type === 'string' to the predicate fails it, and only it — 1 failed | 13 passed. So the next person who tries to "tighten" the boundary gets told why not.

Status: daemon-server-malformed-frame.test.ts 14/14. Full src/main/daemon: 1738 passed, 16 failed, all 16 in six terminal-emulator/xterm-snapshot files that fail identically on the merge base in my environment (they need a build artifact my sparse checkout lacks) — unrelated to this change. pnpm lint/typecheck I cannot run here; CI is the authority.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Pre-auth hello guard — handleFirstMessage now rejects a first frame that isn't an object (null\n, numbers, strings) with a { type: 'hello', ok: false } reply and destroys the socket, instead of reading .type off it and throwing synchronously inside the socket's data handler — which killed the daemon before any token check.
  • Socket-level test rewrite — the malformed frames are now written as raw NDJSON over a real unix socket so they traverse the actual isDispatchableRequest parser boundary, with a ping round-trip as proof of life, a hostile pre-auth null first-frame test, and a direct handleRequest bypass test retained for the third guard.

Both points from the prior review are addressed: the test now exercises the socket path end-to-end, and the pre-auth crash is closed. Verified locally: pnpm vitest run src/main/daemon/daemon-server-malformed-frame.test.ts passes 13/13.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Boundary contract documented — the isDispatchableRequest JSDoc now states explicitly that the narrowing stops at id on purpose: type validity belongs to DaemonRequestRouter.route, so a usable-id frame with an unknown or absent method still gets an Unknown request type error reply instead of a silent drop.
  • Unknown-method test — a new test writes { id: 'unknown-method', type: 'nope' } and { id: 'no-method' } over the real socket and asserts an ok: false reply containing Unknown request type, pinning that tightening the guard to check type would fail loudly.

Verified locally: pnpm vitest run src/main/daemon/daemon-server-malformed-frame.test.ts passes 14/14.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog

pullfrog Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Checked the reasoning rather than taking it, and it holds: DaemonRequestRouter.route ends its switch with throw new Error('Unknown request type: …') (daemon-request-router.ts:147), handleRequest catches it and writes ok: false (daemon-server.ts:284-294), so { id: 'abc' } is answered exactly as described. Keeping message is DaemonRequest over a message is { id: string } + call-site cast is the right trade — the latter re-arms the unchecked cast on the very line that caused the bug.

The docblock now makes the narrowing contract explicit, and the { id: 'unknown-method' } / { id: 'no-method' } frames over the real socket pin that a tightened predicate would drop { id: 'no-method' } silently and fail. A genuine ratchet, not decoration.

No further concerns.

Pullfrog  | View workflow run | via Pullfrog | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@klaidliadon klaidliadon changed the title fix(daemon): stop a control frame with no id killing the daemon fix(daemon): stop malformed control and hello frames killing the daemon Sep 1, 2026
@nwparker

Copy link
Copy Markdown
Contributor

Thanks @klaidliadon for the thorough investigation, especially catching the pre-auth hello case! This is already fixed on main by #26483 (e3639ef). handleFirstMessage now validates with isHelloFrame (so null or other non-object frames get Expected hello and a destroy), the control parser only dispatches frames that pass isDaemonRequestFrame and destroys the socket otherwise, and onControlRequest attaches a .catch to handleRequest so a rejection can't reach the daemon's fatal handler. If you can still crash the daemon with a malformed frame on the latest build, please comment or reopen with the payload.

@nwparker nwparker closed this Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: A control frame with no id kills the terminal daemon and every terminal on the host

2 participants