Skip to main content

syncspin_core/pairing/
token.rs

1//! The pairing token: the single string an operator carries from a client into a server.
2//!
3//! Sendspin's "Pairing Token" section defines a token as a fixed `SP:` prefix, one version
4//! character and a body:
5//!
6//! ```text
7//! token = "SP:" || version || body
8//! body  = base32(payload), padding stripped, every `2` transliterated to `9`
9//! ```
10//!
11//! The body is [RFC 4648 §6] base32 with the `=` padding stripped. Transliterating `2` to `9`
12//! keeps the whole token inside the QR code alphanumeric set (`0`-`9`, `A`-`Z`, `:`), so a token
13//! survives a QR scan and a manual copy identically. Decoding reverses the transform and is
14//! lenient about how the operator supplied the string - surrounding whitespace, case and a
15//! missing `SP:` prefix - and strict about everything else.
16//!
17//! Two versions exist:
18//!
19//! - version `0` carries `client_key || pairing_psk`, 64 payload bytes: a raw Curve25519 public
20//!   key followed by the client's pairing PSK. [`encode_v0`] builds it.
21//! - version `1` carries the 24-byte dynamic pairing code of the `qr_code` emission format.
22//!   [`encode_v1`] builds it.
23//!
24//! A token is a credential: anyone holding it can pair a server with the client. Nothing here is
25//! behind a feature gate - a token is text, not a PAKE - and neither [`Debug`] output nor an
26//! error message ever contains payload bytes; both report lengths instead.
27//!
28//! The spec's reference vectors are asserted in `tests/pairing_token.rs`.
29//!
30//! [RFC 4648 §6]: https://www.rfc-editor.org/rfc/rfc4648#section-6
31
32use std::fmt;
33
34use anyhow::{anyhow, bail, Result};
35
36/// Version 0's payload length: a 32-byte public key and a 32-byte pairing PSK.
37const VERSION_0_PAYLOAD_LEN: usize = 64;
38
39/// Version 1's payload length: the dynamic pairing code of the `qr_code` emission format.
40pub const VERSION_1_PAYLOAD_LEN: usize = 24;
41
42/// The RFC 4648 base32 alphabet, upper case: `A`-`Z` then `2`-`7`.
43const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
44
45/// A decoded pairing token.
46///
47/// The payload is a credential; [`Debug`] prints its length, never its bytes.
48#[derive(Clone, PartialEq, Eq)]
49pub struct Token {
50    /// The version character the token carried, as a number.
51    pub version: u8,
52    /// The decoded payload, exactly as long as the version defines.
53    ///
54    /// Bytes beyond that length that the token carried are dropped here: the spec reserves them
55    /// for future extension and requires a decoder to ignore them.
56    pub payload: Vec<u8>,
57}
58
59impl fmt::Debug for Token {
60    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
61        // The payload is the pairing credential. A derived `Debug` would print it byte by byte
62        // into any log line that formats the token, so report only what is not secret.
63        formatter
64            .debug_struct("Token")
65            .field("version", &self.version)
66            .field("payload_len", &self.payload.len())
67            .finish()
68    }
69}
70
71/// Encodes a version-0 pairing token: `client_key || pairing_psk` as base32.
72///
73/// `client_key` is the raw 32-byte Curve25519 public key whose base64url form is the client's
74/// `client_id`; `psk` is the client's pairing PSK. The two must be the pair the client actually
75/// uses, because a server selects and verifies the client's Noise identity from them.
76///
77/// # Example
78///
79/// ```
80/// use syncspin_core::pairing::token::encode_v0;
81///
82/// // The spec's reference vector: client_key 0x00..=0x1f, pairing_psk 0xe0..=0xff.
83/// let client_key = std::array::from_fn(|index| index as u8);
84/// let psk = std::array::from_fn(|index| 0xe0 + index as u8);
85/// assert_eq!(
86///     encode_v0(&client_key, &psk),
87///     "SP:0AAAQEAYEAUDAOCAJBIFQYDIOB4IBCEQTCQKRMFYYDENBWHA5DYP6BYPC4PSOLZXH5DU6V97M5XXO74HR6LZ7J5PW674PT6X37T6757Y"
88/// );
89/// ```
90pub fn encode_v0(client_key: &[u8; 32], psk: &[u8; 32]) -> String {
91    let mut payload = Vec::with_capacity(VERSION_0_PAYLOAD_LEN);
92    payload.extend_from_slice(client_key);
93    payload.extend_from_slice(psk);
94    encode(0, &payload)
95}
96
97/// Encodes a version-1 pairing token: the 24-byte dynamic pairing code as base32.
98///
99/// `code` is the `qr_code` emission format of a dynamic pairing code, the first 24 bytes of the
100/// derivation digest. A display renders the returned string as a QR code; the server decodes it
101/// and takes the payload as the entered code.
102///
103/// # Example
104///
105/// ```
106/// use syncspin_core::pairing::token::encode_v1;
107///
108/// // The spec's reference vector: the code 0xe0..=0xf7.
109/// let code: [u8; 24] = std::array::from_fn(|index| 0xe0 + index as u8);
110/// assert_eq!(
111///     encode_v1(&code),
112///     "SP:14DQ6FY7E4XTOP9HJ5LV6Z3PO57YPD4XT6T97N5Y"
113/// );
114/// ```
115pub fn encode_v1(code: &[u8; VERSION_1_PAYLOAD_LEN]) -> String {
116    encode(1, code)
117}
118
119/// Decodes a pairing token, or reports why the input is not one.
120///
121/// Lenient about operator formatting: surrounding whitespace is trimmed, ASCII case is folded
122/// and the leading `SP:` is optional. Everything else follows the spec: the first remaining
123/// character is the version, it must be one this crate defines, and the payload must be at least
124/// as long as that version defines. Bytes past that length are reserved for future extension and
125/// are dropped, so [`Token::payload`] always has exactly the version's length. Errors name a rule
126/// or a length and never echo the input.
127///
128/// # Example
129///
130/// ```
131/// use syncspin_core::pairing::token::decode;
132///
133/// // The spec's version-1 vector for the code 0xe0..=0xf7.
134/// let token = decode("SP:14DQ6FY7E4XTOP9HJ5LV6Z3PO57YPD4XT6T97N5Y").expect("version 1");
135/// assert_eq!(token.version, 1);
136/// assert_eq!(token.payload, (0xe0..=0xf7).collect::<Vec<u8>>());
137/// ```
138pub fn decode(token: &str) -> Result<Token> {
139    let trimmed = token.trim();
140    if trimmed.is_empty() {
141        bail!("a pairing token is empty");
142    }
143
144    // Folding case first makes both the prefix and the body case-insensitive; the versions this
145    // crate defines are digits, so folding cannot change which version a token selects.
146    let mut input = trimmed.as_bytes().to_vec();
147    input.make_ascii_uppercase();
148    if input.starts_with(b"SP:") {
149        input.drain(..3);
150    }
151
152    let (version, required) = match input.first() {
153        Some(b'0') => (0, VERSION_0_PAYLOAD_LEN),
154        Some(b'1') => (1, VERSION_1_PAYLOAD_LEN),
155        // The character is free text from the operator and could be part of a pasted key, so the
156        // error does not repeat it.
157        Some(_) => bail!("unsupported pairing token version"),
158        None => bail!("a pairing token needs a version character"),
159    };
160
161    let mut payload = decode_body(&input[1..])?;
162    if payload.len() < required {
163        bail!(
164            "a version {version} pairing token needs {required} payload bytes, this one has {}",
165            payload.len()
166        );
167    }
168    // Bytes beyond the version's payload are reserved for future extension, and the spec says a
169    // decoder MUST ignore them: ignoring them here means no caller ever has to remember to.
170    payload.truncate(required);
171    Ok(Token { version, payload })
172}
173
174/// Encodes `payload` as a token of `version`, the inverse of [`decode`].
175fn encode(version: u8, payload: &[u8]) -> String {
176    let body = encode_body(payload);
177    let mut token = String::with_capacity(4 + body.len());
178    token.push_str("SP:");
179    token.push((b'0' + version) as char);
180    token.push_str(&body);
181    token
182}
183
184/// Encodes a payload as a token body: base32, padding stripped, every `2` transliterated to `9`.
185fn encode_body(payload: &[u8]) -> String {
186    let encoded = base32_encode(payload);
187    let unpadded = encoded.trim_end_matches('=');
188    // The transliteration keeps the body inside the QR code alphanumeric set; `2` and `9` are
189    // then the only characters that differ between a body and plain base32.
190    unpadded.replace('2', "9")
191}
192
193/// Decodes a token body: `9` back to `2`, re-padded to a multiple of eight, base32-decoded.
194fn decode_body(body: &[u8]) -> Result<Vec<u8>> {
195    let mut text = Vec::with_capacity(body.len() + 7);
196    for &byte in body {
197        match byte {
198            // The one transliteration of the format, applied before the alphabet check because
199            // `9` is not itself a base32 character.
200            b'9' => text.push(b'2'),
201            b'A'..=b'Z' | b'2'..=b'7' => text.push(byte),
202            // Padding, whitespace inside the body, and anything else are not part of a token.
203            _ => bail!("a pairing token body has a character outside the base32 alphabet"),
204        }
205    }
206    while text.len() % 8 != 0 {
207        text.push(b'=');
208    }
209    base32_decode(&text)
210}
211
212/// Encodes bytes as RFC 4648 §6 base32, upper case, padded with `=` to eight characters.
213fn base32_encode(bytes: &[u8]) -> String {
214    let mut text = String::with_capacity(base32_len(bytes.len()));
215    let mut buffer = 0u16;
216    let mut bits = 0u32;
217    for &byte in bytes {
218        buffer = (buffer << 8) | u16::from(byte);
219        bits += 8;
220        while bits >= 5 {
221            bits -= 5;
222            text.push(ALPHABET[((buffer >> bits) & 0x1f) as usize] as char);
223            // Drop the bits just consumed; `buffer` then holds only pending bits.
224            buffer &= (1 << bits) - 1;
225        }
226    }
227    if bits > 0 {
228        text.push(ALPHABET[((buffer << (5 - bits)) & 0x1f) as usize] as char);
229    }
230    while text.len() % 8 != 0 {
231        text.push('=');
232    }
233    text
234}
235
236/// Decodes RFC 4648 §6 base32, ignoring any trailing `=` padding.
237///
238/// Fails on a character outside the alphabet, on a length base32 cannot produce, and on non-zero
239/// padding bits. None of the three is written by a conformant encoder, and accepting any of them
240/// would turn a malformed string into a valid token.
241fn base32_decode(text: &[u8]) -> Result<Vec<u8>> {
242    let end = text
243        .iter()
244        .rposition(|&byte| byte != b'=')
245        .map_or(0, |index| index + 1);
246    let mut bytes = Vec::with_capacity(end * 5 / 8);
247    let mut buffer = 0u16;
248    let mut bits = 0u32;
249    for &byte in &text[..end] {
250        let value = base32_value(byte).ok_or_else(|| {
251            anyhow!("a pairing token body has a character outside the base32 alphabet")
252        })?;
253        buffer = (buffer << 5) | u16::from(value);
254        bits += 5;
255        if bits >= 8 {
256            bits -= 8;
257            bytes.push((buffer >> bits) as u8);
258            buffer &= (1 << bits) - 1;
259        }
260    }
261    // A final quantum of 1, 3 or 6 characters leaves a whole five-bit symbol that no byte uses;
262    // base32 only produces final quanta of 2, 4, 5, 7 or 8 characters. When those bits are zero
263    // the input would otherwise decode to a shorter payload and pass unnoticed.
264    if bits >= 5 {
265        bail!("a pairing token body has a length base32 cannot encode");
266    }
267    if buffer != 0 {
268        bail!("a pairing token body has non-zero padding bits");
269    }
270    Ok(bytes)
271}
272
273/// Maps one base32 character to its five-bit value.
274fn base32_value(byte: u8) -> Option<u8> {
275    match byte {
276        b'A'..=b'Z' => Some(byte - b'A'),
277        b'2'..=b'7' => Some(byte - b'2' + 26),
278        _ => None,
279    }
280}
281
282/// Returns how many characters base32 uses for `len` bytes, padding included.
283fn base32_len(len: usize) -> usize {
284    (len * 8).div_ceil(5).div_ceil(8) * 8
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    /// RFC 4648 §10's base32 examples, transcribed from the RFC.
292    const RFC_4648: &[(&[u8], &str)] = &[
293        (b"", ""),
294        (b"f", "MY======"),
295        (b"fo", "MZXQ===="),
296        (b"foo", "MZXW6==="),
297        (b"foob", "MZXW6YQ="),
298        (b"fooba", "MZXW6YTB"),
299        (b"foobar", "MZXW6YTBOI======"),
300    ];
301
302    /// The spec's version-1 vector for the code `0xe0..=0xf7`.
303    const VERSION_1: &str = "SP:14DQ6FY7E4XTOP9HJ5LV6Z3PO57YPD4XT6T97N5Y";
304
305    #[test]
306    fn base32_matches_the_rfc_vectors() {
307        for (bytes, base32) in RFC_4648 {
308            assert_eq!(&base32_encode(bytes), base32, "encoding {base32:?}");
309            assert_eq!(
310                base32_decode(base32.as_bytes()).expect("the RFC's own base32 decodes"),
311                *bytes,
312                "decoding {base32:?}"
313            );
314        }
315    }
316
317    #[test]
318    fn the_body_transliterates_two_to_nine() {
319        // 0xd0 is 11010 000 in five-bit groups: value 26 is the alphabet's character `2`, so the
320        // body carries `9A` and a decoder has to map the `9` back.
321        assert_eq!(encode_body(&[0xd0]), "9A");
322        assert!(!encode_body(&[0xd0]).contains('2'));
323        assert_eq!(
324            decode_body(b"9A").expect("a transliterated body decodes"),
325            [0xd0]
326        );
327    }
328
329    #[test]
330    fn bodies_round_trip_at_every_length() {
331        let payload: Vec<u8> = (0..=64).collect();
332        for len in 0..=payload.len() {
333            let body = encode_body(&payload[..len]);
334            assert!(
335                !body.contains('=') && !body.contains('2'),
336                "a body is unpadded base32 with `2` transliterated: {body}"
337            );
338            assert_eq!(
339                decode_body(body.as_bytes()).expect("a body we just encoded decodes"),
340                payload[..len],
341                "a {len}-byte payload survives the body transform"
342            );
343        }
344    }
345
346    #[test]
347    fn the_version_1_encoder_matches_the_spec() {
348        assert_eq!(encode(1, &(0xe0..=0xf7).collect::<Vec<u8>>()), VERSION_1);
349    }
350
351    #[test]
352    fn extension_bytes_beyond_the_version_are_dropped() {
353        // The spec reserves trailing payload bytes for future extension and requires a decoder to
354        // ignore them: the token still decodes, and its payload is exactly the version's length.
355        for (version, len) in [(0, VERSION_0_PAYLOAD_LEN), (1, VERSION_1_PAYLOAD_LEN)] {
356            let payload: Vec<u8> = (0..len as u8 + 3).collect();
357            let token = decode(&encode(version, &payload)).unwrap_or_else(|error| {
358                panic!("a longer version-{version} payload decodes: {error}")
359            });
360            assert_eq!(token.version, version);
361            assert_eq!(
362                token.payload,
363                payload[..len],
364                "version {version} drops the three extension bytes"
365            );
366        }
367    }
368
369    #[test]
370    fn a_body_of_a_length_base32_cannot_encode_is_rejected() {
371        // Appending one zero symbol to a 24-byte body gives 41 characters, whose five-bit groups
372        // leave one whole symbol over: 40 characters (25 bytes) is the nearest length base32 can
373        // write. All those bits are zero, so only the quantum check can catch it.
374        let body = format!("{VERSION_1}AA");
375        let message = decode(&body).expect_err("41 body characters are not a base32 length");
376        assert!(
377            message.to_string().contains("length"),
378            "the error names the length: {message}"
379        );
380    }
381
382    #[test]
383    fn an_invalid_character_is_reported_without_echoing_it() {
384        let message = decode_body(b"A!")
385            .expect_err("`!` is not base32")
386            .to_string();
387        assert!(!message.contains('!'), "the error must not echo: {message}");
388    }
389
390    #[test]
391    fn debug_reports_the_length_only() {
392        let token = Token {
393            version: 0,
394            payload: vec![0xe0; VERSION_0_PAYLOAD_LEN],
395        };
396        assert_eq!(
397            format!("{token:?}"),
398            "Token { version: 0, payload_len: 64 }",
399            "the payload bytes must not reach a log line"
400        );
401    }
402}