second_brain_sync/pairing/
code.rs1use std::fmt;
2use std::sync::OnceLock;
3
4use anyhow::{Context, Result, bail};
5use rand_core::{OsRng, RngCore};
6use zeroize::Zeroizing;
7
8use super::PAIR_PORT;
9
10const WORD_LIST: &str = include_str!("words.txt");
12const WORD_COUNT: usize = 2048;
13pub const CODE_WORDS: usize = 4;
14const SECRET_LEN: usize = 16;
15const INVITE_PREFIX: &str = "sb-pair:";
16const PREFIX_LEN: usize = 4;
17
18fn words() -> &'static [&'static str] {
19 static WORDS: OnceLock<Vec<&'static str>> = OnceLock::new();
20 WORDS.get_or_init(|| WORD_LIST.lines().collect())
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum CodeKind {
26 Words,
27 Invite,
28}
29
30impl CodeKind {
31 pub(super) fn byte(self) -> u8 {
32 match self {
33 Self::Words => 1,
34 Self::Invite => 2,
35 }
36 }
37
38 pub(super) fn from_byte(byte: u8) -> Option<Self> {
39 match byte {
40 1 => Some(Self::Words),
41 2 => Some(Self::Invite),
42 _ => None,
43 }
44 }
45}
46
47pub struct HostSecrets {
50 words: Zeroizing<[u16; CODE_WORDS]>,
51 secret: Zeroizing<[u8; SECRET_LEN]>,
52}
53
54impl fmt::Debug for HostSecrets {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 f.write_str("HostSecrets(..)")
57 }
58}
59
60impl HostSecrets {
61 pub fn generate() -> Self {
62 let mut words = Zeroizing::new([0u16; CODE_WORDS]);
63 for word in words.iter_mut() {
64 *word = u16::try_from(OsRng.next_u32() % WORD_COUNT as u32).unwrap_or(0);
65 }
66 let mut secret = Zeroizing::new([0u8; SECRET_LEN]);
67 OsRng.fill_bytes(secret.as_mut());
68 Self { words, secret }
69 }
70
71 pub fn code(&self) -> Zeroizing<String> {
73 let list = words();
74 Zeroizing::new(
75 self.words
76 .iter()
77 .map(|&i| list[usize::from(i)])
78 .collect::<Vec<_>>()
79 .join("-"),
80 )
81 }
82
83 pub fn invite(&self, hosts: &[String], port: u16) -> Zeroizing<String> {
85 let secret: String = self.secret.iter().map(|b| format!("{b:02x}")).collect();
86 let secret = Zeroizing::new(secret);
87 Zeroizing::new(format!(
88 "{INVITE_PREFIX}{}@{}:{port}",
89 secret.as_str(),
90 hosts.join(",")
91 ))
92 }
93
94 pub(super) fn password(&self, kind: CodeKind) -> Zeroizing<Vec<u8>> {
95 match kind {
96 CodeKind::Words => words_password(&self.words),
97 CodeKind::Invite => secret_password(&self.secret),
98 }
99 }
100}
101
102fn words_password(indices: &[u16; CODE_WORDS]) -> Zeroizing<Vec<u8>> {
103 let mut out = Zeroizing::new(b"words:".to_vec());
104 for index in indices {
105 out.extend_from_slice(&index.to_be_bytes());
106 }
107 out
108}
109
110fn secret_password(secret: &[u8; SECRET_LEN]) -> Zeroizing<Vec<u8>> {
111 let mut out = Zeroizing::new(b"invite:".to_vec());
112 out.extend_from_slice(secret);
113 out
114}
115
116pub struct JoinCode {
118 kind: CodeKind,
119 password: Zeroizing<Vec<u8>>,
120 hosts: Vec<String>,
121 port: Option<u16>,
122}
123
124impl fmt::Debug for JoinCode {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126 f.debug_struct("JoinCode")
127 .field("kind", &self.kind)
128 .field("hosts", &self.hosts)
129 .field("port", &self.port)
130 .finish_non_exhaustive()
131 }
132}
133
134impl JoinCode {
135 pub fn parse(text: &str) -> Result<Self> {
138 let text = text.trim();
139 if let Some(rest) = text.strip_prefix(INVITE_PREFIX) {
140 return parse_invite(rest);
141 }
142 let tokens: Vec<String> = text
143 .split(|c: char| c == '-' || c.is_whitespace())
144 .filter(|t| !t.is_empty())
145 .map(str::to_ascii_lowercase)
146 .collect();
147 if tokens.len() != CODE_WORDS {
148 bail!(
149 "a pairing code is {CODE_WORDS} words, like the one `sb pair` shows on the other \
150 device"
151 );
152 }
153 let mut indices = Zeroizing::new([0u16; CODE_WORDS]);
154 for (slot, token) in indices.iter_mut().zip(&tokens) {
155 *slot = word_index(token)
156 .with_context(|| format!("{token:?} is not a word `sb pair` uses"))?;
157 }
158 let mut tokens = tokens;
159 tokens.iter_mut().for_each(|t| zeroize::Zeroize::zeroize(t));
160 Ok(Self {
161 kind: CodeKind::Words,
162 password: words_password(&indices),
163 hosts: Vec::new(),
164 port: None,
165 })
166 }
167
168 pub fn kind(&self) -> CodeKind {
169 self.kind
170 }
171
172 pub fn hosts(&self) -> &[String] {
174 &self.hosts
175 }
176
177 pub fn port(&self) -> Option<u16> {
178 self.port
179 }
180
181 pub fn addresses(&self, host: Option<&str>) -> Result<Vec<(String, u16)>> {
184 if let Some(host) = host {
185 return Ok(vec![pairing_address(host)?]);
186 }
187 let port = self.port.unwrap_or(PAIR_PORT);
188 Ok(self.hosts.iter().map(|h| (h.clone(), port)).collect())
189 }
190
191 pub(super) fn password(&self) -> &[u8] {
192 &self.password
193 }
194}
195
196fn word_index(token: &str) -> Option<u16> {
197 let list = words();
198 let position = match list.binary_search(&token) {
199 Ok(i) => i,
200 Err(_) if token.len() >= PREFIX_LEN => {
201 list.iter().position(|word| word.starts_with(token))?
202 }
203 Err(_) => return None,
204 };
205 u16::try_from(position).ok()
206}
207
208fn parse_invite(rest: &str) -> Result<JoinCode> {
209 let malformed = || {
210 anyhow::anyhow!(
211 "a pairing invite reads sb-pair:<secret>@<hosts>:<port>; this one is cut short"
212 )
213 };
214 let (secret, place) = rest.split_once('@').ok_or_else(malformed)?;
215 let (hosts, port) = place.rsplit_once(':').ok_or_else(malformed)?;
216 let port: u16 = port.parse().map_err(|_| malformed())?;
217 if secret.len() != SECRET_LEN * 2 {
218 return Err(malformed());
219 }
220 let mut bytes = Zeroizing::new([0u8; SECRET_LEN]);
221 for (byte, pair) in bytes.iter_mut().zip(secret.as_bytes().chunks_exact(2)) {
222 let digits = std::str::from_utf8(pair).map_err(|_| malformed())?;
223 *byte = u8::from_str_radix(digits, 16).map_err(|_| malformed())?;
224 }
225 let hosts: Vec<String> = hosts
226 .split(',')
227 .filter(|h| !h.is_empty())
228 .map(str::to_string)
229 .collect();
230 if hosts.is_empty() {
231 return Err(malformed());
232 }
233 Ok(JoinCode {
234 kind: CodeKind::Invite,
235 password: secret_password(&bytes),
236 hosts,
237 port: Some(port),
238 })
239}
240
241pub fn pairing_address(host: &str) -> Result<(String, u16)> {
244 let host = host.trim();
245 let host = host.rsplit_once('@').map_or(host, |(_, h)| h);
246 if let Some(rest) = host.strip_prefix('[') {
247 let (name, after) = rest
248 .split_once(']')
249 .with_context(|| format!("{host:?} opens a bracket it does not close"))?;
250 let port = match after.strip_prefix(':') {
251 Some(port) => port
252 .parse()
253 .with_context(|| format!("{port:?} is not a port"))?,
254 None if after.is_empty() => PAIR_PORT,
255 None => bail!("{host:?} has text after its closing bracket"),
256 };
257 return Ok((name.to_string(), port));
258 }
259 match host.split_once(':') {
260 Some((name, port)) if !port.contains(':') => Ok((
261 name.to_string(),
262 port.parse()
263 .with_context(|| format!("{port:?} is not a port"))?,
264 )),
265 Some(_) => Ok((host.to_string(), PAIR_PORT)),
266 None if host.is_empty() => bail!("--host needs a host name or address"),
267 None => Ok((host.to_string(), PAIR_PORT)),
268 }
269}
270
271#[cfg(test)]
272mod tests {
273 use super::*;
274
275 #[test]
276 fn the_word_list_has_2048_sorted_words_with_distinct_prefixes() {
277 let list = words();
278 assert_eq!(list.len(), WORD_COUNT);
279 assert!(
280 list.windows(2).all(|w| w[0] < w[1]),
281 "binary search needs order"
282 );
283 let prefixes: std::collections::BTreeSet<&str> =
284 list.iter().map(|w| &w[..w.len().min(PREFIX_LEN)]).collect();
285 assert_eq!(prefixes.len(), WORD_COUNT);
286 assert!(
287 list.iter()
288 .all(|w| w.bytes().all(|b| b.is_ascii_lowercase()))
289 );
290 }
291
292 #[test]
293 fn a_shown_code_parses_back_to_the_same_password_in_any_spelling() {
294 let host = HostSecrets::generate();
295 let code = host.code();
296 let words: Vec<&str> = code.split('-').collect();
297 assert_eq!(words.len(), CODE_WORDS);
298 let spellings = [
299 code.to_string(),
300 code.to_uppercase(),
301 words.join(" "),
302 words
303 .iter()
304 .map(|w| &w[..w.len().min(PREFIX_LEN)])
305 .collect::<Vec<_>>()
306 .join(" "),
307 ];
308 for spelling in spellings {
309 let parsed = JoinCode::parse(&spelling).unwrap();
310 assert_eq!(parsed.kind(), CodeKind::Words);
311 assert_eq!(parsed.password(), &host.password(CodeKind::Words)[..]);
312 }
313 }
314
315 #[test]
316 fn an_invite_parses_back_to_its_secret_hosts_and_port() {
317 let host = HostSecrets::generate();
318 let hosts = vec!["192.0.2.4".to_string(), "desk".to_string()];
319 let invite = host.invite(&hosts, 7301);
320 let parsed = JoinCode::parse(&invite).unwrap();
321 assert_eq!(parsed.kind(), CodeKind::Invite);
322 assert_eq!(parsed.hosts(), &hosts[..]);
323 assert_eq!(parsed.port(), Some(7301));
324 assert_eq!(parsed.password(), &host.password(CodeKind::Invite)[..]);
325 assert_ne!(
326 host.password(CodeKind::Invite),
327 host.password(CodeKind::Words)
328 );
329 }
330
331 #[test]
332 fn malformed_codes_are_refused() {
333 for bad in [
334 "",
335 "abandon ability able",
336 "abandon ability able about above",
337 "abandon ability able zzzz",
338 "aban-abil-able-ab",
339 "sb-pair:00@desk:1",
340 "sb-pair:00112233445566778899aabbccddeeff@:7201",
341 "sb-pair:00112233445566778899aabbccddeeff@desk",
342 "sb-pair:0011223344556677889gaabbccddeeff@desk:7201",
343 ] {
344 assert!(JoinCode::parse(bad).is_err(), "{bad:?} must be refused");
345 }
346 }
347
348 fn secrets(words: [u16; CODE_WORDS], secret: [u8; SECRET_LEN]) -> HostSecrets {
349 HostSecrets {
350 words: Zeroizing::new(words),
351 secret: Zeroizing::new(secret),
352 }
353 }
354
355 fn tokens(text: &str) -> std::collections::BTreeSet<String> {
356 text.split(|c: char| !c.is_ascii_alphanumeric())
357 .filter(|t| !t.is_empty())
358 .map(str::to_ascii_lowercase)
359 .collect()
360 }
361
362 fn debug_views(host: &HostSecrets) -> [String; 3] {
363 let invite = host.invite(&["desk".into()], 7201);
364 [
365 format!("{host:?}"),
366 format!("{:?}", JoinCode::parse(&host.code()).unwrap()),
367 format!("{:?}", JoinCode::parse(&invite).unwrap()),
368 ]
369 }
370
371 #[test]
372 fn secrets_never_appear_in_debug_output() {
373 let fixed = ["zebra", "orbit", "velvet", "lunar"];
374 let indices = fixed.map(|w| word_index(w).unwrap());
375 let secret: [u8; SECRET_LEN] = std::array::from_fn(|i| 0xa0 + i as u8);
376 let host = secrets(indices, secret);
377 let hex: String = secret.iter().map(|b| format!("{b:02x}")).collect();
378 let renderings = [
379 hex,
380 format!("{indices:?}"),
381 format!("{secret:?}"),
382 format!("{:?}", &host.password(CodeKind::Words)[..]),
383 format!("{:?}", &host.password(CodeKind::Invite)[..]),
384 ];
385 for shown in debug_views(&host) {
386 let shown_tokens = tokens(&shown);
387 for word in fixed {
388 assert!(!shown_tokens.contains(word), "{word} in {shown}");
389 }
390 for rendering in &renderings {
391 assert!(
392 !shown.contains(rendering.as_str()),
393 "{rendering} in {shown}"
394 );
395 }
396 }
397 }
398
399 #[test]
400 fn debug_output_is_the_same_for_every_word_and_secret() {
401 let baseline = debug_views(&secrets([0; CODE_WORDS], [0; SECRET_LEN]));
402 for (index, word) in words().iter().enumerate() {
403 let byte = u8::try_from(index % 256).unwrap();
404 let host = secrets(
405 [u16::try_from(index).unwrap(); CODE_WORDS],
406 [byte; SECRET_LEN],
407 );
408 assert_eq!(debug_views(&host), baseline, "{word}");
409 }
410 }
411
412 #[test]
413 fn a_host_names_its_pairing_port_or_takes_the_default() {
414 let cases = [
415 ("desk", ("desk", PAIR_PORT)),
416 ("user@desk", ("desk", PAIR_PORT)),
417 ("desk:7300", ("desk", 7300)),
418 ("192.0.2.2:7300", ("192.0.2.2", 7300)),
419 ("[fe80::1]", ("fe80::1", PAIR_PORT)),
420 ("[fe80::1]:7300", ("fe80::1", 7300)),
421 ("fe80::1", ("fe80::1", PAIR_PORT)),
422 ];
423 for (input, (host, port)) in cases {
424 assert_eq!(
425 pairing_address(input).unwrap(),
426 (host.to_string(), port),
427 "{input}"
428 );
429 }
430 assert!(pairing_address("desk:port").is_err());
431 assert!(pairing_address("").is_err());
432 }
433}