Repository navigation
fix(daemon): stop malformed control and hello frames killing the daemon - #17848
klaidliadon wants to merge 4 commits into
Conversation
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 SummaryThe PR hardens daemon control-frame handling so malformed or unroutable messages cannot terminate the terminal daemon.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| 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
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
|
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 The frames are now written as raw bytes to an authenticated control socket, so they arrive through Checked it catches the original defect rather than assuming it does. Against the pre-fix code: 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) {
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 On the three guards, since it may come up: each independently allowed the crash and they are not redundant. The parser gate cannot protect Unroutable frames are still dropped rather than error-replied — a reply has to be correlated against the Verification: |
There was a problem hiding this comment.
ℹ️ No critical issues — one coverage gap worth closing, and a nitpick.
Reviewed changes
- Boundary guard —
isDispatchableRequest()drops control frames without a non-empty stringidat the NDJSON boundary and logscontrol-frame-droppedwith the client id. - Dispatch-site catch —
onControlRequestnow routeshandleRequestrejections to acontrol-request-failedlog instead of the daemon's fataluncaughtExceptionpath. handleRequestguard — atypeof request?.id !== 'string'early return closes the same hole for callers that bypass the parser.- Tests — a real-socket
DaemonServerintegration test plus a unit block pinningisDispatchableRequest.
ℹ️ Nitpicks
isDispatchableRequest's predicate declaresmessage is DaemonRequestafter checking onlyid, so a frame like{ id: 'abc' }(notype/payload) is narrowed toDaemonRequesteven though it isn't one. Harmless today because the router'sswitch (request.type)falls through to theUnknown request typeerror reply, but the narrowing over-promises to future readers.
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
|
@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 You are right that it over-promises, and I checked your reasoning rather than taking it: I am keeping the declared type, for a specific reason. The only way to weaken it is What your comment correctly identified is that nothing said the narrowing was deliberate, and nothing held it in place. Both are fixed in 85a4165:
And I checked that test is a ratchet rather than decoration: adding Status: |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Pre-auth hello guard —
handleFirstMessagenow 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.typeoff it and throwing synchronously inside the socket'sdatahandler — 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
isDispatchableRequestparser boundary, with apinground-trip as proof of life, a hostile pre-authnullfirst-frame test, and a directhandleRequestbypass 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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Boundary contract documented — the
isDispatchableRequestJSDoc now states explicitly that the narrowing stops atidon purpose:typevalidity belongs toDaemonRequestRouter.route, so a usable-id frame with an unknown or absent method still gets anUnknown request typeerror 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 anok: falsereply containingUnknown request type, pinning that tightening the guard to checktypewould fail loudly.
Verified locally: pnpm vitest run src/main/daemon/daemon-server-malformed-frame.test.ts passes 14/14.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Checked the reasoning rather than taking it, and it holds: The docblock now makes the narrowing contract explicit, and the No further concerns.
|
|
Thanks @klaidliadon for the thorough investigation, especially catching the pre-auth hello case! This is already fixed on main by #26483 (e3639ef). |

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 handlercarried the same unchecked cast one frame earlier:
const hello = message as HelloMessage; if (hello.type !== 'hello').JSON.parse('null')is a validframe, so
.typethrew. Two things make this worse than the control-frame case:the throw is synchronous inside the socket's
datahandler —onRecordisinvoked outside the
trythat wrapsJSON.parseinmain-process-ndjson-framer.ts— so it is an uncaught exception rather than arejection; 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 firstframe is:
Expected hello, then destroy.daemon-client-connections.ts— newisDispatchableRequest()at the NDJSONboundary.
createNdjsonParserhands through any parsed JSON,nullincluded,and the callback asserted
as DaemonRequestover it without checking anything.Frames with no usable
idare now dropped and logged ascontrol-frame-droppedwith the client id.
daemon-server.ts, dispatch site —void this.handleRequest(...)nowcarries a
.catchthat logscontrol-request-failed.daemon-server.ts,handleRequest— therequest.idread is guarded withtypeof, 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
idthe frame did not carry.Why
handleRequestreadrequest.idone line above a try/catch that was alreadythere:
On a frame without an
id, that throws a TypeError. It escaped as an unhandledrejection, reached the daemon's
uncaughtExceptionhandler, and was rethrownbecause 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
handleRequestthrowing for anyone who callsit directly; fixing only
handleRequestwould leave every other rejection in thatasync chain still fatal, because reaching
uncaughtExceptionat all is what turnsa routine error into a host-wide outage.
Linked Issue
Fixes #17841
Visual Proof
N/A— daemon-internal protocol handling. No UI or interaction surface; theuser-visible effect is the absence of a crash.
Testing
src/main/daemon/daemon-server-malformed-frame.test.tsstarts a realDaemonServeron a real unix socket, writes each malformed shape, and asserts thedaemon 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.
AI Disclosure
Claude Opus 5 wrote the commits and this description. I reviewed them and ran the
verification on my own hardware.
Review
pipe transport is unchanged; the guards sit above the transport.
reaching the daemon through the relay goes through the same dispatch, so it gets
the same protection.
typeofcheck and one property read per control frame,against a code path that already parses JSON per frame. The
.catchallocatesonly on rejection. Not measurable.
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.
behaviour change is for frames that previously crashed the process.
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand 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
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)