Skip to main content

agentmux_srv_core/backend/viewer/
signing.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A paired device's key, and the signature its send requests carry
5//! (agentmux-mobile's SPEC_SEND_FROM_THE_PHONE_2026_10_13 §4, §5.2.1).
6//!
7//! Sending makes the phone the operator for an agent, so the viewer token
8//! alone isn't enough: a request also carries a signature by a key made in
9//! the phone's hardware key store at pairing, which never leaves it. srv
10//! keeps the public half (`db_viewer_devices.device_key`) and checks:
11//!
12//! ```text
13//! amxv-sig-v1
14//! <METHOD>
15//! <path as sent, no query>
16//! <X-Amxv-Timestamp, unix ms>
17//! <lowercase hex SHA-256 of the body>
18//! ```
19//!
20//! joined by `\n`. The phone's key is ECDSA P-256 (the one curve Android's
21//! Keystore and iOS's Secure Enclave both hold in hardware), sent as the
22//! 65-byte uncompressed point, signing SHA-256 with a DER signature. A
23//! 32-byte key is Ed25519, the shape pairing accepted first; it verifies too.
24
25use base64::Engine as _;
26use sha2::{Digest, Sha256};
27
28/// The first line of the signed text; a new format gets a new tag.
29pub const SIG_VERSION: &str = "amxv-sig-v1";
30/// The header carrying the signing time, unix ms.
31pub const TIMESTAMP_HEADER: &str = "x-amxv-timestamp";
32/// The header carrying the signature, standard base64.
33pub const SIGNATURE_HEADER: &str = "x-amxv-signature";
34/// How far a request's timestamp may be from srv's clock, either way.
35pub const MAX_SKEW_MS: i64 = 60_000;
36
37/// A device's public key, parsed from its stored base64.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum DeviceKey {
40    /// The 65-byte uncompressed SEC1 point `0x04 ‖ X ‖ Y`.
41    P256(Vec<u8>),
42    Ed25519([u8; 32]),
43}
44
45impl DeviceKey {
46    /// Parse standard base64 of a 65-byte P-256 point or a 32-byte Ed25519
47    /// key.
48    pub fn parse(b64: &str) -> Result<Self, &'static str> {
49        const SHAPE: &str = "device_key must be standard base64 of a 65-byte P-256 point or a 32-byte Ed25519 key";
50        let bytes = base64::engine::general_purpose::STANDARD.decode(b64.trim()).map_err(|_| SHAPE)?;
51        match bytes.len() {
52            // ring checks the point is on the curve when it verifies: a
53            // device that paired with a bad point can never send.
54            65 if bytes[0] == 0x04 => Ok(Self::P256(bytes)),
55            32 => {
56                let key: [u8; 32] = bytes.try_into().map_err(|_| SHAPE)?;
57                ed25519_dalek::VerifyingKey::from_bytes(&key).map_err(|_| "device_key is not an Ed25519 key")?;
58                Ok(Self::Ed25519(key))
59            }
60            _ => Err(SHAPE),
61        }
62    }
63
64    /// Whether `signature` (standard base64) signs `message` with this key.
65    pub fn verifies(&self, message: &[u8], signature_b64: &str) -> bool {
66        let Ok(sig) = base64::engine::general_purpose::STANDARD.decode(signature_b64.trim()) else {
67            return false;
68        };
69        match self {
70            Self::P256(point) => ring::signature::UnparsedPublicKey::new(&ring::signature::ECDSA_P256_SHA256_ASN1, point)
71                .verify(message, &sig)
72                .is_ok(),
73            Self::Ed25519(key) => {
74                let Ok(key) = ed25519_dalek::VerifyingKey::from_bytes(key) else {
75                    return false;
76                };
77                let Ok(sig) = ed25519_dalek::Signature::from_slice(&sig) else {
78                    return false;
79                };
80                key.verify_strict(message, &sig).is_ok()
81            }
82        }
83    }
84}
85
86/// The text a request's signature covers.
87pub fn signed_text(method: &str, path: &str, timestamp_ms: i64, body: &[u8]) -> String {
88    let body_hash = hex::encode(Sha256::digest(body));
89    format!("{SIG_VERSION}\n{method}\n{path}\n{timestamp_ms}\n{body_hash}")
90}
91
92/// Whether a request signed at `timestamp_ms` is fresh at `now_ms`.
93pub fn fresh(timestamp_ms: i64, now_ms: i64) -> bool {
94    (now_ms - timestamp_ms).abs() <= MAX_SKEW_MS
95}
96
97/// The first line of the text a computer signs to open a feed
98/// (docs/specs/SPEC_REMOTE_PANES_WATCH_AND_DRIVE_AN_AGENT_ON_ANOTHER_COMPUTER_2026_11_20.md §3):
99///
100/// ```text
101/// amxv-sig-v2
102/// <METHOD>
103/// <path as sent, no query>
104/// <X-Amxv-Timestamp, unix ms>
105/// <X-Amxv-Nonce>
106/// <this computer's viewer certificate fingerprint, as the pairing link carries it>
107/// ```
108///
109/// The fingerprint binds the signature to the host it was made for; the nonce, remembered for
110/// [`NONCE_MEMORY_MS`], makes it good for one open.
111pub const OPEN_SIG_VERSION: &str = "amxv-sig-v2";
112/// The header carrying the nonce of a signed open.
113pub const NONCE_HEADER: &str = "x-amxv-nonce";
114/// How long a nonce is remembered: longer than a timestamp stays fresh either way, so a replay is either stale or
115/// remembered.
116pub const NONCE_MEMORY_MS: i64 = 3 * 60_000;
117/// The most nonces remembered at once. Past it an open is refused rather than a nonce forgotten.
118pub const MAX_NONCES: usize = 8192;
119
120/// The text a computer's feed open signs.
121pub fn open_signed_text(method: &str, path: &str, timestamp_ms: i64, nonce: &str, host_fingerprint: &str) -> String {
122    format!("{OPEN_SIG_VERSION}\n{method}\n{path}\n{timestamp_ms}\n{nonce}\n{host_fingerprint}")
123}
124
125/// Whether `nonce` has the shape a nonce must: 16 to 128 characters of letters, digits, `-` and `_`.
126pub fn nonce_shape_ok(nonce: &str) -> bool {
127    (16..=128).contains(&nonce.len()) && nonce.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
128}
129
130/// The nonces of signed opens seen lately, per device.
131#[derive(Debug, Default)]
132pub struct NonceLog {
133    /// `device\nnonce` → when it may be forgotten (unix ms).
134    seen: std::collections::HashMap<String, i64>,
135}
136
137impl NonceLog {
138    /// Records `nonce` for `device` at `now_ms`: true the first time, false for a nonce seen within
139    /// [`NONCE_MEMORY_MS`], and false when [`MAX_NONCES`] are remembered.
140    pub fn first_use(&mut self, device: &str, nonce: &str, now_ms: i64) -> bool {
141        self.seen.retain(|_, forget_at| *forget_at > now_ms);
142        let key = format!("{device}\n{nonce}");
143        if self.seen.contains_key(&key) || self.seen.len() >= MAX_NONCES {
144            return false;
145        }
146        self.seen.insert(key, now_ms + NONCE_MEMORY_MS);
147        true
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use ring::rand::SystemRandom;
155    use ring::signature::{EcdsaKeyPair, KeyPair, ECDSA_P256_SHA256_ASN1_SIGNING};
156
157    fn b64(bytes: &[u8]) -> String {
158        base64::engine::general_purpose::STANDARD.encode(bytes)
159    }
160
161    fn p256() -> EcdsaKeyPair {
162        let rng = SystemRandom::new();
163        let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &rng).unwrap();
164        EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8.as_ref(), &rng).unwrap()
165    }
166
167    #[test]
168    fn a_p256_signature_over_the_signed_text_verifies() {
169        let pair = p256();
170        let key = DeviceKey::parse(&b64(pair.public_key().as_ref())).unwrap();
171        assert!(matches!(key, DeviceKey::P256(_)));
172        let text = signed_text("POST", "/agentmux/viewer/agents/Clamk/input", 1_791_963_024_123, br#"{"message":"hi"}"#);
173        let sig = pair.sign(&SystemRandom::new(), text.as_bytes()).unwrap();
174        assert!(key.verifies(text.as_bytes(), &b64(sig.as_ref())));
175        // Any change to what was signed fails.
176        let other = signed_text("POST", "/agentmux/viewer/agents/Clamk/input", 1_791_963_024_123, br#"{"message":"rm"}"#);
177        assert!(!key.verifies(other.as_bytes(), &b64(sig.as_ref())));
178        // Another device's key fails.
179        let stranger = DeviceKey::parse(&b64(p256().public_key().as_ref())).unwrap();
180        assert!(!stranger.verifies(text.as_bytes(), &b64(sig.as_ref())));
181        assert!(!key.verifies(text.as_bytes(), "not base64!"));
182    }
183
184    /// A nonce as a computer makes one: random, never a value written in the code.
185    fn random_nonce() -> String {
186        uuid::Uuid::new_v4().simple().to_string()
187    }
188
189    #[test]
190    fn a_nonce_opens_once_per_device_until_it_is_forgotten() {
191        let mut log = NonceLog::default();
192        let nonce = random_nonce();
193        assert!(log.first_use("d1", &nonce, 1_000));
194        assert!(!log.first_use("d1", &nonce, 2_000), "a replay");
195        assert!(log.first_use("d2", &nonce, 2_000), "another device's nonce is its own");
196        assert!(log.first_use("d1", &nonce, 1_000 + NONCE_MEMORY_MS + 1), "forgotten once stale anyway");
197        let (short, spaced) = (nonce[..8].to_string(), format!("{} {}", &nonce[..10], &nonce[10..]));
198        assert!(nonce_shape_ok(&nonce) && !nonce_shape_ok(&short) && !nonce_shape_ok(&spaced));
199    }
200
201    #[test]
202    fn a_full_nonce_log_refuses_instead_of_forgetting() {
203        let mut log = NonceLog::default();
204        for _ in 0..MAX_NONCES {
205            assert!(log.first_use("d", &random_nonce(), 1));
206        }
207        assert!(!log.first_use("d", &random_nonce(), 2));
208    }
209
210    #[test]
211    fn an_open_signature_is_bound_to_the_host_and_the_nonce() {
212        let pair = p256();
213        let key = DeviceKey::parse(&b64(pair.public_key().as_ref())).unwrap();
214        let nonce = random_nonce();
215        let text = open_signed_text("GET", "/agentmux/viewer/agents/a/feed", 5, &nonce, "aa11");
216        let sig = b64(pair.sign(&SystemRandom::new(), text.as_bytes()).unwrap().as_ref());
217        assert!(key.verifies(text.as_bytes(), &sig));
218        let other_host = open_signed_text("GET", "/agentmux/viewer/agents/a/feed", 5, &nonce, "bb22");
219        assert!(!key.verifies(other_host.as_bytes(), &sig));
220        let other_nonce = open_signed_text("GET", "/agentmux/viewer/agents/a/feed", 5, &random_nonce(), "aa11");
221        assert!(!key.verifies(other_nonce.as_bytes(), &sig));
222    }
223
224    #[test]
225    fn an_ed25519_signature_verifies() {
226        let signing = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]);
227        let key = DeviceKey::parse(&b64(signing.verifying_key().as_bytes())).unwrap();
228        let text = signed_text("POST", "/p", 1, b"{}");
229        use ed25519_dalek::Signer as _;
230        let sig = signing.sign(text.as_bytes());
231        assert!(key.verifies(text.as_bytes(), &b64(&sig.to_bytes())));
232        assert!(!key.verifies(b"other", &b64(&sig.to_bytes())));
233    }
234
235    #[test]
236    fn keys_of_the_wrong_shape_are_refused() {
237        assert!(DeviceKey::parse("").is_err());
238        assert!(DeviceKey::parse("%%%").is_err());
239        assert!(DeviceKey::parse(&b64(&[4u8; 64])).is_err(), "64 bytes is neither shape");
240        let mut compressed = vec![0x02];
241        compressed.extend([1u8; 32]);
242        assert!(DeviceKey::parse(&b64(&compressed)).is_err(), "compressed points are not accepted");
243        // A point off the curve parses, and never verifies.
244        let mut off = vec![0x04];
245        off.extend([1u8; 64]);
246        let off = DeviceKey::parse(&b64(&off)).unwrap();
247        let pair = p256();
248        let sig = pair.sign(&SystemRandom::new(), b"x").unwrap();
249        assert!(!off.verifies(b"x", &b64(sig.as_ref())));
250    }
251
252    #[test]
253    fn the_signed_text_is_five_lines_with_the_body_hash_last() {
254        let text = signed_text("POST", "/agentmux/viewer/agents/A%20B/input", 42, b"");
255        assert_eq!(
256            text,
257            "amxv-sig-v1\nPOST\n/agentmux/viewer/agents/A%20B/input\n42\n\
258             e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
259        );
260    }
261
262    #[test]
263    fn a_timestamp_is_fresh_within_a_minute_either_way() {
264        assert!(fresh(100_000, 160_000));
265        assert!(fresh(160_000, 100_000));
266        assert!(!fresh(100_000, 160_001));
267        assert!(!fresh(160_001, 100_000));
268    }
269}