@@ -10,6 +10,7 @@ import { randomUUID } from 'node:crypto';
1010import type { DiagnosticsRecordRef , NormalizedError } from '@agent-device/kernel/errors' ;
1111import { normalizeError } from '@agent-device/kernel/errors' ;
1212import { LEASE_BACKENDS } from '@agent-device/kernel/contracts' ;
13+ import { isRecord } from '@agent-device/kernel/record' ;
1314import type { DaemonInvokeFn , DaemonRequest , DaemonResponse } from '../daemon-request.ts' ;
1415import { emitDiagnostic } from '@agent-device/host-kit/diagnostics' ;
1516import {
@@ -178,6 +179,10 @@ export async function createDaemonHttpServer(options: {
178179 }
179180
180181 readRpcRequestBody ( req , res , ( body ) => {
182+ // The flow owns this request's lifetime, so this call site must neither hold lifetime state
183+ // nor re-run it; the `catch` only answers. That answer is load-bearing: the daemon exits on
184+ // an `unhandledRejection`, so a rejection dropped here would let any process that reaches
185+ // the port stop the daemon with one request body.
181186 void handleRpcRequest ( {
182187 req,
183188 res,
@@ -186,6 +191,8 @@ export async function createDaemonHttpServer(options: {
186191 expectedToken : token ,
187192 instanceId,
188193 handleRequest,
194+ } ) . catch ( ( error : unknown ) => {
195+ sendUnownedRpcRequestFailure ( res , error ) ;
189196 } ) ;
190197 } ) ;
191198 } ) ;
@@ -242,7 +249,8 @@ async function handleRpcRequest(params: {
242249 const lifetime = beginRpcRequestLifetime ( { req, res, rpcId : validated . rpcRequest . id } ) ;
243250 // The `finally` below is the flow's only cleanup for a call that never reached an
244251 // invocation: unsound method params or a duplicate tracking id. An invoked request
245- // releases its own lifetime as the last step of answering.
252+ // releases its own lifetime as the last step of answering, before anything observing the
253+ // socket gets a turn.
246254 try {
247255 const admission = await admitRpcRequest ( {
248256 req,
@@ -275,7 +283,7 @@ async function handleRpcRequest(params: {
275283 // or a duplicate tracking id. The failure answer is on its way, so a socket closing
276284 // after it is not a client walking out on work still in flight.
277285 lifetime . markHandlerCompleted ( ) ;
278- sendRpcRequestFailure ( res , validated . rpcRequest , error ) ;
286+ sendRpcRequestFailure ( res , validated . rpcRequest . id , normalizeError ( error ) ) ;
279287 } finally {
280288 lifetime . release ( ) ;
281289 }
@@ -310,15 +318,25 @@ type RpcEnvelopeVerdict =
310318
311319/**
312320 * Parses and validates one `/rpc` body. A body that is not JSON gets the same -32700 answer
313- * the socket's `error` listener gives a stream that breaks before it ends.
321+ * the socket's `error` listener gives a stream that breaks before it ends. A body that parses as
322+ * anything but one object — `null`, a number, a string, an array — is refused as -32600 before
323+ * anything reads a property off it: reading through `null` throws, and that throw has no call to
324+ * answer for.
314325 */
315326function validateRpcRequestEnvelope ( body : string ) : RpcEnvelopeVerdict {
316- let rpcRequest : JsonRpcRequest ;
327+ let parsed : unknown ;
317328 try {
318- rpcRequest = JSON . parse ( body ) as JsonRpcRequest ;
329+ parsed = JSON . parse ( body ) ;
319330 } catch {
320331 return { ok : false , refusal : rpcParseErrorRefusal ( ) } ;
321332 }
333+ if ( ! isRecord ( parsed ) ) {
334+ return {
335+ ok : false ,
336+ refusal : rpcRefusal ( null , INVALID_REQUEST , 'Invalid Request' , 400 ) ,
337+ } ;
338+ }
339+ const rpcRequest = parsed as JsonRpcRequest ;
322340
323341 const refused = ( code : number , message : string , statusCode : number ) : RpcEnvelopeVerdict => ( {
324342 ok : false ,
@@ -493,7 +511,7 @@ async function admitRpcRequest(params: {
493511 outcome : 'rejected' ,
494512 refusal : rpcRefusal (
495513 rpcRequest . id ?? null ,
496- - 32602 ,
514+ INVALID_PARAMS ,
497515 'Invalid params: command is required' ,
498516 400 ,
499517 ) ,
@@ -636,34 +654,53 @@ async function invokeAdmittedRpcRequest(params: {
636654 writeRpcResponseEnvelope ( res , rpcAnswerFor ( rpcRequest , daemonResponse ) ) ;
637655 } catch ( error ) {
638656 lifetime . markHandlerCompleted ( ) ;
639- sendRpcRequestFailure ( res , rpcRequest , error ) ;
657+ sendRpcRequestFailure ( res , rpcRequest . id , normalizeError ( error ) ) ;
640658 } finally {
641659 lifetime . release ( ) ;
642660 }
643661}
644662
645663/**
646- * Answers a call that failed before an answer could be written — malformed wire input the
647- * method vocabulary refused, or a handler that threw. A status code goes only to a call
648- * that has not started answering; a stream already opened answers with its envelope.
664+ * Answers a `/rpc` request whose flow rejected before it took the answer over — a body the
665+ * envelope never turned into a call, or a flow that failed ahead of its own `try`. No call id is
666+ * knowable, so the refusal answers an unnamed call and the reason goes to the request diagnostics
667+ * as well as the socket: the daemon exits on an `unhandledRejection`, so a dropped rejection would
668+ * let any process that reaches the port stop it without ever passing the token check.
669+ */
670+ function sendUnownedRpcRequestFailure ( res : http . ServerResponse , error : unknown ) : void {
671+ const failure = normalizeError ( error ) ;
672+ emitDiagnostic ( {
673+ level : 'error' ,
674+ phase : 'rpc_request_flow_failed' ,
675+ data : { code : failure . code , message : failure . message } ,
676+ } ) ;
677+ // A socket this flow already started answering has an answer on its way; writing after it ends
678+ // the response throws, and an exception escaping this handler is the failure being prevented.
679+ if ( res . headersSent ) return ;
680+ sendRpcRequestFailure ( res , null , failure ) ;
681+ }
682+
683+ /**
684+ * Answers a call that failed before an answer could be written — malformed wire input the method
685+ * vocabulary refused, a handler that threw, or a flow that rejected outright. A status code goes
686+ * only to a call that has not started answering; a stream already opened answers with its envelope.
649687 */
650688function sendRpcRequestFailure (
651689 res : http . ServerResponse ,
652- rpcRequest : JsonRpcRequest ,
653- error : unknown ,
690+ requestId : JsonRpcRequest [ 'id' ] ,
691+ failure : NormalizedError ,
654692) : void {
655- const normalized = normalizeError ( error ) ;
656693 const response = createRpcError (
657- rpcRequest . id ?? null ,
658- jsonRpcCodeForNormalizedError ( normalized . code ) ,
659- normalized . message ,
660- normalized ,
694+ requestId ?? null ,
695+ jsonRpcCodeForNormalizedError ( failure . code ) ,
696+ failure . message ,
697+ failure ,
661698 ) ;
662699 if ( res . headersSent ) {
663700 writeRpcResponseEnvelope ( res , response ) ;
664701 return ;
665702 }
666- sendJson ( res , response , statusCodeForNormalizedError ( normalized . code ) ) ;
703+ sendJson ( res , response , statusCodeForNormalizedError ( failure . code ) ) ;
667704}
668705
669706function rpcAnswerFor ( rpcRequest : JsonRpcRequest , daemonResponse : DaemonResponse ) : JsonRpcResponse {
0 commit comments