use std::fmt;
use anyhow::{anyhow, bail, Result};
const VERSION_0_PAYLOAD_LEN: usize = 64;
pub const VERSION_1_PAYLOAD_LEN: usize = 24;
const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
#[derive(Clone, PartialEq, Eq)]
pub struct Token {
pub version: u8,
pub payload: Vec<u8>,
}
impl fmt::Debug for Token {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Token")
.field("version", &self.version)
.field("payload_len", &self.payload.len())
.finish()
}
}
pub fn encode_v0(client_key: &[u8; 32], psk: &[u8; 32]) -> String {
let mut payload = Vec::with_capacity(VERSION_0_PAYLOAD_LEN);
payload.extend_from_slice(client_key);
payload.extend_from_slice(psk);
encode(0, &payload)
}
pub fn encode_v1(code: &[u8; VERSION_1_PAYLOAD_LEN]) -> String {
encode(1, code)
}
pub fn decode(token: &str) -> Result<Token> {
let trimmed = token.trim();
if trimmed.is_empty() {
bail!("a pairing token is empty");
}
let mut input = trimmed.as_bytes().to_vec();
input.make_ascii_uppercase();
if input.starts_with(b"SP:") {
input.drain(..3);
}
let (version, required) = match input.first() {
Some(b'0') => (0, VERSION_0_PAYLOAD_LEN),
Some(b'1') => (1, VERSION_1_PAYLOAD_LEN),
Some(_) => bail!("unsupported pairing token version"),
None => bail!("a pairing token needs a version character"),
};
let mut payload = decode_body(&input[1..])?;
if payload.len() < required {
bail!(
"a version {version} pairing token needs {required} payload bytes, this one has {}",
payload.len()
);
}
payload.truncate(required);
Ok(Token { version, payload })
}
fn encode(version: u8, payload: &[u8]) -> String {
let body = encode_body(payload);
let mut token = String::with_capacity(4 + body.len());
token.push_str("SP:");
token.push((b'0' + version) as char);
token.push_str(&body);
token
}
fn encode_body(payload: &[u8]) -> String {
let encoded = base32_encode(payload);
let unpadded = encoded.trim_end_matches('=');
unpadded.replace('2', "9")
}
fn decode_body(body: &[u8]) -> Result<Vec<u8>> {
let mut text = Vec::with_capacity(body.len() + 7);
for &byte in body {
match byte {
b'9' => text.push(b'2'),
b'A'..=b'Z' | b'2'..=b'7' => text.push(byte),
_ => bail!("a pairing token body has a character outside the base32 alphabet"),
}
}
while text.len() % 8 != 0 {
text.push(b'=');
}
base32_decode(&text)
}
fn base32_encode(bytes: &[u8]) -> String {
let mut text = String::with_capacity(base32_len(bytes.len()));
let mut buffer = 0u16;
let mut bits = 0u32;
for &byte in bytes {
buffer = (buffer << 8) | u16::from(byte);
bits += 8;
while bits >= 5 {
bits -= 5;
text.push(ALPHABET[((buffer >> bits) & 0x1f) as usize] as char);
buffer &= (1 << bits) - 1;
}
}
if bits > 0 {
text.push(ALPHABET[((buffer << (5 - bits)) & 0x1f) as usize] as char);
}
while text.len() % 8 != 0 {
text.push('=');
}
text
}
fn base32_decode(text: &[u8]) -> Result<Vec<u8>> {
let end = text
.iter()
.rposition(|&byte| byte != b'=')
.map_or(0, |index| index + 1);
let mut bytes = Vec::with_capacity(end * 5 / 8);
let mut buffer = 0u16;
let mut bits = 0u32;
for &byte in &text[..end] {
let value = base32_value(byte).ok_or_else(|| {
anyhow!("a pairing token body has a character outside the base32 alphabet")
})?;
buffer = (buffer << 5) | u16::from(value);
bits += 5;
if bits >= 8 {
bits -= 8;
bytes.push((buffer >> bits) as u8);
buffer &= (1 << bits) - 1;
}
}
if bits >= 5 {
bail!("a pairing token body has a length base32 cannot encode");
}
if buffer != 0 {
bail!("a pairing token body has non-zero padding bits");
}
Ok(bytes)
}
fn base32_value(byte: u8) -> Option<u8> {
match byte {
b'A'..=b'Z' => Some(byte - b'A'),
b'2'..=b'7' => Some(byte - b'2' + 26),
_ => None,
}
}
fn base32_len(len: usize) -> usize {
(len * 8).div_ceil(5).div_ceil(8) * 8
}
#[cfg(test)]
mod tests {
use super::*;
const RFC_4648: &[(&[u8], &str)] = &[
(b"", ""),
(b"f", "MY======"),
(b"fo", "MZXQ===="),
(b"foo", "MZXW6==="),
(b"foob", "MZXW6YQ="),
(b"fooba", "MZXW6YTB"),
(b"foobar", "MZXW6YTBOI======"),
];
const VERSION_1: &str = "SP:14DQ6FY7E4XTOP9HJ5LV6Z3PO57YPD4XT6T97N5Y";
#[test]
fn base32_matches_the_rfc_vectors() {
for (bytes, base32) in RFC_4648 {
assert_eq!(&base32_encode(bytes), base32, "encoding {base32:?}");
assert_eq!(
base32_decode(base32.as_bytes()).expect("the RFC's own base32 decodes"),
*bytes,
"decoding {base32:?}"
);
}
}
#[test]
fn the_body_transliterates_two_to_nine() {
assert_eq!(encode_body(&[0xd0]), "9A");
assert!(!encode_body(&[0xd0]).contains('2'));
assert_eq!(
decode_body(b"9A").expect("a transliterated body decodes"),
[0xd0]
);
}
#[test]
fn bodies_round_trip_at_every_length() {
let payload: Vec<u8> = (0..=64).collect();
for len in 0..=payload.len() {
let body = encode_body(&payload[..len]);
assert!(
!body.contains('=') && !body.contains('2'),
"a body is unpadded base32 with `2` transliterated: {body}"
);
assert_eq!(
decode_body(body.as_bytes()).expect("a body we just encoded decodes"),
payload[..len],
"a {len}-byte payload survives the body transform"
);
}
}
#[test]
fn the_version_1_encoder_matches_the_spec() {
assert_eq!(encode(1, &(0xe0..=0xf7).collect::<Vec<u8>>()), VERSION_1);
}
#[test]
fn extension_bytes_beyond_the_version_are_dropped() {
for (version, len) in [(0, VERSION_0_PAYLOAD_LEN), (1, VERSION_1_PAYLOAD_LEN)] {
let payload: Vec<u8> = (0..len as u8 + 3).collect();
let token = decode(&encode(version, &payload)).unwrap_or_else(|error| {
panic!("a longer version-{version} payload decodes: {error}")
});
assert_eq!(token.version, version);
assert_eq!(
token.payload,
payload[..len],
"version {version} drops the three extension bytes"
);
}
}
#[test]
fn a_body_of_a_length_base32_cannot_encode_is_rejected() {
let body = format!("{VERSION_1}AA");
let message = decode(&body).expect_err("41 body characters are not a base32 length");
assert!(
message.to_string().contains("length"),
"the error names the length: {message}"
);
}
#[test]
fn an_invalid_character_is_reported_without_echoing_it() {
let message = decode_body(b"A!")
.expect_err("`!` is not base32")
.to_string();
assert!(!message.contains('!'), "the error must not echo: {message}");
}
#[test]
fn debug_reports_the_length_only() {
let token = Token {
version: 0,
payload: vec![0xe0; VERSION_0_PAYLOAD_LEN],
};
assert_eq!(
format!("{token:?}"),
"Token { version: 0, payload_len: 64 }",
"the payload bytes must not reach a log line"
);
}
}