second-brain-sync 0.13.1

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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
use std::collections::BTreeSet;
use std::fmt;
use std::fs;
use std::io::Write;
use std::path::Path;

use age::x25519::Recipient;
use anyhow::{Context, Result, anyhow};
use second_brain_core::keys::{
    DEVICE_KEY_FILE, DeviceKeys, DeviceRecord, Envelope, Epoch, EpochCause, IdentityKey,
    IdentityTag, KeyGuard, SignedRecord, load_device_keys, newest_epoch, wrap,
};
use second_brain_core::sqlite_store::SqliteStore;
use serde::{Deserialize, Serialize};

use crate::crypto::{EpochSealer, WireKey, read_key_file};
use crate::protocol::HandshakeKeys;
use crate::snapshot::SnapshotKey;

mod handover;
mod own_row;
mod pairing;
mod recovery;
mod retirement;
mod revocation;
mod status;

pub use pairing::{Joined, REMOVED, take_admission};
pub use recovery::RecoveryState;
pub use retirement::Retired;
pub use revocation::{Removal, RemovalRefused};
pub use status::{IdentityStatus, PeerStanding, RetiredPhrase};

pub const LEGACY_KEY_FILE: &str = "sync.key";
pub const MIGRATED_PEERS_FILE: &str = "migrated-peers.json";

/// How long after this device's upgrade a peer it knew before may still
/// introduce itself with a self-signed row.
pub const MIGRATION_WINDOW_MICROS: i64 = 90 * 86_400 * 1_000_000;

const MIGRATED_TAG_PREFIX: &str = "m-";

/// The two sides of a sync hold different identity keys, or one holds none,
/// so neither could open the other's frames.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdentityMismatch(pub String);

impl fmt::Display for IdentityMismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for IdentityMismatch {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Continuity {
    /// No `sync.key` to carry over.
    NoKeyFile,
    /// The key became epoch 0 of `identity` and the file was deleted.
    Migrated { identity: IdentityTag },
    /// This device already holds an identity key, so the file was left in
    /// place and is never read for sync.
    Ignored { reason: String },
}

#[derive(Debug, Serialize, Deserialize)]
struct MigratedPeers {
    frozen_at_micros: i64,
    machine_ids: BTreeSet<String>,
}

/// Turns a `sync.key` from sync protocol 3 or older into epoch 0 of this
/// device's identity key, wrapped to its device key, mints epoch 1 and
/// writes this device's self-signed row. The file is deleted only once the
/// wrapped key is on disk and opens again. Safe to rerun after a crash at
/// any step.
pub fn migrate_sync_key(
    store: &SqliteStore,
    data_dir: &Path,
    name: &str,
    now_micros: i64,
) -> Result<Continuity> {
    let path = data_dir.join(LEGACY_KEY_FILE);
    let Some(raw) = read_key_file(&path)? else {
        return Ok(Continuity::NoKeyFile);
    };
    let epoch0_key = IdentityKey::from_bytes(KeyGuard::new(raw));
    let tag = IdentityTag::migrated(&epoch0_key.key_id());
    let epoch0 = Epoch {
        number: 0,
        key_id: epoch0_key.key_id(),
    };
    let device = load_device(data_dir)?;
    let own = store.machine_id().to_string();
    let recipient = device.age_recipient();

    let held = store.envelopes_for_machine(&own)?;
    if !held.is_empty()
        && !held
            .iter()
            .any(|e| e.identity_tag == tag && e.epoch == epoch0)
    {
        return Ok(Continuity::Ignored {
            reason: format!(
                "{} is ignored: this device already holds an identity key",
                path.display()
            ),
        });
    }

    let mut epochs = vec![epoch0];
    let mut envelopes = vec![wrap(&epoch0_key, 0, &tag, &recipient, Some(own.clone()))?];
    if !held
        .iter()
        .any(|e| e.identity_tag == tag && e.epoch.number > 0)
    {
        let first = IdentityKey::generate()?;
        epochs.push(Epoch {
            number: 1,
            key_id: first.key_id(),
        });
        envelopes.push(wrap(&first, 1, &tag, &recipient, Some(own.clone()))?);
    }
    if store.device_record(&own)?.is_none() {
        let row = own_row(&device, &own, &tag, name).sign(&own, device.signing_key());
        store.insert_first_device_record(&row, &own, &device.verifying_key())?;
    }
    freeze_known_peers(store, data_dir, now_micros)?;
    // The synced commit flushes the whole WAL, so the row written above is on
    // disk with the envelopes before the file goes.
    store.put_keys_durably(&tag, &epochs, &envelopes, now_micros)?;

    let stored = store
        .envelope(&tag, &epoch0, &recipient.to_string())?
        .context("the wrapped sync.key is not in the store after the write")?;
    let reopened = stored.open(device.age_identity())?;
    anyhow::ensure!(
        reopened.key_id() == epoch0.key_id,
        "the wrapped sync.key opened to another key"
    );
    fs::remove_file(&path).with_context(|| format!("deleting {}", path.display()))?;
    sync_dir(data_dir)?;
    Ok(Continuity::Migrated { identity: tag })
}

fn own_row(device: &DeviceKeys, own: &str, tag: &IdentityTag, name: &str) -> DeviceRecord {
    DeviceRecord {
        machine_id: own.to_string(),
        identity_tag: tag.as_str().to_string(),
        version: 1,
        name: name.to_string(),
        age_recipient: device.age_recipient().to_string(),
        ssh_public_key: device.ssh_public_key(),
        signing_public_key: device.verifying_key().to_bytes(),
        recovery_fingerprints: Vec::new(),
        ssh_login: None,
        ssh_port: None,
        ssh_host_key: None,
    }
}

fn freeze_known_peers(store: &SqliteStore, data_dir: &Path, now_micros: i64) -> Result<()> {
    let path = data_dir.join(MIGRATED_PEERS_FILE);
    if path.exists() {
        return Ok(());
    }
    let frozen = MigratedPeers {
        frozen_at_micros: now_micros,
        machine_ids: store.known_peer_ids()?,
    };
    let staged = data_dir.join(format!(".{MIGRATED_PEERS_FILE}.tmp"));
    let mut file =
        fs::File::create(&staged).with_context(|| format!("staging {}", staged.display()))?;
    file.write_all(&serde_json::to_vec(&frozen)?)?;
    file.sync_all()?;
    drop(file);
    fs::rename(&staged, &path).with_context(|| format!("writing {}", path.display()))?;
    sync_dir(data_dir)
}

fn load_migrated_peers(data_dir: &Path) -> Result<Option<MigratedPeers>> {
    let path = data_dir.join(MIGRATED_PEERS_FILE);
    match fs::read(&path) {
        Ok(bytes) => Ok(Some(
            serde_json::from_slice(&bytes)
                .with_context(|| format!("reading {}", path.display()))?,
        )),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
    }
}

fn sync_dir(dir: &Path) -> Result<()> {
    fs::File::open(dir)
        .and_then(|d| d.sync_all())
        .with_context(|| format!("syncing {}", dir.display()))
}

fn load_device(data_dir: &Path) -> Result<DeviceKeys> {
    load_device_keys(data_dir)?.with_context(|| {
        format!(
            "{} is missing; the daemon creates it on start",
            data_dir.join(DEVICE_KEY_FILE).display()
        )
    })
}

/// A refused row is the peer's doing and stays at debug; a failing store
/// is this device's and must be seen.
fn is_store_error(error: &anyhow::Error) -> bool {
    error.chain().any(|cause| cause.is::<rusqlite::Error>())
}

fn is_migrated(tag: &IdentityTag) -> bool {
    tag.as_str().starts_with(MIGRATED_TAG_PREFIX)
}

/// This device's sync identity: its device keys and the identity key epochs
/// it can open.
pub struct Keyring<'a> {
    store: &'a SqliteStore,
    data_dir: &'a Path,
    device: DeviceKeys,
    identity: Option<IdentityTag>,
    held: Vec<(Epoch, IdentityKey)>,
}

impl<'a> Keyring<'a> {
    pub fn load(store: &'a SqliteStore, data_dir: &'a Path) -> Result<Self> {
        let device = load_device(data_dir)?;
        let recipient = device.age_recipient().to_string();
        let mut identity = None;
        let mut held = Vec::new();
        if let Some((tag, envelopes)) = store.own_identity_envelopes(&recipient)? {
            for envelope in envelopes {
                match envelope.open(device.age_identity()) {
                    Ok(key) => held.push((envelope.epoch, key)),
                    Err(e) => tracing::warn!("skipping an envelope this device cannot open: {e:#}"),
                }
            }
            identity = Some(tag);
        }
        Ok(Self {
            store,
            data_dir,
            device,
            identity,
            held,
        })
    }

    pub fn identity(&self) -> Option<&IdentityTag> {
        self.identity.as_ref()
    }

    pub fn held_epochs(&self) -> Vec<Epoch> {
        self.held.iter().map(|(epoch, _)| *epoch).collect()
    }

    fn own(&self) -> &str {
        self.store.machine_id()
    }

    /// The name in a stored device row, else the machine id; never a name a
    /// peer sent, since refusal texts reach the user.
    fn device_name(&self, machine_id: &str) -> String {
        match self.store.device_record(machine_id) {
            Ok(Some(row)) if !row.current.record.name.is_empty() => row.current.record.name,
            _ => machine_id.to_string(),
        }
    }

    fn key(&self, epoch: &Epoch) -> Option<&IdentityKey> {
        self.held.iter().find(|(e, _)| e == epoch).map(|(_, k)| k)
    }

    /// A peer's current row when it belongs to this identity and is not
    /// revoked.
    fn active_row(&self, machine_id: &str) -> Result<Option<SignedRecord>> {
        let Some(tag) = &self.identity else {
            return Ok(None);
        };
        Ok(self
            .store
            .device_record(machine_id)?
            .filter(|row| !row.revoked && row.current.record.identity_tag == tag.as_str())
            .map(|row| row.current))
    }

    fn recipient_of(&self, machine_id: &str) -> Result<Option<(String, Recipient)>> {
        let Some(row) = self.active_row(machine_id)? else {
            return Ok(None);
        };
        let text = row.record.age_recipient;
        let parsed = text
            .parse::<Recipient>()
            .map_err(|e| anyhow!("device {machine_id} has an invalid age recipient: {e}"))?;
        Ok(Some((text, parsed)))
    }

    /// Epochs `peer` is known to hold: those it declared in a hello this
    /// device accepted, plus epoch 0 of a migrated identity, which every
    /// member holds.
    fn known_to_peer(&self, peer: &str) -> Result<Vec<Epoch>> {
        let Some(tag) = &self.identity else {
            return Ok(Vec::new());
        };
        let recipient = self.recipient_of(peer)?.map(|(text, _)| text);
        let mut known = Vec::new();
        for epoch in self.held_epochs() {
            let marked = match &recipient {
                Some(recipient) => self.store.envelope(tag, &epoch, recipient)?.is_some(),
                None => false,
            };
            if marked || (epoch.number == 0 && is_migrated(tag)) {
                known.push(epoch);
            }
        }
        Ok(known)
    }

    /// What this device tells `peer` in its hello: its identity, the epochs
    /// it holds, the rows it holds and the epochs `peer` lacks, wrapped for
    /// it. `declared` is what `peer` said it holds in the hello being
    /// answered; without one, earlier hellos decide.
    pub fn handshake_for(&self, peer: &str, declared: Option<&[Epoch]>) -> Result<HandshakeKeys> {
        let Some(tag) = &self.identity else {
            return Ok(HandshakeKeys::default());
        };
        let mut devices = Vec::new();
        let mut active = Vec::new();
        for row in self.store.device_records()? {
            if row.current.record.identity_tag != tag.as_str() {
                continue;
            }
            if !row.revoked {
                active.push(row.current.record.machine_id.clone());
            }
            if row.current != row.first {
                devices.push(row.first);
            }
            devices.push(row.current);
        }
        let mut envelopes = Vec::new();
        if let Some((_, recipient)) = self.recipient_of(peer)? {
            let known = match declared {
                Some(declared) => declared.to_vec(),
                None => self.known_to_peer(peer)?,
            };
            for (epoch, key) in &self.held {
                if !known.contains(epoch) {
                    envelopes.push(wrap(key, epoch.number, tag, &recipient, Some(peer.into()))?);
                }
            }
        }
        Ok(HandshakeKeys {
            identity_tag: Some(tag.clone()),
            epochs: self.held_epochs(),
            devices,
            envelopes,
            revocations: self.store.revocations(tag)?,
            retirements: self.store.retirements(tag)?,
            causes: self.causes()?,
            routes: self
                .store
                .device_routes()?
                .into_iter()
                .filter(|route| active.contains(&route.machine_id))
                .collect(),
        })
    }

    /// Refuses a peer that holds no identity key or another one, naming
    /// pairing as the fix. The text reaches the other side too, so it names
    /// both machines rather than saying "this device".
    pub fn check_peer(&self, peer: &HandshakeKeys, peer_name: &str) -> Result<()> {
        let own = self.device_name(self.own());
        let peer_name = self.device_name(peer_name);
        let mismatch = match (&self.identity, &peer.identity_tag) {
            (Some(ours), Some(theirs)) if ours == theirs => return Ok(()),
            (None, Some(_)) => format!(
                "{own} holds no sync identity key, so it cannot sync with {peer_name}; run \
                 `sb pair` on {peer_name}, then `sb pair <code>` on {own}; nothing was applied"
            ),
            (Some(_), None) => format!(
                "{peer_name} holds no sync identity key, so it cannot sync with {own}; run \
                 `sb pair` on {own}, then `sb pair <code>` on {peer_name}; nothing was applied"
            ),
            (None, None) => format!(
                "neither {own} nor {peer_name} holds a sync identity key; run `sb pair` on one \
                 of them, then `sb pair <code>` on the other; nothing was applied"
            ),
            (Some(_), Some(_)) => format!(
                "{peer_name} belongs to a different sync identity than {own}; run `sb pair` on \
                 the one to keep, then `sb pair <code>` on the other; nothing was applied"
            ),
        };
        Err(IdentityMismatch(mismatch).into())
    }

    /// Takes in what a peer's hello carries: the rows and revocations it
    /// holds, the epochs it wrapped for this device, and which epochs it
    /// holds. A peer its own revocations reach is refused once they are
    /// stored.
    pub fn accept(&self, peer: &str, keys: &HandshakeKeys, now_micros: i64) -> Result<()> {
        self.check_peer(keys, peer)?;
        let revoked_peer = self.is_revoked(peer)?;
        // Revocations by devices already known go first, so rows in this
        // hello signed only by a device it revokes are refused; the second
        // pass takes revocations whose revoker the rows introduced.
        self.accept_revocations(peer, &keys.revocations, revoked_peer)?;
        self.accept_rows(peer, &keys.devices, now_micros)?;
        self.accept_revocations(peer, &keys.revocations, revoked_peer)?;
        self.accept_retirements(peer, &keys.retirements)?;
        if let Err(refused) = self.refuse_revoked(peer) {
            self.apply_retirements(now_micros)?;
            return Err(refused);
        }
        self.accept_envelopes(peer, &keys.envelopes, &keys.causes, now_micros)?;
        self.fill_causes(&keys.causes, now_micros)?;
        self.mark_held_by(peer, &keys.epochs)?;
        self.store.merge_device_routes(peer, &keys.routes)?;
        self.apply_retirements(now_micros)?;
        self.fill_recovery_envelopes()?;
        if let Err(e) = self.record_peer_view(peer, keys, now_micros) {
            tracing::warn!("cannot record what {peer}'s hello showed of this device: {e:#}");
        }
        Ok(())
    }

    fn accept_rows(&self, peer: &str, rows: &[SignedRecord], now_micros: i64) -> Result<()> {
        let Some(tag) = &self.identity else {
            return Ok(());
        };
        let mut pending: Vec<&SignedRecord> = rows
            .iter()
            .filter(|row| {
                row.record.identity_tag == tag.as_str() && row.record.machine_id != self.own()
            })
            .collect();
        let migrated = load_migrated_peers(self.data_dir)?;
        loop {
            let before = pending.len();
            let mut left = Vec::new();
            for row in pending {
                match self.accept_row(peer, row, migrated.as_ref(), now_micros) {
                    Ok(true) => {}
                    Ok(false) => left.push(row),
                    Err(e) if is_store_error(&e) => tracing::warn!(
                        "cannot store the row for {} from {peer}: {e:#}",
                        row.record.machine_id
                    ),
                    Err(e) => tracing::debug!(
                        "not taking the row for {} from {peer}: {e:#}",
                        row.record.machine_id
                    ),
                }
            }
            pending = left;
            if pending.is_empty() || pending.len() == before {
                return Ok(());
            }
        }
    }

    /// False when no signer this device trusts has vouched for the row yet,
    /// so a later row in the same hello may still introduce its signer.
    fn accept_row(
        &self,
        peer: &str,
        row: &SignedRecord,
        migrated: Option<&MigratedPeers>,
        now_micros: i64,
    ) -> Result<bool> {
        let id = &row.record.machine_id;
        if let Some(stored) = self.store.device_record(id)? {
            if stored.revoked {
                return Ok(true);
            }
            if row.record == stored.first.record {
                for signature in &row.signatures {
                    if stored.first.signatures.contains(signature) || signature.signer == *id {
                        continue;
                    }
                    if let Some(signer) = self.active_row(&signature.signer)? {
                        self.store.insert_first_device_record(
                            row,
                            &signature.signer,
                            &signer.record.signing_public_key()?,
                        )?;
                    }
                }
            } else if row.record.version > stored.current.record.version {
                self.store.update_device_record(row)?;
            }
            return Ok(true);
        }

        let direct = id == peer
            && is_migrated(&IdentityTag::from(row.record.identity_tag.clone()))
            && migrated.is_some_and(|m| {
                m.machine_ids.contains(id)
                    && now_micros <= m.frozen_at_micros.saturating_add(MIGRATION_WINDOW_MICROS)
            });
        if direct {
            self.store
                .insert_first_device_record(row, id, &row.record.signing_public_key()?)?;
            let mut countersigned = row.clone();
            countersigned.countersign(self.own(), self.device.signing_key());
            self.store.insert_first_device_record(
                &countersigned,
                self.own(),
                &self.device.verifying_key(),
            )?;
            return Ok(true);
        }
        for signature in &row.signatures {
            if signature.signer == *id {
                continue;
            }
            if let Some(signer) = self.active_row(&signature.signer)? {
                self.store.insert_first_device_record(
                    row,
                    &signature.signer,
                    &signer.record.signing_public_key()?,
                )?;
                return Ok(true);
            }
        }
        Ok(false)
    }

    fn accept_envelopes(
        &self,
        peer: &str,
        envelopes: &[Envelope],
        causes: &[(Epoch, EpochCause)],
        now_micros: i64,
    ) -> Result<()> {
        let Some(tag) = &self.identity else {
            return Ok(());
        };
        if self.active_row(peer)?.is_none() {
            return Ok(());
        }
        let recipient = self.device.age_recipient().to_string();
        for envelope in envelopes {
            if envelope.identity_tag != *tag
                || envelope.recipient != recipient
                || envelope.machine_id.as_deref() != Some(self.own())
                || self.key(&envelope.epoch).is_some()
            {
                continue;
            }
            if let Err(e) = envelope.open(self.device.age_identity()) {
                tracing::warn!(
                    "{peer} sent an envelope for epoch {} this device cannot open: {e:#}",
                    envelope.epoch.number
                );
                continue;
            }
            let Some(cause) = self.applicable_cause(&envelope.epoch, causes)? else {
                tracing::warn!(
                    "{peer} sent epoch {} without the revocations behind it; it waits",
                    envelope.epoch.number
                );
                continue;
            };
            let cause = (!cause.is_empty()).then(|| cause.to_json()).transpose()?;
            self.store
                .put_key_epoch(tag, &envelope.epoch, cause.as_deref(), now_micros)?;
            self.store.put_envelope(envelope)?;
        }
        Ok(())
    }

    /// Keeps an envelope for exactly the epochs `peer` declared that this
    /// device also holds, which is how `known_to_peer` remembers them; a
    /// peer restored from an older backup declares fewer and loses the rest.
    fn mark_held_by(&self, peer: &str, declared: &[Epoch]) -> Result<()> {
        let Some(tag) = &self.identity else {
            return Ok(());
        };
        if peer == self.own() {
            return Ok(());
        }
        let Some((text, recipient)) = self.recipient_of(peer)? else {
            return Ok(());
        };
        for (epoch, key) in &self.held {
            let marked = self.store.envelope(tag, epoch, &text)?.is_some();
            if declared.contains(epoch) && !marked {
                let envelope = wrap(key, epoch.number, tag, &recipient, Some(peer.into()))?;
                self.store.put_envelope(&envelope)?;
            } else if !declared.contains(epoch) && marked {
                self.store.delete_envelope(tag, epoch, &text)?;
            }
        }
        Ok(())
    }

    /// Seals under the newest epoch `peer` holds: from its hello when one is
    /// at hand, otherwise from what earlier hellos showed.
    pub fn sealer_for(&self, peer: &str, declared: Option<&[Epoch]>) -> Result<EpochSealer> {
        let epoch = self.shared_epoch(peer, declared)?;
        EpochSealer::new(self.wire_keys()?, Some(epoch))
    }

    /// The snapshot key for the newest epoch `peer` holds, chosen as
    /// `sealer_for` chooses the wire key.
    pub fn snapshot_key_for(&self, peer: &str, declared: Option<&[Epoch]>) -> Result<SnapshotKey> {
        let epoch = self.shared_epoch(peer, declared)?;
        self.snapshot_key(&epoch)
    }

    /// The snapshot key of an epoch this device holds, to open a snapshot
    /// sealed under it.
    pub fn snapshot_key(&self, epoch: &Epoch) -> Result<SnapshotKey> {
        let identity = self.key(epoch).ok_or_else(|| {
            IdentityMismatch(format!(
                "the snapshot is sealed under identity key epoch {} (key id {}), which this \
                 device does not hold; pair it with `sb pair`, nothing was applied",
                epoch.number, epoch.key_id
            ))
        })?;
        SnapshotKey::derive(identity, epoch)
    }

    fn shared_epoch(&self, peer: &str, declared: Option<&[Epoch]>) -> Result<Epoch> {
        self.refuse_revoked(peer)?;
        let shared: Vec<Epoch> = match declared {
            Some(declared) => self
                .held_epochs()
                .into_iter()
                .filter(|e| declared.contains(e))
                .collect(),
            None => self.known_to_peer(peer)?,
        };
        Ok(newest_epoch(&shared).ok_or_else(|| {
            let (own, peer) = (self.device_name(self.own()), self.device_name(peer));
            IdentityMismatch(format!(
                "{own} and {peer} share no identity key epoch; re-pair {peer} with `sb pair`, \
                 nothing was sent"
            ))
        })?)
    }

    pub fn opener(&self) -> Result<EpochSealer> {
        if self.identity.is_none() {
            return Err(IdentityMismatch(
                "this device holds no sync identity key, so it cannot open a peer's records; \
                 pair it with `sb pair` from a device that syncs, nothing was applied"
                    .to_string(),
            )
            .into());
        }
        EpochSealer::new(self.wire_keys()?, None)
    }

    fn wire_keys(&self) -> Result<Vec<WireKey>> {
        self.held
            .iter()
            .map(|(epoch, key)| WireKey::derive(key, epoch))
            .collect()
    }
}