Skip to main content

blitz_debug_control/
lib.rs

1//! Debug-only, loopback WebDriver transport for Blitz renderers.
2//!
3//! The server owns networking and session authentication. Renderer commands
4//! cross a typed Arc queue and must be executed by the UI/runtime thread.
5//!
6//! # Security boundary
7//!
8//! Enabling this server grants the holder of its per-process discovery token
9//! debugger-level control, including arbitrary JavaScript execution in the
10//! document. It deliberately has the same trust posture as a browser remote
11//! debugging port: loopback-only transport, an unpredictable token, and a
12//! descriptor created with owner-only permissions on Unix. It is not a sandbox
13//! or an authorization boundary against another process running as the same
14//! OS user and able to read that user's files. Production builds should leave
15//! the feature and its environment variables disabled.
16
17use std::fs::{self, OpenOptions};
18use std::io::{self, Write};
19use std::net::SocketAddr;
20use std::path::PathBuf;
21use std::pin::Pin;
22use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
23use std::sync::{Arc, Mutex, OnceLock};
24use std::task::{Poll, Waker};
25use std::time::Duration;
26
27use futures_util::{Stream, stream::FuturesUnordered};
28use nagoya::reactor::{Addr, Reactor, TcpListener, TcpStream};
29use serde::Serialize;
30use serde_json::{Value, json};
31
32mod handoff;
33use handoff::{CommandQueue, QueueError, Reply, ResponseWait};
34pub use handoff::{
35    CommandReceiver, IntoValueIter, RecvError, RecvTimeoutError, TryRecvError, TryValueIter,
36    ValueIter, ValueReceiver,
37};
38
39const PROTOCOL_VERSION: u32 = 1;
40const MAX_REQUEST_BYTES: usize = 1024 * 1024;
41const COMMAND_TIMEOUT: Duration = Duration::from_secs(5);
42const MAX_PENDING_COMMANDS: usize = 64;
43const MAX_CONNECTIONS: usize = 64;
44
45#[derive(Default)]
46struct ActiveSession(AtomicU64);
47
48impl ActiveSession {
49    fn create(&self) -> io::Result<Option<String>> {
50        let value = loop {
51            let mut bytes = [0_u8; 8];
52            getrandom::fill(&mut bytes).map_err(io::Error::other)?;
53            let value = u64::from_ne_bytes(bytes);
54            if value != 0 {
55                break value;
56            }
57        };
58        match self
59            .0
60            .compare_exchange(0, value, Ordering::AcqRel, Ordering::Acquire)
61        {
62            Ok(_) => Ok(Some(format!("{value:016x}"))),
63            Err(_) => Ok(None),
64        }
65    }
66
67    fn matches(&self, supplied: &str) -> bool {
68        u64::from_str_radix(supplied, 16)
69            .ok()
70            .is_some_and(|value| value != 0 && self.0.load(Ordering::Acquire) == value)
71    }
72
73    fn clear(&self) {
74        self.0.store(0, Ordering::Release);
75    }
76}
77
78/// Configuration for a loopback debug-control server.
79#[derive(Debug, Clone)]
80pub struct ServerConfig {
81    /// Loopback address to bind. Port zero asks the OS to choose a free port.
82    pub bind_address: SocketAddr,
83    /// Atomically written once the server is accepting connections.
84    pub descriptor_path: PathBuf,
85    /// Git revision or build identifier for the renderer.
86    pub renderer_revision: String,
87}
88
89/// Wakes whichever thread services requests, so it does not have to poll for
90/// them.
91///
92/// The server cannot know how to wake its embedder, and the embedder's event
93/// loop does not exist yet when the server starts, so the callback is installed
94/// later. A `OnceLock` rather than a lock because it is written exactly once
95/// and read on the path of every request.
96///
97/// Without one installed the embedder must poll, which is what the Blitz shell
98/// used to do on a 10ms timer: 100 wakeups a second while idle, up to 10ms of
99/// latency on every command, and enough of both to show up in any measurement
100/// taken with the driver attached.
101#[derive(Clone, Default)]
102pub struct ServiceWaker(Arc<OnceLock<Box<dyn Fn() + Send + Sync>>>);
103
104impl ServiceWaker {
105    /// Install the wake callback. Later calls are ignored.
106    pub fn set(&self, wake: impl Fn() + Send + Sync + 'static) {
107        if self.0.set(Box::new(wake)).is_ok() {
108            // A request may have arrived before the embedder installed us.
109            self.wake();
110        }
111    }
112
113    fn wake(&self) {
114        if let Some(wake) = self.0.get() {
115            wake();
116        }
117    }
118}
119
120impl std::fmt::Debug for ServiceWaker {
121    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        formatter
123            .debug_struct("ServiceWaker")
124            .field("installed", &self.0.get().is_some())
125            .finish()
126    }
127}
128
129/// A command forwarded from the HTTP server to the renderer thread.
130#[derive(Debug)]
131pub struct ControlRequest {
132    pub method: String,
133    pub path: String,
134    pub body: Value,
135    reply: Arc<Reply>,
136}
137
138impl ControlRequest {
139    /// Hand the finished pointer to the waiting transport task.
140    pub fn respond_arc(&self, response: Arc<ControlResponse>) -> Result<(), Arc<ControlResponse>> {
141        self.reply.complete(response)
142    }
143
144    /// Complete this request. Failure means the client already disconnected.
145    pub fn respond(self, response: ControlResponse) -> Result<(), ControlResponse> {
146        self.respond_arc(Arc::new(response)).map_err(|response| {
147            Arc::try_unwrap(response).expect("failed response is uniquely owned")
148        })
149    }
150}
151
152impl Drop for ControlRequest {
153    fn drop(&mut self) {
154        self.reply.close_sender();
155    }
156}
157
158/// A renderer response represented using W3C WebDriver success/error values.
159#[derive(Debug)]
160pub enum ControlResponse {
161    Success(Value),
162    Error {
163        error: String,
164        message: String,
165        stacktrace: String,
166    },
167}
168
169impl ControlResponse {
170    pub fn unsupported(message: impl Into<String>) -> Self {
171        Self::Error {
172            error: "unsupported operation".into(),
173            message: message.into(),
174            stacktrace: String::new(),
175        }
176    }
177}
178
179#[derive(Debug, Serialize)]
180#[serde(rename_all = "camelCase")]
181struct Descriptor<'a> {
182    pid: u32,
183    address: String,
184    protocol_version: u32,
185    renderer: &'static str,
186    renderer_revision: &'a str,
187}
188
189/// Running server. Dropping it shuts down the listener and removes discovery.
190pub struct DebugServer {
191    address: SocketAddr,
192    token: String,
193    descriptor_path: PathBuf,
194    waker: ServiceWaker,
195    state: Option<Arc<ServerState>>,
196    task: Option<nagoya::JoinHandle<()>>,
197    reactor: Option<Reactor>,
198}
199
200struct CommandSink(Arc<CommandQueue>);
201
202impl CommandSink {
203    fn enqueue(&self, request: Arc<ControlRequest>) -> Result<(), &'static str> {
204        self.0.enqueue(request).map_err(|error| match error {
205            QueueError::Full => "renderer command queue is full",
206            QueueError::Closed => "renderer command channel is closed",
207        })
208    }
209
210    fn close(&self) {
211        self.0.close();
212    }
213}
214
215struct ServerState {
216    token: Arc<String>,
217    active_session: ActiveSession,
218    commands: CommandSink,
219    waker: ServiceWaker,
220    shutdown: AtomicBool,
221    stop_waker: Mutex<Option<Waker>>,
222}
223
224impl DebugServer {
225    /// Bind a loopback port and deliver owned values through the typed ring.
226    pub fn start(config: ServerConfig) -> io::Result<(Self, ValueReceiver)> {
227        let (server, receiver) = Self::start_typed(config)?;
228        Ok((server, ValueReceiver(receiver)))
229    }
230
231    /// Bind a loopback port and hand typed request pointers to the renderer.
232    pub fn start_typed(config: ServerConfig) -> io::Result<(Self, CommandReceiver)> {
233        let queue = CommandQueue::new(MAX_PENDING_COMMANDS);
234        let server = Self::start_with_sink(config, CommandSink(Arc::clone(&queue)))?;
235        Ok((server, CommandReceiver(queue)))
236    }
237
238    /// Bind a loopback port with an authentication token supplied by the embedding process.
239    pub fn start_typed_with_token(
240        config: ServerConfig,
241        token: impl Into<String>,
242    ) -> io::Result<(Self, CommandReceiver)> {
243        let queue = CommandQueue::new(MAX_PENDING_COMMANDS);
244        let server =
245            Self::start_with_sink_and_token(config, CommandSink(Arc::clone(&queue)), token.into())?;
246        Ok((server, CommandReceiver(queue)))
247    }
248
249    fn start_with_sink(config: ServerConfig, commands: CommandSink) -> io::Result<Self> {
250        Self::start_with_sink_and_token(config, commands, random_hex(32)?)
251    }
252
253    fn start_with_sink_and_token(
254        config: ServerConfig,
255        commands: CommandSink,
256        token: String,
257    ) -> io::Result<Self> {
258        if token.len() < 32 {
259            return Err(io::Error::new(
260                io::ErrorKind::InvalidInput,
261                "debug-control token must contain at least 32 bytes",
262            ));
263        }
264        if !config.bind_address.ip().is_loopback() {
265            return Err(io::Error::new(
266                io::ErrorKind::InvalidInput,
267                "debug control must bind to a loopback address",
268            ));
269        }
270        let reactor = Reactor::start().map_err(reactor_error)?;
271        let listener = TcpListener::bind(reactor_addr(config.bind_address), &reactor.handle())
272            .map_err(reactor_error)?;
273        let address = socket_addr(listener.local_addr().map_err(reactor_error)?)?;
274        let waker = ServiceWaker::default();
275        let state = Arc::new(ServerState {
276            token: Arc::new(token.clone()),
277            active_session: ActiveSession::default(),
278            commands,
279            waker: waker.clone(),
280            shutdown: AtomicBool::new(false),
281            stop_waker: Mutex::new(None),
282        });
283        write_descriptor(&config, address)?;
284        let task = nagoya::runtime::background().spawn(server_loop(listener, Arc::clone(&state)));
285        Ok(Self {
286            address,
287            token,
288            descriptor_path: config.descriptor_path,
289            waker,
290            state: Some(state),
291            task: Some(task),
292            reactor: Some(reactor),
293        })
294    }
295
296    /// Handle for waking the renderer after a request has been queued.
297    pub fn waker(&self) -> ServiceWaker {
298        self.waker.clone()
299    }
300
301    pub fn address(&self) -> SocketAddr {
302        self.address
303    }
304
305    pub fn token(&self) -> &str {
306        &self.token
307    }
308
309    pub fn shutdown(mut self) {
310        self.stop();
311    }
312
313    fn stop(&mut self) {
314        if let Some(state) = self.state.take() {
315            state.commands.close();
316            state.shutdown.store(true, Ordering::Release);
317            let wake = state.stop_waker.lock().unwrap().take();
318            if let Some(wake) = wake {
319                wake.wake();
320            }
321        }
322        if let Some(task) = self.task.take() {
323            let _ = nagoya::block_on(task);
324        }
325        if let Some(reactor) = self.reactor.take() {
326            reactor.shutdown();
327        }
328        let _ = fs::remove_file(&self.descriptor_path);
329    }
330}
331
332impl Drop for DebugServer {
333    fn drop(&mut self) {
334        self.stop();
335    }
336}
337
338fn reactor_error(error: nagoya::reactor::Errno) -> io::Error {
339    io::Error::from_raw_os_error(error.0)
340}
341
342fn reactor_addr(address: SocketAddr) -> Addr {
343    match address {
344        SocketAddr::V4(address) => Addr::V4(address.ip().octets(), address.port()),
345        SocketAddr::V6(address) => {
346            Addr::V6Scoped(address.ip().octets(), address.port(), address.scope_id())
347        }
348    }
349}
350
351fn socket_addr(address: Addr) -> io::Result<SocketAddr> {
352    match address {
353        Addr::V4(ip, port) => Ok((std::net::Ipv4Addr::from(ip), port).into()),
354        Addr::V6(ip, port) => Ok((std::net::Ipv6Addr::from(ip), port).into()),
355        Addr::V6Scoped(ip, port, scope) => {
356            Ok(std::net::SocketAddrV6::new(std::net::Ipv6Addr::from(ip), port, 0, scope).into())
357        }
358        Addr::Path(_) => Err(io::Error::new(
359            io::ErrorKind::InvalidInput,
360            "expected a TCP address",
361        )),
362    }
363}
364
365fn random_hex(byte_len: usize) -> io::Result<String> {
366    let mut bytes = vec![0; byte_len];
367    getrandom::fill(&mut bytes).map_err(io::Error::other)?;
368    let mut output = String::with_capacity(byte_len * 2);
369    for byte in bytes {
370        use std::fmt::Write as _;
371        write!(output, "{byte:02x}").unwrap();
372    }
373    Ok(output)
374}
375
376fn write_descriptor(config: &ServerConfig, address: SocketAddr) -> io::Result<()> {
377    let descriptor = Descriptor {
378        pid: std::process::id(),
379        address: address.to_string(),
380        protocol_version: PROTOCOL_VERSION,
381        renderer: "blitz",
382        renderer_revision: &config.renderer_revision,
383    };
384    let bytes = serde_json::to_vec_pretty(&descriptor).map_err(io::Error::other)?;
385    if contains_environment_secret(config.descriptor_path.to_string_lossy().as_bytes())
386        || contains_environment_secret(&bytes)
387    {
388        return Err(io::Error::new(
389            io::ErrorKind::PermissionDenied,
390            "refusing to write a debug-control descriptor containing an environment secret",
391        ));
392    }
393    if let Some(parent) = config.descriptor_path.parent() {
394        fs::create_dir_all(parent)?;
395    }
396    let temporary = config
397        .descriptor_path
398        .with_extension(format!("tmp-{}", random_hex(8)?));
399    let result = (|| {
400        let mut options = OpenOptions::new();
401        options.write(true).create_new(true);
402        #[cfg(unix)]
403        {
404            use std::os::unix::fs::OpenOptionsExt;
405            options.mode(0o600);
406        }
407        let mut file = options.open(&temporary)?;
408        file.write_all(&bytes)?;
409        file.sync_all()?;
410        fs::rename(&temporary, &config.descriptor_path)
411    })();
412    if result.is_err() {
413        let _ = fs::remove_file(&temporary);
414    }
415    result
416}
417
418fn contains_environment_secret(content: &[u8]) -> bool {
419    std::env::vars_os().any(|(name, value)| {
420        let name = name.to_string_lossy().to_ascii_uppercase();
421        if !is_secret_environment_name(&name) {
422            return false;
423        }
424        let value = value.to_string_lossy();
425        if value.is_empty() {
426            return false;
427        }
428        let raw = value.as_bytes();
429        let encoded = serde_json::to_vec(value.as_ref()).unwrap_or_default();
430        content.windows(raw.len()).any(|part| part == raw)
431            || (!encoded.is_empty()
432                && content
433                    .windows(encoded.len())
434                    .any(|part| part == encoded.as_slice()))
435    })
436}
437
438fn is_secret_environment_name(name: &str) -> bool {
439    [
440        "PASSWORD",
441        "PASSWD",
442        "TOKEN",
443        "SECRET",
444        "SEED",
445        "PRIVATE_KEY",
446        "ACCESS_KEY",
447        "CREDENTIAL",
448        "COOKIE",
449        "JWT",
450        "SESSION",
451    ]
452    .iter()
453    .any(|needle| name.contains(needle))
454        || name.contains("_KEY")
455        || name.ends_with("KEY")
456}
457
458async fn server_loop(listener: TcpListener, state: Arc<ServerState>) {
459    let mut connections = FuturesUnordered::new();
460    std::future::poll_fn(|cx| {
461        {
462            let mut wake = state.stop_waker.lock().unwrap();
463            if state.shutdown.load(Ordering::Acquire) {
464                return Poll::Ready(());
465            }
466            *wake = Some(cx.waker().clone());
467        }
468        while let Poll::Ready(Some(())) = Pin::new(&mut connections).poll_next(cx) {}
469        // One extra slot reports the connection limit. Until it finishes,
470        // accept is backpressured, keeping all connection work bounded.
471        if connections.len() <= MAX_CONNECTIONS {
472            match listener.poll_accept(cx) {
473                Poll::Ready(Ok((stream, _))) => {
474                    let limited = connections.len() == MAX_CONNECTIONS;
475                    connections.push(serve_connection(stream, Arc::clone(&state), limited));
476                    cx.waker().wake_by_ref();
477                }
478                Poll::Ready(Err(_)) => {
479                    state.commands.close();
480                    return Poll::Ready(());
481                }
482                Poll::Pending => {}
483            }
484        }
485        Poll::Pending
486    })
487    .await;
488    // Dropping these futures releases every socket and response waiter.
489    drop(connections);
490}
491
492async fn serve_connection(mut stream: TcpStream, state: Arc<ServerState>, limited: bool) {
493    let response = if limited {
494        webdriver_error("unknown error", "debug-control connection limit reached")
495    } else {
496        match read_request(&mut stream).await {
497            Ok(request) => route(request, &state).await,
498            Err(error) => webdriver_error("invalid argument", error.to_string()),
499        }
500    };
501    let _ = nagoya::time::timeout(COMMAND_TIMEOUT, write_response(&mut stream, response)).await;
502}
503
504#[derive(Debug)]
505struct HttpRequest {
506    method: String,
507    path: String,
508    body: Value,
509}
510
511async fn read_request(stream: &mut TcpStream) -> io::Result<HttpRequest> {
512    read_request_within(stream, COMMAND_TIMEOUT).await
513}
514
515async fn read_request_within(stream: &mut TcpStream, within: Duration) -> io::Result<HttpRequest> {
516    nagoya::time::timeout(within, read_request_inner(stream))
517        .await
518        .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
519}
520
521async fn read_request_inner(stream: &mut TcpStream) -> io::Result<HttpRequest> {
522    // Read directly into uninitialised receive storage, with a fixed bound.
523    let mut bytes = bytes::BytesMut::with_capacity(MAX_REQUEST_BYTES);
524    let mut scan_from = 0;
525    let header_end = loop {
526        if bytes.len() >= MAX_REQUEST_BYTES {
527            return Err(io::Error::new(
528                io::ErrorKind::InvalidData,
529                "request is too large",
530            ));
531        }
532        let prior_len = bytes.len();
533        let count = stream.read_buf(&mut bytes).await.map_err(reactor_error)?;
534        if count == 0 {
535            return Err(io::Error::new(
536                io::ErrorKind::UnexpectedEof,
537                "connection closed before headers",
538            ));
539        }
540        scan_from = scan_from.min(prior_len.saturating_sub(3));
541        if let Some(index) = bytes[scan_from..]
542            .windows(4)
543            .position(|window| window == b"\r\n\r\n")
544        {
545            break scan_from + index + 4;
546        }
547        scan_from = bytes.len().saturating_sub(3);
548    };
549
550    let headers = std::str::from_utf8(&bytes[..header_end])
551        .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
552    let mut lines = headers.split("\r\n");
553    let mut request_line = lines.next().unwrap_or_default().split_whitespace();
554    let method = request_line.next().unwrap_or_default().to_string();
555    let path = request_line.next().unwrap_or_default().to_string();
556    if method.is_empty() || path.is_empty() {
557        return Err(io::Error::new(
558            io::ErrorKind::InvalidData,
559            "invalid request line",
560        ));
561    }
562    let header_fields: Vec<_> = lines.filter_map(|line| line.split_once(':')).collect();
563    let content_length = header_fields
564        .iter()
565        .copied()
566        .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
567        .map(|(_, value)| value.trim().parse::<usize>())
568        .transpose()
569        .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?
570        .unwrap_or(0);
571    if header_fields.iter().any(|(name, value)| {
572        name.eq_ignore_ascii_case("transfer-encoding")
573            && !value.trim().eq_ignore_ascii_case("identity")
574    }) {
575        return Err(io::Error::new(
576            io::ErrorKind::InvalidData,
577            "transfer-encoding is unsupported; send Content-Length",
578        ));
579    }
580    let body_end = header_end
581        .checked_add(content_length)
582        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "request size overflow"))?;
583    if body_end > MAX_REQUEST_BYTES {
584        return Err(io::Error::new(
585            io::ErrorKind::InvalidData,
586            "request is too large",
587        ));
588    }
589    while bytes.len() < body_end {
590        let count = stream.read_buf(&mut bytes).await.map_err(reactor_error)?;
591        if count == 0 {
592            return Err(io::Error::new(
593                io::ErrorKind::UnexpectedEof,
594                "connection closed before body",
595            ));
596        }
597    }
598    let body = if content_length == 0 {
599        Value::Null
600    } else {
601        serde_json::from_slice(&bytes[header_end..body_end])
602            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?
603    };
604    Ok(HttpRequest { method, path, body })
605}
606
607async fn route(request: HttpRequest, state: &ServerState) -> Value {
608    let token = state.token.as_str();
609    let active_session = &state.active_session;
610    if request.method == "GET" && request.path == "/status" {
611        return json!({"value": {
612            "ready": true,
613            "message": "Blitz debug control is ready",
614            "protocolVersion": PROTOCOL_VERSION,
615        }});
616    }
617
618    if request.method == "POST" && request.path == "/session" {
619        let supplied_token = request
620            .body
621            .pointer("/capabilities/alwaysMatch/blitz:token")
622            .and_then(Value::as_str);
623        if !token_matches(supplied_token, token) {
624            return webdriver_error("invalid argument", "invalid blitz:token capability");
625        }
626        let session_id = match active_session.create() {
627            Ok(Some(value)) => value,
628            Ok(None) => {
629                return webdriver_error("session not created", "only one session is supported");
630            }
631            Err(error) => return webdriver_error("unknown error", error.to_string()),
632        };
633        return json!({"value": {
634            "sessionId": session_id,
635            "capabilities": {
636                "browserName": "blitz",
637                "blitz:protocolVersion": PROTOCOL_VERSION,
638            }
639        }});
640    }
641
642    let Some((session_id, command_path)) = session_path(&request.path) else {
643        return webdriver_error("unknown command", "unknown debug-control route");
644    };
645    if !active_session.matches(session_id) {
646        return webdriver_error("invalid session id", "session is not active");
647    }
648    if request.method == "DELETE" && command_path.is_empty() {
649        active_session.clear();
650        return json!({"value": null});
651    }
652
653    let reply = Reply::new();
654    let response = ResponseWait::new(&reply);
655    let control_request = Arc::new(ControlRequest {
656        method: request.method,
657        path: command_path.to_string(),
658        body: request.body,
659        reply,
660    });
661    if let Err(message) = state.commands.enqueue(control_request) {
662        return webdriver_error("unknown error", message);
663    }
664    state.waker.wake();
665    match nagoya::time::timeout(COMMAND_TIMEOUT, response).await {
666        Ok(Ok(response)) => match response.as_ref() {
667            ControlResponse::Success(value) => json!({"value": value}),
668            ControlResponse::Error {
669                error,
670                message,
671                stacktrace,
672            } => json!({"value": {
673                "error": error,
674                "message": message,
675                "stacktrace": stacktrace,
676            }}),
677        },
678        Err(_) => webdriver_error("timeout", "renderer command timed out"),
679        Ok(Err(())) => webdriver_error("unknown error", "renderer response channel is closed"),
680    }
681}
682
683/// Compare an attacker-controlled capability with the fixed-size discovery
684/// token without leaking how many prefix bytes matched.
685fn token_matches(supplied: Option<&str>, expected: &str) -> bool {
686    let supplied = supplied.unwrap_or_default().as_bytes();
687    let expected = expected.as_bytes();
688    let mut difference = supplied.len() ^ expected.len();
689    for (index, expected_byte) in expected.iter().enumerate() {
690        difference |= usize::from(*expected_byte ^ supplied.get(index).copied().unwrap_or(0));
691    }
692    difference == 0
693}
694
695fn session_path(path: &str) -> Option<(&str, &str)> {
696    let remainder = path.strip_prefix("/session/")?;
697    let (session_id, command) = remainder.split_once('/').unwrap_or((remainder, ""));
698    Some((session_id, command))
699}
700
701fn webdriver_error(error: &str, message: impl Into<String>) -> Value {
702    json!({"value": {
703        "error": error,
704        "message": message.into(),
705        "stacktrace": "",
706    }})
707}
708
709async fn write_response(stream: &mut TcpStream, body: Value) -> io::Result<()> {
710    let bytes = serde_json::to_vec(&body).map_err(io::Error::other)?;
711    let status = match body.pointer("/value/error").and_then(Value::as_str) {
712        None => "200 OK",
713        Some("unknown command" | "invalid session id") => "404 Not Found",
714        Some("timeout" | "unknown error") => "500 Internal Server Error",
715        Some(_) => "400 Bad Request",
716    };
717    let header = format!(
718        "HTTP/1.1 {status}\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
719        bytes.len()
720    );
721    stream
722        .write_all_vectored(header.as_bytes(), &bytes)
723        .await
724        .map_err(reactor_error)
725}