whisker_dev_protocol/lib.rs
1//! Authenticated wire protocol for the `whisker run` development channel
2//!
3//! `whisker run` (through `whisker-dev-server`) and the app it launches
4//! (through `whisker-dev-runtime`) talk over a WebSocket that can deliver
5//! native libraries the app then loads. This crate holds everything both
6//! sides must agree on so that only the app launched by the current session
7//! accepts those libraries, and only the current session's server can send
8//! them:
9//!
10//! - the per-session secret ([`generate_secret`]) and operating-system
11//! randomness ([`random_bytes`]),
12//! - the mutual-authentication handshake ([`ClientHandshake`] and
13//! [`ServerHandshake`]),
14//! - the replay-protected envelope every later message travels in
15//! ([`Session`] and [`FrameKind`]),
16//! - the size limits and timeout both peers enforce.
17//!
18//! The crate performs no I/O. The dev server and the dev runtime own their
19//! sockets, feed received handshake text into these state machines, and send
20//! whatever text or bytes the state machines return.
21//!
22//! # Handshake
23//!
24//! ```text
25//! app (client) whisker run (server)
26//! ClientHandshake::start ── challenge ──▶ ServerHandshake::respond
27//! ClientHandshake::finish ◀── server proof ──
28//! ── client proof ─▶ ServerHandshake::finish
29//! ```
30//!
31//! Both nonces are fresh 256-bit random values. Each proof is an
32//! HMAC-SHA256 over both nonces under a role-specific domain, so neither
33//! proof can be reflected back as the other. The secret itself never crosses
34//! the wire. The client verifies the server before it sends anything that
35//! identifies the process, which keeps a substituted server from learning the
36//! app's ASLR reference, logs, or trace data. There is no version
37//! negotiation: a peer built against a different protocol version fails the
38//! handshake with an [`Error`] that names the mismatch.
39//!
40//! # Envelope
41//!
42//! After the handshake every message is a binary envelope:
43//!
44//! ```text
45//! [version: u8][kind: u8][sequence: u64 BE][payload][HMAC-SHA256: 32 bytes]
46//! ```
47//!
48//! The tag covers the direction, both nonces, and every envelope byte before
49//! it. Each direction must use the next sequence number, so modified,
50//! replayed, reordered, reflected, and cross-session envelopes fail
51//! [`Session::open`] before the payload reaches a parser.
52//!
53//! # Example
54//!
55//! ```rust
56//! use whisker_dev_protocol::{ClientHandshake, FrameKind, ServerHandshake};
57//!
58//! let secret = whisker_dev_protocol::generate_secret()?;
59//!
60//! let (client, challenge) = ClientHandshake::start(&secret)?;
61//! let (server, server_proof) = ServerHandshake::respond(&secret, &challenge)?;
62//! let (mut app, client_proof) = client.finish(&server_proof)?;
63//! let mut host = server.finish(&client_proof)?;
64//!
65//! let envelope = host.seal(FrameKind::Text, br#"{"kind":"reload"}"#)?;
66//! assert_eq!(
67//! app.open(&envelope)?,
68//! (FrameKind::Text, br#"{"kind":"reload"}"#.as_slice())
69//! );
70//! // The same envelope is rejected the second time.
71//! assert!(app.open(&envelope).is_err());
72//! # Ok::<(), Box<dyn std::error::Error>>(())
73//! ```
74//!
75//! # Trust boundary
76//!
77//! HMAC authenticates the channel but does not encrypt it. The operating
78//! system's debug transport (environment variables, `adb`) that delivers the
79//! secret to the app is trusted.
80
81#![warn(missing_docs)]
82
83mod handshake;
84mod random;
85mod session;
86
87use std::time::Duration;
88
89pub use handshake::{ClientHandshake, ServerHandshake};
90pub use random::{generate_secret, random_bytes};
91pub use session::{FrameKind, Session};
92
93/// Version byte carried by the challenge and every envelope
94///
95/// Both peers must be built from the same protocol version; a mismatch
96/// fails the handshake with [`Error::UnsupportedVersion`] rather than
97/// falling back to an older scheme.
98pub const PROTOCOL_VERSION: u8 = 1;
99
100/// Largest complete envelope, header and tag included, in bytes
101///
102/// This bounds a single hot-reload patch. A patch that does not fit needs a
103/// Full Reload instead.
104pub const MAX_MESSAGE: usize = 256 * 1024 * 1024;
105
106/// Bytes an envelope adds around its payload
107///
108/// One version byte, one kind byte, an eight-byte sequence number, and a
109/// 32-byte HMAC-SHA256 tag.
110pub const ENVELOPE_OVERHEAD: usize = 1 + 1 + 8 + 32;
111
112/// Largest payload a single envelope carries, in bytes
113pub const MAX_PAYLOAD: usize = MAX_MESSAGE - ENVELOPE_OVERHEAD;
114
115/// Largest [`FrameKind::Text`] payload and patch metadata header, in bytes
116///
117/// Control messages, logs, traces, and the JSON jump table that prefixes a
118/// patch are all far smaller than this. Servers use it, plus
119/// [`ENVELOPE_OVERHEAD`], as their read limit because clients never send
120/// patches.
121pub const MAX_CONTROL: usize = 1024 * 1024;
122
123/// Largest handshake message, in bytes
124///
125/// Handshake messages are a few hundred bytes of JSON. Receivers check this
126/// before parsing; the dev runtime additionally caps how many bytes it reads
127/// at all until the handshake completes.
128pub const MAX_HANDSHAKE: usize = 4096;
129
130/// Time either peer allows for the complete handshake
131///
132/// A peer that has not authenticated within this window is disconnected,
133/// so a stalled connection cannot hold a session slot open.
134pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);
135
136/// Why a handshake or envelope was rejected
137///
138/// Every variant is terminal for the connection: the caller closes the
139/// socket and, for handshake failures, reports the message so a developer
140/// can tell a stale app or a version mismatch apart from a missing server.
141#[derive(Debug, thiserror::Error)]
142#[non_exhaustive]
143pub enum Error {
144 /// The operating system could not supply random bytes
145 #[error("operating-system randomness is unavailable: {0}")]
146 Random(#[from] std::io::Error),
147 /// No session secret was provisioned
148 #[error("no development session secret was provisioned")]
149 MissingSecret,
150 /// A handshake message exceeded [`MAX_HANDSHAKE`]
151 #[error("handshake message exceeds {MAX_HANDSHAKE} bytes")]
152 HandshakeTooLarge,
153 /// A handshake message was not valid for this protocol version
154 #[error(
155 "malformed handshake message ({0}); rebuild the app with the same Whisker version as the CLI"
156 )]
157 MalformedHandshake(#[source] serde_json::Error),
158 /// The peer announced a different [`PROTOCOL_VERSION`]
159 #[error(
160 "peer speaks development protocol version {0}, expected {PROTOCOL_VERSION}; rebuild the app with the same Whisker version as the CLI"
161 )]
162 UnsupportedVersion(u8),
163 /// The server could not prove it holds this app's session secret
164 #[error(
165 "the development server does not hold this app's session secret (the app was launched by a different `whisker run` session)"
166 )]
167 InvalidServerProof,
168 /// The client could not prove it holds this server's session secret
169 #[error(
170 "the app does not hold this session's secret (it was launched by a different `whisker run` session)"
171 )]
172 InvalidClientProof,
173 /// An envelope had an unknown version or kind, or was truncated
174 #[error("malformed development frame")]
175 InvalidFrame,
176 /// An envelope or its payload exceeded the size limits
177 #[error("development frame exceeds the size limit")]
178 FrameTooLarge,
179 /// An envelope did not carry the next expected sequence number
180 #[error("replayed or out-of-order development frame")]
181 OutOfSequence,
182 /// An envelope's tag did not verify
183 #[error("development frame failed authentication")]
184 InvalidMac,
185 /// A direction used every available sequence number
186 #[error("development frame sequence exhausted")]
187 SequenceExhausted,
188}