second-brain-sync 0.13.4

Bidirectional sync for second-brain: SSH transport, JSONL change log, conflict resolution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use std::fmt;
use std::sync::OnceLock;

use anyhow::{Context, Result, bail};
use rand_core::{OsRng, RngCore};
use zeroize::Zeroizing;

use super::PAIR_PORT;

/// The BIP-39 English list: 2048 words whose first four letters differ.
const WORD_LIST: &str = include_str!("words.txt");
const WORD_COUNT: usize = 2048;
pub const CODE_WORDS: usize = 4;
const SECRET_LEN: usize = 16;
const INVITE_PREFIX: &str = "sb-pair:";
const PREFIX_LEN: usize = 4;

fn words() -> &'static [&'static str] {
    static WORDS: OnceLock<Vec<&'static str>> = OnceLock::new();
    WORDS.get_or_init(|| WORD_LIST.lines().collect())
}

/// Which secret a joiner runs SPAKE2 over, sent in its first frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodeKind {
    Words,
    Invite,
}

impl CodeKind {
    pub(super) fn byte(self) -> u8 {
        match self {
            Self::Words => 1,
            Self::Invite => 2,
        }
    }

    pub(super) fn from_byte(byte: u8) -> Option<Self> {
        match byte {
            1 => Some(Self::Words),
            2 => Some(Self::Invite),
            _ => None,
        }
    }
}

/// What a pairing listener accepts: a four-word code to type and a 128-bit
/// secret for the QR invite. Both are retired together.
pub struct HostSecrets {
    words: Zeroizing<[u16; CODE_WORDS]>,
    secret: Zeroizing<[u8; SECRET_LEN]>,
}

impl fmt::Debug for HostSecrets {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("HostSecrets(..)")
    }
}

impl HostSecrets {
    pub fn generate() -> Self {
        let mut words = Zeroizing::new([0u16; CODE_WORDS]);
        for word in words.iter_mut() {
            *word = u16::try_from(OsRng.next_u32() % WORD_COUNT as u32).unwrap_or(0);
        }
        let mut secret = Zeroizing::new([0u8; SECRET_LEN]);
        OsRng.fill_bytes(secret.as_mut());
        Self { words, secret }
    }

    /// The code to type, words joined by `-`.
    pub fn code(&self) -> Zeroizing<String> {
        let list = words();
        Zeroizing::new(
            self.words
                .iter()
                .map(|&i| list[usize::from(i)])
                .collect::<Vec<_>>()
                .join("-"),
        )
    }

    /// The QR text: the secret, then where to dial.
    pub fn invite(&self, hosts: &[String], port: u16) -> Zeroizing<String> {
        let secret: String = self.secret.iter().map(|b| format!("{b:02x}")).collect();
        let secret = Zeroizing::new(secret);
        Zeroizing::new(format!(
            "{INVITE_PREFIX}{}@{}:{port}",
            secret.as_str(),
            hosts.join(",")
        ))
    }

    pub(super) fn password(&self, kind: CodeKind) -> Zeroizing<Vec<u8>> {
        match kind {
            CodeKind::Words => words_password(&self.words),
            CodeKind::Invite => secret_password(&self.secret),
        }
    }
}

fn words_password(indices: &[u16; CODE_WORDS]) -> Zeroizing<Vec<u8>> {
    let mut out = Zeroizing::new(b"words:".to_vec());
    for index in indices {
        out.extend_from_slice(&index.to_be_bytes());
    }
    out
}

fn secret_password(secret: &[u8; SECRET_LEN]) -> Zeroizing<Vec<u8>> {
    let mut out = Zeroizing::new(b"invite:".to_vec());
    out.extend_from_slice(secret);
    out
}

/// A code typed or scanned on the joining device.
pub struct JoinCode {
    kind: CodeKind,
    password: Zeroizing<Vec<u8>>,
    hosts: Vec<String>,
    port: Option<u16>,
}

impl fmt::Debug for JoinCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("JoinCode")
            .field("kind", &self.kind)
            .field("hosts", &self.hosts)
            .field("port", &self.port)
            .finish_non_exhaustive()
    }
}

impl JoinCode {
    /// Takes four words (separated by `-` or spaces, any case, each word or
    /// its first four letters) or a QR invite.
    pub fn parse(text: &str) -> Result<Self> {
        let text = text.trim();
        if let Some(rest) = text.strip_prefix(INVITE_PREFIX) {
            return parse_invite(rest);
        }
        let tokens: Vec<String> = text
            .split(|c: char| c == '-' || c.is_whitespace())
            .filter(|t| !t.is_empty())
            .map(str::to_ascii_lowercase)
            .collect();
        if tokens.len() != CODE_WORDS {
            bail!(
                "a pairing code is {CODE_WORDS} words, like the one `sb pair` shows on the other \
                 device"
            );
        }
        let mut indices = Zeroizing::new([0u16; CODE_WORDS]);
        for (slot, token) in indices.iter_mut().zip(&tokens) {
            *slot = word_index(token)
                .with_context(|| format!("{token:?} is not a word `sb pair` uses"))?;
        }
        let mut tokens = tokens;
        tokens.iter_mut().for_each(|t| zeroize::Zeroize::zeroize(t));
        Ok(Self {
            kind: CodeKind::Words,
            password: words_password(&indices),
            hosts: Vec::new(),
            port: None,
        })
    }

    pub fn kind(&self) -> CodeKind {
        self.kind
    }

    /// Where the invite says the pairing device listens; empty for words.
    pub fn hosts(&self) -> &[String] {
        &self.hosts
    }

    pub fn port(&self) -> Option<u16> {
        self.port
    }

    /// Where to dial: `--host` when given, else the invite's addresses;
    /// empty for typed words without `--host`.
    pub fn addresses(&self, host: Option<&str>) -> Result<Vec<(String, u16)>> {
        if let Some(host) = host {
            return Ok(vec![pairing_address(host)?]);
        }
        let port = self.port.unwrap_or(PAIR_PORT);
        Ok(self.hosts.iter().map(|h| (h.clone(), port)).collect())
    }

    pub(super) fn password(&self) -> &[u8] {
        &self.password
    }
}

fn word_index(token: &str) -> Option<u16> {
    let list = words();
    let position = match list.binary_search(&token) {
        Ok(i) => i,
        Err(_) if token.len() >= PREFIX_LEN => {
            list.iter().position(|word| word.starts_with(token))?
        }
        Err(_) => return None,
    };
    u16::try_from(position).ok()
}

fn parse_invite(rest: &str) -> Result<JoinCode> {
    let malformed = || {
        anyhow::anyhow!(
            "a pairing invite reads sb-pair:<secret>@<hosts>:<port>; this one is cut short"
        )
    };
    let (secret, place) = rest.split_once('@').ok_or_else(malformed)?;
    let (hosts, port) = place.rsplit_once(':').ok_or_else(malformed)?;
    let port: u16 = port.parse().map_err(|_| malformed())?;
    if secret.len() != SECRET_LEN * 2 {
        return Err(malformed());
    }
    let mut bytes = Zeroizing::new([0u8; SECRET_LEN]);
    for (byte, pair) in bytes.iter_mut().zip(secret.as_bytes().chunks_exact(2)) {
        let digits = std::str::from_utf8(pair).map_err(|_| malformed())?;
        *byte = u8::from_str_radix(digits, 16).map_err(|_| malformed())?;
    }
    let hosts: Vec<String> = hosts
        .split(',')
        .filter(|h| !h.is_empty())
        .map(str::to_string)
        .collect();
    if hosts.is_empty() {
        return Err(malformed());
    }
    Ok(JoinCode {
        kind: CodeKind::Invite,
        password: secret_password(&bytes),
        hosts,
        port: Some(port),
    })
}

/// Splits `--host` into a host to dial and the pairing port: `name`,
/// `user@name`, `name:port`, `[v6]` or `[v6]:port`.
pub fn pairing_address(host: &str) -> Result<(String, u16)> {
    let host = host.trim();
    let host = host.rsplit_once('@').map_or(host, |(_, h)| h);
    if let Some(rest) = host.strip_prefix('[') {
        let (name, after) = rest
            .split_once(']')
            .with_context(|| format!("{host:?} opens a bracket it does not close"))?;
        let port = match after.strip_prefix(':') {
            Some(port) => port
                .parse()
                .with_context(|| format!("{port:?} is not a port"))?,
            None if after.is_empty() => PAIR_PORT,
            None => bail!("{host:?} has text after its closing bracket"),
        };
        return Ok((name.to_string(), port));
    }
    match host.split_once(':') {
        Some((name, port)) if !port.contains(':') => Ok((
            name.to_string(),
            port.parse()
                .with_context(|| format!("{port:?} is not a port"))?,
        )),
        Some(_) => Ok((host.to_string(), PAIR_PORT)),
        None if host.is_empty() => bail!("--host needs a host name or address"),
        None => Ok((host.to_string(), PAIR_PORT)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_word_list_has_2048_sorted_words_with_distinct_prefixes() {
        let list = words();
        assert_eq!(list.len(), WORD_COUNT);
        assert!(
            list.windows(2).all(|w| w[0] < w[1]),
            "binary search needs order"
        );
        let prefixes: std::collections::BTreeSet<&str> =
            list.iter().map(|w| &w[..w.len().min(PREFIX_LEN)]).collect();
        assert_eq!(prefixes.len(), WORD_COUNT);
        assert!(
            list.iter()
                .all(|w| w.bytes().all(|b| b.is_ascii_lowercase()))
        );
    }

    #[test]
    fn a_shown_code_parses_back_to_the_same_password_in_any_spelling() {
        let host = HostSecrets::generate();
        let code = host.code();
        let words: Vec<&str> = code.split('-').collect();
        assert_eq!(words.len(), CODE_WORDS);
        let spellings = [
            code.to_string(),
            code.to_uppercase(),
            words.join("  "),
            words
                .iter()
                .map(|w| &w[..w.len().min(PREFIX_LEN)])
                .collect::<Vec<_>>()
                .join(" "),
        ];
        for spelling in spellings {
            let parsed = JoinCode::parse(&spelling).unwrap();
            assert_eq!(parsed.kind(), CodeKind::Words);
            assert_eq!(parsed.password(), &host.password(CodeKind::Words)[..]);
        }
    }

    #[test]
    fn an_invite_parses_back_to_its_secret_hosts_and_port() {
        let host = HostSecrets::generate();
        let hosts = vec!["192.0.2.4".to_string(), "desk".to_string()];
        let invite = host.invite(&hosts, 7301);
        let parsed = JoinCode::parse(&invite).unwrap();
        assert_eq!(parsed.kind(), CodeKind::Invite);
        assert_eq!(parsed.hosts(), &hosts[..]);
        assert_eq!(parsed.port(), Some(7301));
        assert_eq!(parsed.password(), &host.password(CodeKind::Invite)[..]);
        assert_ne!(
            host.password(CodeKind::Invite),
            host.password(CodeKind::Words)
        );
    }

    #[test]
    fn malformed_codes_are_refused() {
        for bad in [
            "",
            "abandon ability able",
            "abandon ability able about above",
            "abandon ability able zzzz",
            "aban-abil-able-ab",
            "sb-pair:00@desk:1",
            "sb-pair:00112233445566778899aabbccddeeff@:7201",
            "sb-pair:00112233445566778899aabbccddeeff@desk",
            "sb-pair:0011223344556677889gaabbccddeeff@desk:7201",
        ] {
            assert!(JoinCode::parse(bad).is_err(), "{bad:?} must be refused");
        }
    }

    fn secrets(words: [u16; CODE_WORDS], secret: [u8; SECRET_LEN]) -> HostSecrets {
        HostSecrets {
            words: Zeroizing::new(words),
            secret: Zeroizing::new(secret),
        }
    }

    fn tokens(text: &str) -> std::collections::BTreeSet<String> {
        text.split(|c: char| !c.is_ascii_alphanumeric())
            .filter(|t| !t.is_empty())
            .map(str::to_ascii_lowercase)
            .collect()
    }

    fn debug_views(host: &HostSecrets) -> [String; 3] {
        let invite = host.invite(&["desk".into()], 7201);
        [
            format!("{host:?}"),
            format!("{:?}", JoinCode::parse(&host.code()).unwrap()),
            format!("{:?}", JoinCode::parse(&invite).unwrap()),
        ]
    }

    #[test]
    fn secrets_never_appear_in_debug_output() {
        let fixed = ["zebra", "orbit", "velvet", "lunar"];
        let indices = fixed.map(|w| word_index(w).unwrap());
        let secret: [u8; SECRET_LEN] = std::array::from_fn(|i| 0xa0 + i as u8);
        let host = secrets(indices, secret);
        let hex: String = secret.iter().map(|b| format!("{b:02x}")).collect();
        let renderings = [
            hex,
            format!("{indices:?}"),
            format!("{secret:?}"),
            format!("{:?}", &host.password(CodeKind::Words)[..]),
            format!("{:?}", &host.password(CodeKind::Invite)[..]),
        ];
        for shown in debug_views(&host) {
            let shown_tokens = tokens(&shown);
            for word in fixed {
                assert!(!shown_tokens.contains(word), "{word} in {shown}");
            }
            for rendering in &renderings {
                assert!(
                    !shown.contains(rendering.as_str()),
                    "{rendering} in {shown}"
                );
            }
        }
    }

    #[test]
    fn debug_output_is_the_same_for_every_word_and_secret() {
        let baseline = debug_views(&secrets([0; CODE_WORDS], [0; SECRET_LEN]));
        for (index, word) in words().iter().enumerate() {
            let byte = u8::try_from(index % 256).unwrap();
            let host = secrets(
                [u16::try_from(index).unwrap(); CODE_WORDS],
                [byte; SECRET_LEN],
            );
            assert_eq!(debug_views(&host), baseline, "{word}");
        }
    }

    #[test]
    fn a_host_names_its_pairing_port_or_takes_the_default() {
        let cases = [
            ("desk", ("desk", PAIR_PORT)),
            ("user@desk", ("desk", PAIR_PORT)),
            ("desk:7300", ("desk", 7300)),
            ("192.0.2.2:7300", ("192.0.2.2", 7300)),
            ("[fe80::1]", ("fe80::1", PAIR_PORT)),
            ("[fe80::1]:7300", ("fe80::1", 7300)),
            ("fe80::1", ("fe80::1", PAIR_PORT)),
        ];
        for (input, (host, port)) in cases {
            assert_eq!(
                pairing_address(input).unwrap(),
                (host.to_string(), port),
                "{input}"
            );
        }
        assert!(pairing_address("desk:port").is_err());
        assert!(pairing_address("").is_err());
    }
}