Skip to main content

agentmux_srv_core/backend/viewer/
pairing.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pairing codes and viewer tokens (agentmux-mobile's
5//! SPEC_AGENT_STATUS_AND_LIVE_PANE_FEED_2026_10_07 ยง13.2).
6//!
7//! A code is shown in the desktop's QR, so whoever redeems it has seen this
8//! screen. It is 10 characters of base32, works once, for 120 s, and only the
9//! newest one shown works: showing a new QR cancels the last. Guessing is
10//! bounded twice over: an address with five wrong codes in the last minute is
11//! refused with 429 before its next code is even compared, and ten wrong codes
12//! in a row, from anywhere, cancel every outstanding code.
13
14use std::collections::{HashMap, VecDeque};
15use std::net::IpAddr;
16use std::time::{Duration, Instant};
17
18use agentmux_common::secret_eq::secret_eq;
19use base64::Engine as _;
20use sha2::{Digest, Sha256};
21
22pub const CODE_LEN: usize = 10;
23pub const CODE_TTL: Duration = Duration::from_secs(120);
24/// Wrong codes one address may send per [`WRONG_WINDOW`]; the next attempt
25/// gets 429.
26pub const WRONG_PER_ADDRESS: usize = 5;
27pub const WRONG_WINDOW: Duration = Duration::from_secs(60);
28/// Wrong codes in a row, from any address, that cancel every outstanding code.
29pub const WRONG_IN_A_ROW: u32 = 10;
30pub const TOKEN_PREFIX: &str = "amxv_";
31
32const BASE32: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
33
34/// `n` bytes from the operating system's CSPRNG (ring's, through rustls).
35pub fn random_bytes<const N: usize>() -> [u8; N] {
36    let mut buf = [0u8; N];
37    rustls::crypto::ring::default_provider()
38        .secure_random
39        .fill(&mut buf)
40        .expect("the system random source failed");
41    buf
42}
43
44/// A fresh pairing code. 32 divides 256, so `byte % 32` is uniform.
45pub fn new_code() -> String {
46    random_bytes::<CODE_LEN>().iter().map(|b| BASE32[(b % 32) as usize] as char).collect()
47}
48
49/// A fresh viewer token: `amxv_` + base64url (no padding) of 32 random bytes.
50pub fn new_token() -> String {
51    let token = format!(
52        "{TOKEN_PREFIX}{}",
53        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(random_bytes::<32>())
54    );
55    // A device's token is never written into a transcript, nor shown on a paired device's feed, until the device is
56    // unpaired (`withhold_owner`).
57    crate::backend::transcript::withhold::hold(&withhold_owner(&token_hash(&token)), &token, None);
58    token
59}
60
61/// What a token is stored as: lowercase hex SHA-256.
62pub fn token_hash(token: &str) -> String {
63    hex::encode(Sha256::digest(token.as_bytes()))
64}
65
66/// Who holds a device's token, named by its stored hash, in the transcript withhold registry.
67pub fn withhold_owner(token_hash: &str) -> String {
68    format!("viewer-token:{token_hash}")
69}
70
71/// The outcome of presenting a code.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Redeem {
74    Accepted,
75    /// Unknown, expired, already used or cancelled: 401.
76    Refused,
77    /// Too many wrong codes from this address: 429.
78    RateLimited,
79}
80
81#[derive(Default)]
82struct Inner {
83    /// Outstanding codes and when each stops working. At most one in practice.
84    codes: Vec<(String, Instant)>,
85    wrong_by_address: HashMap<Option<IpAddr>, VecDeque<Instant>>,
86    wrong_in_a_row: u32,
87}
88
89#[derive(Default)]
90pub struct Pairing {
91    inner: parking_lot::Mutex<Inner>,
92}
93
94impl Pairing {
95    pub fn new() -> Self {
96        Self::default()
97    }
98
99    /// Show a new code: cancels any earlier one. Returns it and how long it
100    /// works.
101    pub fn start(&self) -> (String, Duration) {
102        self.start_at(Instant::now())
103    }
104
105    pub(crate) fn start_at(&self, now: Instant) -> (String, Duration) {
106        let code = new_code();
107        let mut inner = self.inner.lock();
108        inner.codes = vec![(code.clone(), now + CODE_TTL)];
109        (code, CODE_TTL)
110    }
111
112    /// Whether a code is shown now (the person started pairing and it hasn't expired or been used).
113    pub fn showing(&self) -> bool {
114        let now = Instant::now();
115        self.inner.lock().codes.iter().any(|(_, until)| *until > now)
116    }
117
118    /// Present `code` from `from` (`None` when the source is unknown, which
119    /// counts as one address).
120    pub fn redeem(&self, code: &str, from: Option<IpAddr>) -> Redeem {
121        self.redeem_at(code, from, Instant::now())
122    }
123
124    pub(crate) fn redeem_at(&self, code: &str, from: Option<IpAddr>, now: Instant) -> Redeem {
125        let mut inner = self.inner.lock();
126        inner.codes.retain(|(_, until)| *until > now);
127        let recent = inner.wrong_by_address.entry(from).or_default();
128        while recent.front().is_some_and(|at| now.duration_since(*at) >= WRONG_WINDOW) {
129            recent.pop_front();
130        }
131        if recent.len() >= WRONG_PER_ADDRESS {
132            return Redeem::RateLimited;
133        }
134        let presented = code.trim().to_ascii_uppercase();
135        // Every outstanding code is compared, in constant time, whatever matched.
136        let mut matched = None;
137        for (i, (c, _)) in inner.codes.iter().enumerate() {
138            if secret_eq(c.as_bytes(), presented.as_bytes()) {
139                matched = Some(i);
140            }
141        }
142        match matched {
143            Some(i) => {
144                inner.codes.remove(i);
145                inner.wrong_in_a_row = 0;
146                Redeem::Accepted
147            }
148            None => {
149                inner.wrong_by_address.entry(from).or_default().push_back(now);
150                inner.wrong_in_a_row += 1;
151                if inner.wrong_in_a_row >= WRONG_IN_A_ROW {
152                    tracing::warn!(attempts = inner.wrong_in_a_row, "too many wrong pairing codes; cancelling the outstanding code");
153                    inner.codes.clear();
154                    inner.wrong_in_a_row = 0;
155                }
156                // Forget addresses with nothing recent, so the map stays small.
157                inner.wrong_by_address.retain(|_, v| v.back().is_some_and(|at| now.duration_since(*at) < WRONG_WINDOW));
158                Redeem::Refused
159            }
160        }
161    }
162
163    #[cfg(test)]
164    pub(crate) fn outstanding(&self) -> usize {
165        self.inner.lock().codes.len()
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    fn addr(last: u8) -> Option<IpAddr> {
174        Some(IpAddr::from([198, 51, 100, last]))
175    }
176
177    #[test]
178    fn a_code_is_ten_base32_characters() {
179        for _ in 0..50 {
180            let code = new_code();
181            assert_eq!(code.len(), CODE_LEN);
182            assert!(code.bytes().all(|b| BASE32.contains(&b)), "{code}");
183        }
184        assert_ne!(new_code(), new_code());
185    }
186
187    #[test]
188    fn a_token_has_the_prefix_and_43_base64url_characters() {
189        let t = new_token();
190        let body = t.strip_prefix(TOKEN_PREFIX).unwrap();
191        assert_eq!(body.len(), 43, "32 bytes, unpadded");
192        assert!(body.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'));
193        assert_eq!(base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(body).unwrap().len(), 32);
194        assert_eq!(token_hash(&t).len(), 64);
195        assert_ne!(token_hash(&t), token_hash(&new_token()));
196    }
197
198    #[test]
199    fn a_code_works_once() {
200        let p = Pairing::new();
201        let (code, ttl) = p.start();
202        assert_eq!(ttl, CODE_TTL);
203        assert_eq!(p.redeem(&code, addr(1)), Redeem::Accepted);
204        assert_eq!(p.redeem(&code, addr(1)), Redeem::Refused, "single use");
205    }
206
207    #[test]
208    fn a_code_is_case_and_whitespace_tolerant() {
209        let p = Pairing::new();
210        let (code, _) = p.start();
211        assert_eq!(p.redeem(&format!(" {} ", code.to_lowercase()), addr(1)), Redeem::Accepted);
212    }
213
214    #[test]
215    fn a_code_expires_after_120_seconds() {
216        let p = Pairing::new();
217        let t0 = Instant::now();
218        let (code, _) = p.start_at(t0);
219        assert_eq!(p.redeem_at(&code, addr(1), t0 + CODE_TTL), Redeem::Refused);
220        let (code, _) = p.start_at(t0);
221        assert_eq!(p.redeem_at(&code, addr(1), t0 + CODE_TTL - Duration::from_secs(1)), Redeem::Accepted);
222    }
223
224    #[test]
225    fn a_new_code_cancels_the_last() {
226        let p = Pairing::new();
227        let (old, _) = p.start();
228        let (new, _) = p.start();
229        assert_eq!(p.redeem(&old, addr(1)), Redeem::Refused);
230        assert_eq!(p.redeem(&new, addr(1)), Redeem::Accepted);
231    }
232
233    #[test]
234    fn five_wrong_codes_in_a_minute_give_429_to_that_address_only() {
235        let p = Pairing::new();
236        let t0 = Instant::now();
237        let (code, _) = p.start_at(t0);
238        for i in 0..WRONG_PER_ADDRESS {
239            assert_eq!(p.redeem_at("AAAAAAAAAA", addr(1), t0 + Duration::from_secs(i as u64)), Redeem::Refused);
240        }
241        let t = t0 + Duration::from_secs(10);
242        assert_eq!(p.redeem_at(&code, addr(1), t), Redeem::RateLimited, "even the right code");
243        assert_eq!(p.redeem_at(&code, addr(2), t), Redeem::Accepted, "another address is not limited");
244
245        // A minute after the first wrong code the address may try again.
246        let (code, _) = p.start_at(t);
247        let later = t0 + WRONG_WINDOW + Duration::from_secs(5);
248        assert_eq!(p.redeem_at(&code, addr(1), later), Redeem::Accepted);
249    }
250
251    #[test]
252    fn ten_wrong_codes_in_a_row_cancel_the_outstanding_code() {
253        let p = Pairing::new();
254        let t0 = Instant::now();
255        let (code, _) = p.start_at(t0);
256        // From several addresses, so no single one is rate limited.
257        for i in 0..WRONG_IN_A_ROW {
258            let from = addr((i / 2) as u8);
259            assert_eq!(p.redeem_at("BBBBBBBBBB", from, t0), Redeem::Refused);
260        }
261        assert_eq!(p.outstanding(), 0);
262        assert_eq!(p.redeem_at(&code, addr(200), t0), Redeem::Refused, "cancelled");
263    }
264
265    #[test]
266    fn a_right_code_resets_the_run_of_wrong_ones() {
267        let p = Pairing::new();
268        let t0 = Instant::now();
269        for i in 0..(WRONG_IN_A_ROW - 1) {
270            p.redeem_at("CCCCCCCCCC", addr(i as u8), t0);
271        }
272        let (code, _) = p.start_at(t0);
273        assert_eq!(p.redeem_at(&code, addr(100), t0), Redeem::Accepted);
274        let (code, _) = p.start_at(t0);
275        p.redeem_at("CCCCCCCCCC", addr(101), t0);
276        assert_eq!(p.outstanding(), 1, "the run started over");
277        assert_eq!(p.redeem_at(&code, addr(102), t0), Redeem::Accepted);
278    }
279
280    #[test]
281    fn a_code_is_showing_from_its_start_until_it_is_used() {
282        let p = Pairing::new();
283        assert!(!p.showing());
284        let (code, _) = p.start();
285        assert!(p.showing());
286        assert_eq!(p.redeem(&code, addr(1)), Redeem::Accepted);
287        assert!(!p.showing());
288    }
289}