Skip to main content

sew_call_client/device/
mod.rs

1//! The device store: the native equivalent of the browser's IndexedDB `sew-e2ee`
2//! store.
3//!
4//! - **A host's own store** ([`DeviceKeyStore`], [`StoreChoice::Host`]): the host keeps the
5//!   device's private key **and** its public record ([`DeviceKeyRecord`]: device id,
6//!   certificate) itself, keyed by [`DeviceKeyId`] (install id, member id, `device_scope`), in
7//!   its own keyring or vault. Nothing of the device is written under the data directory then;
8//!   only the pins are. No `key_storage_file` warning.
9//! - **The built-in stores.** The private key (the P-256 scalar) goes in a [`SecretStore`]. By
10//!   default ([`StoreChoice::Auto`] without feature `keyring-store`, or [`StoreChoice::File`])
11//!   that is `device-<device_scope>.key` beside the public data, mode 0600 in a 0700 directory
12//!   ([`FileSecretStore`]), and the engine warns `key_storage_file` once. No pretend
13//!   encryption: a key next to its own decryption key protects nothing. With the optional
14//!   feature `keyring-store` (off by default), `Auto` prefers the OS credential store
15//!   (`OsSecretStore`: macOS login Keychain, Windows Credential Manager, Linux Secret Service
16//!   over `keyring`'s `async-secret-service`), service `sew-voice.<app identifier>`, account
17//!   `<install_id>:<device_scope>`, and falls back to the file when it does not answer.
18//! - **A hardware key** ([`HardwareDeviceKey`], [`StoreChoice::Hardware`]): the private key is
19//!   a non-exportable P-256 key in the Secure Enclave or StrongBox/TEE, behind the host's
20//!   trait; the public record stays in the [`DeviceFile`]. No software fallback: an error from
21//!   the key fails the call (`e2ee_refused`); a key that is gone enrols a new device
22//!   ([`hardware`]).
23//! - **The public data** ([`DeviceFile`]): the TOFU `Pins` (CA, DS, `external_sender`) and,
24//!   with the built-in stores, the `StoredDevice` (device id, certificate) in
25//!   `<data dir>/sew-voice/<install_id>/device-<device_scope>.json`, 0600 in a 0700 directory,
26//!   written atomically (temp file, fsync, rename). It implements `sew_e2ee::DeviceStore` for
27//!   that one install and scope.
28//! - **Losses** ([`DeviceVault::ensure_device`]): key lost or data lost, a new `device_scope` (a
29//!   new login lineage), a certificate refused or revoked: enrol again (`POST /api/v1/devices`),
30//!   keep the pins. Pins lost while a key survives: re-pinned on first sight, with a `pins_reset`
31//!   warning. A pin mismatch is never re-pinned silently: only [`DeviceVault::reset`] (the host's
32//!   explicit `reset_device`, a Rust API) clears the pins.
33
34use std::fmt;
35use std::io::Write as _;
36use std::path::{Path, PathBuf};
37use std::sync::Arc;
38
39use serde::{Deserialize, Serialize};
40use sew_e2ee::{
41    DeviceIdentity, DeviceStore, Enrollment, MemberId, Pins, SoftwareSigner, TrustAnchors,
42};
43/// The device's platform in its enrolment (Sew's `DeviceEnrollRequest.platform`).
44pub use sew_proto::e2ee::DevicePlatform;
45use sew_proto::e2ee::reasons;
46use zeroize::Zeroizing;
47
48use crate::e2ee::transport::KeyTransport;
49
50pub mod hardware;
51
52#[cfg(feature = "sim-software-key")]
53pub use hardware::SimSoftwareKey;
54pub use hardware::{DeviceKey, HardwareDeviceKey, p1363_from_der};
55
56// `sim-software-key` is for the iOS simulator and the x86 Android emulator only. An arm64
57// Android emulator cannot be told from a phone at compile time, so it is refused too.
58#[cfg(all(
59    feature = "sim-software-key",
60    not(any(
61        all(target_os = "ios", target_abi = "sim"),
62        all(target_os = "ios", target_arch = "x86_64"),
63        all(
64            target_os = "android",
65            any(target_arch = "x86_64", target_arch = "x86")
66        ),
67    ))
68))]
69compile_error!(
70    "sew-call-client: feature `sim-software-key` builds only for the iOS simulator \
71     (aarch64-apple-ios-sim, x86_64-apple-ios) and the x86 Android emulator \
72     (x86_64-linux-android, i686-linux-android); never ship it"
73);
74
75/// The platform this build enrols as, from `target_os`: iOS, Android, otherwise desktop.
76pub const fn default_platform() -> DevicePlatform {
77    if cfg!(target_os = "ios") {
78        DevicePlatform::Ios
79    } else if cfg!(target_os = "android") {
80        DevicePlatform::Android
81    } else {
82        DevicePlatform::Desktop
83    }
84}
85
86/// The device's public record in a [`DeviceKeyRecord`] (sew-e2ee's), re-exported so a host's
87/// [`DeviceKeyStore`] needs no sew-e2ee dependency of its own.
88pub use sew_e2ee::StoredDevice;
89
90/// Where the device key is kept.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92#[non_exhaustive]
93pub enum KeyStorage {
94    /// The host's own store ([`DeviceKeyStore`]).
95    Host,
96    /// The OS credential store (feature `keyring-store`).
97    Os,
98    /// A 0600 file beside the public data (the fallback; warned as `key_storage_file`).
99    File,
100    /// Process memory only (tests, a host that keeps keys itself).
101    Memory,
102    /// The host's hardware key ([`HardwareDeviceKey`]: Secure Enclave, StrongBox/TEE).
103    Hardware,
104}
105
106/// A warning for the host (the `errors` event: a warning, not a failure).
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108#[non_exhaustive]
109pub enum DeviceWarning {
110    /// `key_storage_file`: no OS credential store; the key is in a file.
111    KeyStorageFile,
112    /// `pins_reset`: the pins were lost while the key survived; re-pinned on first sight.
113    PinsReset,
114}
115
116impl DeviceWarning {
117    /// The `errors.code`.
118    pub fn code(self) -> &'static str {
119        match self {
120            DeviceWarning::KeyStorageFile => "key_storage_file",
121            DeviceWarning::PinsReset => "pins_reset",
122        }
123    }
124}
125
126/// Why the device store failed.
127#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
128#[non_exhaustive]
129pub enum DeviceError {
130    /// Reading or writing the store failed.
131    #[error("device store: {0}")]
132    Store(String),
133    /// The server refused the enrolment for good.
134    #[error("enrolment refused ({status} {reason:?})")]
135    EnrollRefused {
136        /// HTTP status.
137        status: u16,
138        /// `details.reason`.
139        reason: Option<String>,
140    },
141    /// The certificate Sew answered does not verify against the pinned CA.
142    #[error("certificate refused: {0}")]
143    Certificate(String),
144    /// The hardware key could not answer (a platform error, a signature that is not DER or does
145    /// not verify). The call's key setup fails (`e2ee_refused`); there is no software fallback.
146    #[error("hardware key unavailable: {0}")]
147    Unavailable(String),
148    /// A call is live (or joining): the device store can't be forgotten under it. Leave first.
149    #[error("a call is live")]
150    InCall,
151}
152
153/// Which device a [`DeviceKeyStore`] entry belongs to: one install of Sew, one member, one login
154/// lineage (the call credential's `device_scope`; a new sign-in is a new scope and enrols a new
155/// device).
156#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
157pub struct DeviceKeyId {
158    /// Sew's install id (READY's, the trust anchors').
159    pub install_id: u64,
160    /// The member the device is enrolled for.
161    pub member_id: MemberId,
162    /// The login lineage (32 hex characters from Sew; sanitized to `[A-Za-z0-9_-]`, at most 64).
163    pub device_scope: String,
164}
165
166impl DeviceKeyId {
167    /// A stable text form, `<install_id>:<member_id>:<device_scope>`, for a host that keys a
168    /// keyring or vault entry by one string.
169    pub fn account(&self) -> String {
170        format!(
171            "{}:{}:{}",
172            self.install_id, self.member_id, self.device_scope
173        )
174    }
175}
176
177/// What a [`DeviceKeyStore`] keeps for one device: the private key and the public record Sew
178/// answered at enrolment (or the last renewal).
179#[derive(Clone)]
180pub struct DeviceKeyRecord {
181    /// The device's P-256 private scalar (secret).
182    pub key: Zeroizing<[u8; 32]>,
183    /// The public record: device id, public key (SEC1), certificate, install and member.
184    pub device: StoredDevice,
185}
186
187impl fmt::Debug for DeviceKeyRecord {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        f.debug_struct("DeviceKeyRecord")
190            .field("key", &"<redacted>")
191            .field("install_id", &self.device.install_id)
192            .field("member_id", &self.device.member_id)
193            .field("device_id", &self.device.device_id)
194            .finish()
195    }
196}
197
198/// A host's own store for the device's private key and public record, e.g. K2's
199/// keyring or vault. Give it to the engine with [`StoreChoice::Host`]
200/// (`ClientConfig::with_device_key_store`, the Tauri plugin's `Builder::device_key_store`).
201///
202/// The engine calls it on a blocking thread (`tokio::task::spawn_blocking`), so calls may block
203/// (D-Bus, the Keychain, a vault round trip). Rules:
204///
205/// - `load` answers `Ok(None)` for "no device" (never stored, cleared, or unreadable: a damaged
206///   entry is a lost device, and the engine enrols again). An `Err` fails the call's key setup,
207///   so keep it for a store that cannot answer at all.
208/// - `store` replaces the whole entry (enrolment, renewal).
209/// - `clear` removes the entry and succeeds when there is none. The engine clears a device Sew
210///   refused or revoked and enrols again (the pins stay), and on the host's `reset_device`.
211///
212/// The pins (the server's CA, DS key and `external_sender`, TOFU) stay in the engine's data
213/// directory either way.
214pub trait DeviceKeyStore: Send + Sync + 'static {
215    /// The device of `id`, if stored.
216    fn load(&self, id: &DeviceKeyId) -> Result<Option<DeviceKeyRecord>, DeviceError>;
217    /// Saves (replaces) the device of `id`.
218    fn store(&self, id: &DeviceKeyId, record: &DeviceKeyRecord) -> Result<(), DeviceError>;
219    /// Forgets the device of `id` (no error when absent).
220    fn clear(&self, id: &DeviceKeyId) -> Result<(), DeviceError>;
221}
222
223/// An in-memory [`DeviceKeyStore`] (tests, and an example of the trait; never the engine's
224/// default).
225#[derive(Default)]
226pub struct MemoryDeviceKeyStore {
227    entries: std::sync::Mutex<std::collections::BTreeMap<DeviceKeyId, DeviceKeyRecord>>,
228}
229
230impl fmt::Debug for MemoryDeviceKeyStore {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        f.write_str("MemoryDeviceKeyStore(***)")
233    }
234}
235
236impl MemoryDeviceKeyStore {
237    /// An empty store.
238    pub fn new() -> MemoryDeviceKeyStore {
239        MemoryDeviceKeyStore::default()
240    }
241
242    /// How many devices it holds.
243    pub fn len(&self) -> usize {
244        crate::e2ee::keys::lock(&self.entries).len()
245    }
246
247    /// Whether it holds none.
248    pub fn is_empty(&self) -> bool {
249        self.len() == 0
250    }
251}
252
253impl DeviceKeyStore for MemoryDeviceKeyStore {
254    fn load(&self, id: &DeviceKeyId) -> Result<Option<DeviceKeyRecord>, DeviceError> {
255        Ok(crate::e2ee::keys::lock(&self.entries).get(id).cloned())
256    }
257
258    fn store(&self, id: &DeviceKeyId, record: &DeviceKeyRecord) -> Result<(), DeviceError> {
259        crate::e2ee::keys::lock(&self.entries).insert(id.clone(), record.clone());
260        Ok(())
261    }
262
263    fn clear(&self, id: &DeviceKeyId) -> Result<(), DeviceError> {
264        crate::e2ee::keys::lock(&self.entries).remove(id);
265        Ok(())
266    }
267}
268
269/// A place for the device's private scalar alone, for the built-in stores (the public record
270/// stays in [`DeviceFile`]). A host that keeps the whole device implements [`DeviceKeyStore`]
271/// instead. Calls may block (D-Bus, the Keychain): the key
272/// session runs them on a blocking thread.
273pub trait SecretStore: Send + Sync + 'static {
274    /// Which kind of store this is.
275    fn kind(&self) -> KeyStorage;
276    /// The scalar of `account`, if any.
277    fn load(&self, account: &str) -> Result<Option<Zeroizing<[u8; 32]>>, DeviceError>;
278    /// Saves (replaces) the scalar of `account`.
279    fn save(&self, account: &str, scalar: &[u8; 32]) -> Result<(), DeviceError>;
280    /// Deletes the scalar of `account` (no error when absent).
281    fn delete(&self, account: &str) -> Result<(), DeviceError>;
282}
283
284/// An in-memory store (tests; never chosen by `StoreChoice::Auto`).
285#[derive(Default)]
286pub struct MemorySecretStore {
287    keys: std::sync::Mutex<std::collections::BTreeMap<String, Zeroizing<[u8; 32]>>>,
288}
289
290impl fmt::Debug for MemorySecretStore {
291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292        f.write_str("MemorySecretStore(***)")
293    }
294}
295
296impl MemorySecretStore {
297    /// An empty store.
298    pub fn new() -> MemorySecretStore {
299        MemorySecretStore::default()
300    }
301}
302
303impl SecretStore for MemorySecretStore {
304    fn kind(&self) -> KeyStorage {
305        KeyStorage::Memory
306    }
307
308    fn load(&self, account: &str) -> Result<Option<Zeroizing<[u8; 32]>>, DeviceError> {
309        Ok(crate::e2ee::keys::lock(&self.keys).get(account).cloned())
310    }
311
312    fn save(&self, account: &str, scalar: &[u8; 32]) -> Result<(), DeviceError> {
313        crate::e2ee::keys::lock(&self.keys).insert(account.to_owned(), Zeroizing::new(*scalar));
314        Ok(())
315    }
316
317    fn delete(&self, account: &str) -> Result<(), DeviceError> {
318        crate::e2ee::keys::lock(&self.keys).remove(account);
319        Ok(())
320    }
321}
322
323/// The file fallback: `device-<device_scope>.key` (64 hex characters), 0600.
324#[derive(Debug, Clone)]
325pub struct FileSecretStore {
326    dir: PathBuf,
327}
328
329impl FileSecretStore {
330    /// Keys in `dir` (the install's directory).
331    pub fn new(dir: impl Into<PathBuf>) -> FileSecretStore {
332        FileSecretStore { dir: dir.into() }
333    }
334
335    fn path(&self, account: &str) -> PathBuf {
336        // `account` is `<install_id>:<device_scope>`; the install is the directory already.
337        let scope = account.rsplit(':').next().unwrap_or(account);
338        self.dir.join(format!("device-{}.key", sanitize(scope)))
339    }
340}
341
342impl SecretStore for FileSecretStore {
343    fn kind(&self) -> KeyStorage {
344        KeyStorage::File
345    }
346
347    fn load(&self, account: &str) -> Result<Option<Zeroizing<[u8; 32]>>, DeviceError> {
348        let p = self.path(account);
349        let text = match std::fs::read_to_string(&p) {
350            Ok(t) => Zeroizing::new(t),
351            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
352            Err(e) => return Err(DeviceError::Store(format!("read key: {}", e.kind()))),
353        };
354        let mut out = Zeroizing::new([0u8; 32]);
355        match hex::decode_to_slice(text.trim(), out.as_mut()) {
356            Ok(()) => Ok(Some(out)),
357            // A damaged key file is a lost key: enrol again.
358            Err(_) => Ok(None),
359        }
360    }
361
362    fn save(&self, account: &str, scalar: &[u8; 32]) -> Result<(), DeviceError> {
363        ensure_dir(&self.dir)?;
364        let text = Zeroizing::new(hex::encode(scalar));
365        write_atomic(&self.path(account), text.as_bytes())
366    }
367
368    fn delete(&self, account: &str) -> Result<(), DeviceError> {
369        match std::fs::remove_file(self.path(account)) {
370            Ok(()) => Ok(()),
371            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
372            Err(e) => Err(DeviceError::Store(format!("delete key: {}", e.kind()))),
373        }
374    }
375}
376
377/// The OS credential store through `keyring` (feature `keyring-store`).
378#[cfg(feature = "keyring-store")]
379#[derive(Debug, Clone)]
380pub struct OsSecretStore {
381    service: String,
382}
383
384#[cfg(feature = "keyring-store")]
385impl OsSecretStore {
386    /// The store of service `sew-voice.<app_id>`.
387    pub fn new(app_id: &str) -> OsSecretStore {
388        OsSecretStore {
389            service: format!("sew-voice.{app_id}"),
390        }
391    }
392
393    fn entry(&self, account: &str) -> Result<keyring::Entry, DeviceError> {
394        keyring::Entry::new(&self.service, account)
395            .map_err(|e| DeviceError::Store(format!("os store: {}", kind_of(&e))))
396    }
397
398    /// Whether the store answers at all (a round trip on a probe account). Blocking.
399    pub fn available(&self) -> bool {
400        let Ok(e) = self.entry("probe") else {
401            return false;
402        };
403        match e.get_secret() {
404            Ok(_) | Err(keyring::Error::NoEntry) => true,
405            Err(_) => false,
406        }
407    }
408}
409
410#[cfg(feature = "keyring-store")]
411fn kind_of(e: &keyring::Error) -> &'static str {
412    match e {
413        keyring::Error::NoEntry => "no entry",
414        keyring::Error::NoStorageAccess(_) => "no storage access",
415        keyring::Error::PlatformFailure(_) => "platform failure",
416        keyring::Error::BadEncoding(_) => "bad encoding",
417        keyring::Error::TooLong(..) => "too long",
418        keyring::Error::Invalid(..) => "invalid",
419        keyring::Error::Ambiguous(_) => "ambiguous",
420        _ => "other",
421    }
422}
423
424#[cfg(feature = "keyring-store")]
425impl SecretStore for OsSecretStore {
426    fn kind(&self) -> KeyStorage {
427        KeyStorage::Os
428    }
429
430    fn load(&self, account: &str) -> Result<Option<Zeroizing<[u8; 32]>>, DeviceError> {
431        match self.entry(account)?.get_secret() {
432            Ok(v) => {
433                let v = Zeroizing::new(v);
434                let a: Option<[u8; 32]> = v.as_slice().try_into().ok();
435                Ok(a.map(Zeroizing::new))
436            }
437            Err(keyring::Error::NoEntry) => Ok(None),
438            Err(e) => Err(DeviceError::Store(format!("os store: {}", kind_of(&e)))),
439        }
440    }
441
442    fn save(&self, account: &str, scalar: &[u8; 32]) -> Result<(), DeviceError> {
443        self.entry(account)?
444            .set_secret(scalar)
445            .map_err(|e| DeviceError::Store(format!("os store: {}", kind_of(&e))))
446    }
447
448    fn delete(&self, account: &str) -> Result<(), DeviceError> {
449        match self.entry(account)?.delete_credential() {
450            Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
451            Err(e) => Err(DeviceError::Store(format!("os store: {}", kind_of(&e)))),
452        }
453    }
454}
455
456fn sanitize(s: &str) -> String {
457    s.chars()
458        .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
459        .take(64)
460        .collect()
461}
462
463fn ensure_dir(dir: &Path) -> Result<(), DeviceError> {
464    std::fs::create_dir_all(dir).map_err(|e| DeviceError::Store(format!("mkdir: {}", e.kind())))?;
465    #[cfg(unix)]
466    {
467        use std::os::unix::fs::PermissionsExt as _;
468        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
469            .map_err(|e| DeviceError::Store(format!("chmod dir: {}", e.kind())))?;
470    }
471    Ok(())
472}
473
474/// Writes `bytes` to `path` atomically: a 0600 temp file beside it, fsync, rename, fsync of the
475/// directory (unix).
476pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), DeviceError> {
477    let dir = path
478        .parent()
479        .ok_or_else(|| DeviceError::Store("no parent directory".to_owned()))?;
480    let name = path
481        .file_name()
482        .and_then(|n| n.to_str())
483        .ok_or_else(|| DeviceError::Store("bad file name".to_owned()))?;
484    let tmp = dir.join(format!(".{name}.{:016x}.tmp", rand::random::<u64>()));
485    let io = |what: &str, e: std::io::Error| DeviceError::Store(format!("{what}: {}", e.kind()));
486    {
487        let mut opts = std::fs::OpenOptions::new();
488        opts.write(true).create_new(true);
489        #[cfg(unix)]
490        {
491            use std::os::unix::fs::OpenOptionsExt as _;
492            opts.mode(0o600);
493        }
494        let mut f = opts.open(&tmp).map_err(|e| io("create", e))?;
495        f.write_all(bytes).map_err(|e| io("write", e))?;
496        f.sync_all().map_err(|e| io("fsync", e))?;
497    }
498    if let Err(e) = std::fs::rename(&tmp, path) {
499        let _ = std::fs::remove_file(&tmp);
500        return Err(io("rename", e));
501    }
502    #[cfg(unix)]
503    if let Ok(d) = std::fs::File::open(dir) {
504        let _ = d.sync_all();
505    }
506    Ok(())
507}
508
509#[derive(Serialize, Deserialize, Default)]
510struct FileData {
511    v: u32,
512    #[serde(default, skip_serializing_if = "Option::is_none")]
513    device: Option<DeviceWire>,
514    #[serde(default, skip_serializing_if = "Option::is_none")]
515    pins: Option<PinsWire>,
516}
517
518#[derive(Serialize, Deserialize, Clone)]
519struct DeviceWire {
520    member_id: MemberId,
521    device_id: MemberId,
522    pubkey: String,
523    cert: String,
524}
525
526#[derive(Serialize, Deserialize, Clone)]
527struct PinsWire {
528    ca_public: String,
529    ds_public: String,
530    external_sender: String,
531}
532
533fn h<const N: usize>(s: &str) -> Option<[u8; N]> {
534    let mut out = [0u8; N];
535    hex::decode_to_slice(s, &mut out).ok()?;
536    Some(out)
537}
538
539/// The public data of one install and `device_scope` (a `sew_e2ee::DeviceStore`).
540pub struct DeviceFile {
541    path: PathBuf,
542    install_id: u64,
543    data: FileData,
544    existed: bool,
545}
546
547impl fmt::Debug for DeviceFile {
548    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549        f.debug_struct("DeviceFile")
550            .field("install_id", &self.install_id)
551            .field("device", &self.data.device.is_some())
552            .field("pins", &self.data.pins.is_some())
553            .finish()
554    }
555}
556
557impl DeviceFile {
558    /// Opens (or starts) `<dir>/device-<device_scope>.json`.
559    pub fn open(
560        dir: &Path,
561        install_id: u64,
562        device_scope: &str,
563    ) -> Result<DeviceFile, DeviceError> {
564        let path = dir.join(format!("device-{}.json", sanitize(device_scope)));
565        let (data, existed) = match std::fs::read(&path) {
566            Ok(b) => (serde_json::from_slice(&b).unwrap_or_default(), true),
567            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (FileData::default(), false),
568            Err(e) => return Err(DeviceError::Store(format!("read: {}", e.kind()))),
569        };
570        Ok(DeviceFile {
571            path,
572            install_id,
573            data,
574            existed,
575        })
576    }
577
578    /// The file's path.
579    pub fn path(&self) -> &Path {
580        &self.path
581    }
582
583    fn flush(&self) -> Result<(), String> {
584        let dir = self.path.parent().ok_or("no parent directory")?;
585        ensure_dir(dir).map_err(|e| e.to_string())?;
586        let mut data = serde_json::to_vec_pretty(&FileData {
587            v: 1,
588            device: self.data.device.clone(),
589            pins: self.data.pins.clone(),
590        })
591        .map_err(|e| e.to_string())?;
592        data.push(b'\n');
593        write_atomic(&self.path, &data).map_err(|e| e.to_string())
594    }
595
596    /// Forgets the device and keeps the pins (a lost or refused device).
597    pub fn forget_device(&mut self) -> Result<(), DeviceError> {
598        self.data.device = None;
599        self.flush().map_err(DeviceError::Store)
600    }
601}
602
603impl DeviceStore for DeviceFile {
604    fn load(&self, install_id: u64) -> Option<StoredDevice> {
605        if install_id != self.install_id {
606            return None;
607        }
608        let d = self.data.device.as_ref()?;
609        Some(StoredDevice {
610            install_id,
611            member_id: d.member_id,
612            device_id: d.device_id,
613            pubkey: h::<65>(&d.pubkey)?,
614            cert: hex::decode(&d.cert).ok()?,
615        })
616    }
617
618    fn save(&mut self, dev: &StoredDevice) -> Result<(), String> {
619        if dev.install_id != self.install_id {
620            return Err("another install".to_owned());
621        }
622        self.data.device = Some(DeviceWire {
623            member_id: dev.member_id,
624            device_id: dev.device_id,
625            pubkey: hex::encode(dev.pubkey),
626            cert: hex::encode(&dev.cert),
627        });
628        self.flush()
629    }
630
631    fn clear(&mut self, install_id: u64) {
632        if install_id == self.install_id {
633            self.data.device = None;
634            self.data.pins = None;
635            let _ = self.flush();
636        }
637    }
638
639    fn load_pins(&self, install_id: u64) -> Option<Pins> {
640        if install_id != self.install_id {
641            return None;
642        }
643        let p = self.data.pins.as_ref()?;
644        Some(Pins {
645            install_id,
646            ca_public: h::<32>(&p.ca_public)?,
647            ds_public: h::<32>(&p.ds_public)?,
648            external_sender: hex::decode(&p.external_sender).ok()?,
649        })
650    }
651
652    fn save_pins(&mut self, pins: &Pins) -> Result<(), String> {
653        if pins.install_id != self.install_id {
654            return Err("another install".to_owned());
655        }
656        self.data.pins = Some(PinsWire {
657            ca_public: hex::encode(pins.ca_public),
658            ds_public: hex::encode(pins.ds_public),
659            external_sender: hex::encode(&pins.external_sender),
660        });
661        self.flush()
662    }
663}
664
665/// Which device store to use.
666#[derive(Clone, Default)]
667#[non_exhaustive]
668pub enum StoreChoice {
669    /// The default. The 0600 key file (with `key_storage_file`); with feature `keyring-store`,
670    /// the OS credential store when it answers, else the file.
671    #[default]
672    Auto,
673    /// The file store, always (warned as `key_storage_file`).
674    File,
675    /// A key-only store the host provides; the public record stays in the data directory.
676    Custom(Arc<dyn SecretStore>),
677    /// The host's own store for the key and the public record ([`DeviceKeyStore`]).
678    Host(Arc<dyn DeviceKeyStore>),
679    /// The host's hardware key ([`HardwareDeviceKey`]); the public record stays in the data
680    /// directory. Never falls back to a software key.
681    Hardware(Arc<dyn HardwareDeviceKey>),
682}
683
684impl fmt::Debug for StoreChoice {
685    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
686        match self {
687            StoreChoice::Auto => f.write_str("Auto"),
688            StoreChoice::File => f.write_str("File"),
689            StoreChoice::Custom(s) => write!(f, "Custom({:?})", s.kind()),
690            StoreChoice::Host(_) => f.write_str("Host"),
691            StoreChoice::Hardware(_) => f.write_str("Hardware"),
692        }
693    }
694}
695
696/// Where the vault keeps the key and the public record.
697#[derive(Clone)]
698enum Keys {
699    /// The key in a [`SecretStore`], the record in the [`DeviceFile`].
700    Local(Arc<dyn SecretStore>),
701    /// Both in the host's [`DeviceKeyStore`].
702    Host(Arc<dyn DeviceKeyStore>),
703    /// The key in the host's hardware, the record in the [`DeviceFile`].
704    Hardware(Arc<dyn HardwareDeviceKey>),
705}
706
707/// Where a vault lives.
708#[derive(Debug, Clone)]
709#[non_exhaustive]
710pub struct VaultConfig {
711    /// The host's app data directory.
712    pub data_dir: PathBuf,
713    /// The host's app identifier (with `keyring-store`, the OS store's service is
714    /// `sew-voice.<app_id>`).
715    pub app_id: String,
716    /// The secret store.
717    pub store: StoreChoice,
718    /// The device label Sew shows ("K2 on macOS"); trimmed to Sew's limit.
719    pub label: String,
720    /// The platform the device enrols as (default [`default_platform`], from `target_os`).
721    pub platform: DevicePlatform,
722}
723
724impl VaultConfig {
725    /// A vault in `data_dir` for `app_id`, labelled `label`: the default store
726    /// ([`StoreChoice::Auto`]) and the platform of [`default_platform`] (set `store` and
727    /// `platform` on the result to choose others).
728    pub fn new(
729        data_dir: impl Into<PathBuf>,
730        app_id: impl Into<String>,
731        label: impl Into<String>,
732    ) -> VaultConfig {
733        VaultConfig {
734            data_dir: data_dir.into(),
735            app_id: app_id.into(),
736            store: StoreChoice::default(),
737            label: label.into(),
738            platform: default_platform(),
739        }
740    }
741}
742
743/// One install's and login lineage's device: the public file, the secret store, and the
744/// enrolment and recovery rules.
745pub struct DeviceVault {
746    file: DeviceFile,
747    keys: Keys,
748    account: String,
749    id: DeviceKeyId,
750    label: String,
751    platform: DevicePlatform,
752    warnings: Vec<DeviceWarning>,
753}
754
755impl fmt::Debug for DeviceVault {
756    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
757        f.debug_struct("DeviceVault")
758            .field("file", &self.file)
759            .field("storage", &self.storage())
760            .finish_non_exhaustive()
761    }
762}
763
764/// The platform's name in the default label.
765pub fn platform_name() -> &'static str {
766    match std::env::consts::OS {
767        "macos" => "macOS",
768        "windows" => "Windows",
769        "linux" => "Linux",
770        "ios" => "iOS",
771        "android" => "Android",
772        _ => "desktop",
773    }
774}
775
776impl DeviceVault {
777    /// Opens the vault of `install_id`, `member` and `device_scope`. Blocking (the OS store
778    /// probe, a host store's `load`): call it on a blocking thread from async code. With a
779    /// hardware key the `pins_reset` probe (the key survived, the data did not) needs the key's
780    /// async `public_key`: [`DeviceVault::open_async`] does both.
781    pub fn open(
782        cfg: &VaultConfig,
783        install_id: u64,
784        member: MemberId,
785        device_scope: &str,
786    ) -> Result<DeviceVault, DeviceError> {
787        let dir = cfg.data_dir.join("sew-voice").join(install_id.to_string());
788        let mut warnings = Vec::new();
789        let keys = match &cfg.store {
790            StoreChoice::Host(s) => Keys::Host(s.clone()),
791            StoreChoice::Custom(s) => Keys::Local(s.clone()),
792            StoreChoice::File => {
793                warnings.push(DeviceWarning::KeyStorageFile);
794                Keys::Local(Arc::new(FileSecretStore::new(dir.clone())))
795            }
796            StoreChoice::Auto => Keys::Local(auto_store(&cfg.app_id, &dir, &mut warnings)),
797            StoreChoice::Hardware(k) => Keys::Hardware(k.clone()),
798        };
799        let file = DeviceFile::open(&dir, install_id, device_scope)?;
800        let scope = sanitize(device_scope);
801        let account = format!("{install_id}:{scope}");
802        let id = DeviceKeyId {
803            install_id,
804            member_id: member,
805            device_scope: scope,
806        };
807        let survives = match &keys {
808            Keys::Local(s) => s.load(&account)?.is_some(),
809            Keys::Host(s) => s.load(&id)?.is_some(),
810            // Probed by `open_async`.
811            Keys::Hardware(_) => false,
812        };
813        if !file.existed && survives {
814            warnings.push(DeviceWarning::PinsReset);
815        }
816        Ok(DeviceVault {
817            file,
818            keys,
819            account,
820            id,
821            label: cfg.label.clone(),
822            platform: cfg.platform,
823            warnings,
824        })
825    }
826
827    /// [`DeviceVault::open`] on a blocking thread, then, with a hardware key, its `pins_reset`
828    /// probe (the key's `public_key`). What the key session uses.
829    pub async fn open_async(
830        cfg: &VaultConfig,
831        install_id: u64,
832        member: MemberId,
833        device_scope: &str,
834    ) -> Result<DeviceVault, DeviceError> {
835        let (cfg2, scope) = (cfg.clone(), device_scope.to_owned());
836        let mut vault =
837            blocking(move || DeviceVault::open(&cfg2, install_id, member, &scope)).await?;
838        if let Keys::Hardware(k) = &vault.keys
839            && !vault.file.existed
840            && k.public_key(&vault.id).await?.is_some()
841        {
842            vault.warnings.push(DeviceWarning::PinsReset);
843        }
844        Ok(vault)
845    }
846
847    /// The platform the device enrols as.
848    pub fn platform(&self) -> DevicePlatform {
849        self.platform
850    }
851
852    /// Warnings for the host, once each.
853    pub fn take_warnings(&mut self) -> Vec<DeviceWarning> {
854        std::mem::take(&mut self.warnings)
855    }
856
857    /// Where the key is kept.
858    pub fn storage(&self) -> KeyStorage {
859        match &self.keys {
860            Keys::Local(s) => s.kind(),
861            Keys::Host(_) => KeyStorage::Host,
862            Keys::Hardware(_) => KeyStorage::Hardware,
863        }
864    }
865
866    /// The device this vault is for (the [`DeviceKeyStore`] key).
867    pub fn id(&self) -> &DeviceKeyId {
868        &self.id
869    }
870
871    /// The public data (the pins for `TrustAnchors::from_ready`).
872    pub fn file_mut(&mut self) -> &mut DeviceFile {
873        &mut self.file
874    }
875
876    /// The public data.
877    pub fn file(&self) -> &DeviceFile {
878        &self.file
879    }
880
881    /// The software device key, if stored (on a blocking thread). Always `None` with a hardware
882    /// key, whose private half never leaves the hardware: see [`DeviceVault::device_key`].
883    pub async fn signer(&self) -> Result<Option<SoftwareSigner>, DeviceError> {
884        if matches!(self.keys, Keys::Hardware(_)) {
885            return Ok(None);
886        }
887        Ok(self.stored().await?.1.and_then(DeviceKey::into_software))
888    }
889
890    /// The device key, software or hardware, if stored.
891    pub async fn device_key(&self) -> Result<Option<DeviceKey>, DeviceError> {
892        Ok(self.stored().await?.1)
893    }
894
895    /// The stored public record and key, each if present (on a blocking thread). A host record
896    /// for another install or member is no device; a hardware key whose `public_key` answers
897    /// `None` is a lost key.
898    async fn stored(&self) -> Result<(Option<StoredDevice>, Option<DeviceKey>), DeviceError> {
899        match &self.keys {
900            Keys::Local(s) => {
901                let (s, a) = (s.clone(), self.account.clone());
902                let signer =
903                    blocking(move || Ok(s.load(&a)?.and_then(|k| SoftwareSigner::from_bytes(&k))))
904                        .await?;
905                Ok((
906                    self.file.load(self.file.install_id),
907                    signer.map(DeviceKey::software),
908                ))
909            }
910            Keys::Hardware(k) => {
911                let key = match k.public_key(&self.id).await? {
912                    Some(public) => Some(DeviceKey::hardware(k.clone(), self.id.clone(), public)?),
913                    None => None,
914                };
915                Ok((self.file.load(self.file.install_id), key))
916            }
917            Keys::Host(s) => {
918                let (s, id) = (s.clone(), self.id.clone());
919                let rec = blocking(move || s.load(&id)).await?;
920                Ok(match rec {
921                    Some(r)
922                        if r.device.install_id == self.id.install_id
923                            && r.device.member_id == self.id.member_id =>
924                    {
925                        let signer = SoftwareSigner::from_bytes(&r.key).map(DeviceKey::software);
926                        (Some(r.device), signer)
927                    }
928                    _ => (None, None),
929                })
930            }
931        }
932    }
933
934    /// Saves the device and, when it is new (`key_changed`), its key: an enrolment or a
935    /// renewal. A host store gets the whole record each time.
936    async fn save_device(
937        &mut self,
938        stored: &StoredDevice,
939        signer: &DeviceKey,
940        key_changed: bool,
941    ) -> Result<(), DeviceError> {
942        let scalar = || {
943            signer
944                .software_bytes()
945                .ok_or_else(|| DeviceError::Store("a hardware key in a software store".to_owned()))
946        };
947        match &self.keys {
948            Keys::Local(s) => {
949                if key_changed {
950                    let (s, a) = (s.clone(), self.account.clone());
951                    let k = scalar()?;
952                    blocking(move || s.save(&a, &k)).await?;
953                }
954                self.file.save(stored).map_err(DeviceError::Store)
955            }
956            Keys::Host(s) => {
957                let (s, id) = (s.clone(), self.id.clone());
958                let rec = DeviceKeyRecord {
959                    key: scalar()?,
960                    device: stored.clone(),
961                };
962                blocking(move || s.store(&id, &rec)).await
963            }
964            // The key is the hardware's already (`generate`); only the record is ours.
965            Keys::Hardware(_) => self.file.save(stored).map_err(DeviceError::Store),
966        }
967    }
968
969    /// A new key for an enrolment: a software key, or the hardware's (`generate`, replacing
970    /// any old one).
971    async fn new_key(&self) -> Result<DeviceKey, DeviceError> {
972        match &self.keys {
973            Keys::Hardware(k) => {
974                let public = k.generate(&self.id).await?;
975                DeviceKey::hardware(k.clone(), self.id.clone(), public)
976            }
977            Keys::Local(_) | Keys::Host(_) => Ok(DeviceKey::software(SoftwareSigner::generate(
978                &mut rand::rngs::OsRng,
979            ))),
980        }
981    }
982
983    async fn delete_key(&self) -> Result<(), DeviceError> {
984        match &self.keys {
985            Keys::Local(s) => {
986                let (s, a) = (s.clone(), self.account.clone());
987                blocking(move || s.delete(&a)).await
988            }
989            Keys::Host(s) => {
990                let (s, id) = (s.clone(), self.id.clone());
991                blocking(move || s.clear(&id)).await
992            }
993            Keys::Hardware(k) => k.delete(&self.id).await,
994        }
995    }
996
997    /// Forgets the device and its key, keeping the pins (a refused or revoked device).
998    pub async fn forget_device(&mut self) -> Result<(), DeviceError> {
999        self.delete_key().await?;
1000        match self.keys {
1001            Keys::Local(_) | Keys::Hardware(_) => self.file.forget_device(),
1002            // Nothing of the device is in the file; the pins stay.
1003            Keys::Host(_) => Ok(()),
1004        }
1005    }
1006
1007    /// The host's explicit `reset_device`: the device, its key **and** the pins. The next call
1008    /// re-pins on first sight.
1009    pub async fn reset(&mut self) -> Result<(), DeviceError> {
1010        self.delete_key().await?;
1011        let install = self.file.install_id;
1012        self.file.clear(install);
1013        Ok(())
1014    }
1015
1016    /// The verified device of `me`, enrolling or renewing its certificate as needed:
1017    ///
1018    /// - a stored device with its key whose certificate verifies (pinned CA, member, key, not
1019    ///   in the CRL): used, renewed silently when under 7 days are left; a renewal answered
1020    ///   `422 device_revoked` or `404` enrols again;
1021    /// - anything else (key lost, data lost, refused, revoked): enrol again with a new key,
1022    ///   keeping the pins. `409 device_key_in_use` retries once with another new key.
1023    pub async fn ensure_device(
1024        &mut self,
1025        http: &KeyTransport,
1026        trust: &TrustAnchors,
1027        me: MemberId,
1028        now: u64,
1029    ) -> Result<(DeviceIdentity, DeviceKey), DeviceError> {
1030        if let (Some(stored), Some(signer)) = self.stored().await? {
1031            let key_matches = signer.public_key_sec1() == stored.pubkey;
1032            match DeviceIdentity::from_stored(stored, trust, me, now) {
1033                Ok(id) if key_matches => {
1034                    if !Enrollment::needs_renewal(&id, now) {
1035                        return Ok((id, signer));
1036                    }
1037                    match http.renew_device(id.device_id()).await {
1038                        Ok(resp) => {
1039                            let stored =
1040                                Enrollment::accept(resp, trust, me, &signer.public_key_sec1(), now)
1041                                    .map_err(|e| DeviceError::Certificate(e.to_string()))?;
1042                            self.save_device(&stored, &signer, false).await?;
1043                            let id = DeviceIdentity::from_stored(stored, trust, me, now)
1044                                .map_err(|e| DeviceError::Certificate(e.to_string()))?;
1045                            return Ok((id, signer));
1046                        }
1047                        Err(f) if is_device_refused(&f) || f.status == 404 => {
1048                            tracing::info!(target: "sew_call_client::device", "device refused on renew; enrolling again");
1049                        }
1050                        // Not renewed yet (transport, busy): the certificate is still valid.
1051                        Err(_) => return Ok((id, signer)),
1052                    }
1053                }
1054                _ => {
1055                    tracing::info!(target: "sew_call_client::device", "stored device unusable; enrolling again");
1056                }
1057            }
1058        }
1059        self.forget_device().await?;
1060        self.enroll(http, trust, me, now).await
1061    }
1062
1063    /// Enrols with a fresh key (one retry on `409 device_key_in_use`) as
1064    /// [`DeviceVault::platform`]. With a hardware key the fresh key is the hardware's
1065    /// (`generate`).
1066    pub async fn enroll(
1067        &mut self,
1068        http: &KeyTransport,
1069        trust: &TrustAnchors,
1070        me: MemberId,
1071        now: u64,
1072    ) -> Result<(DeviceIdentity, DeviceKey), DeviceError> {
1073        let install = trust.install_id();
1074        let mut retried = false;
1075        loop {
1076            let signer = self.new_key().await?;
1077            let pubkey = signer.public_key_sec1();
1078            let (draft, req) = Enrollment::begin(&pubkey, self.platform, &self.label, install, me);
1079            let body = Enrollment::request(draft, signer.sign(&req.message).await?);
1080            let resp = match http.enroll(&body).await {
1081                Ok(r) => r,
1082                Err(f) if !retried && f.status == 409 && f.is(reasons::DEVICE_KEY_IN_USE) => {
1083                    retried = true;
1084                    continue;
1085                }
1086                Err(f) => {
1087                    return Err(DeviceError::EnrollRefused {
1088                        status: f.status,
1089                        reason: f.reason,
1090                    });
1091                }
1092            };
1093            let stored = Enrollment::accept(resp, trust, me, &pubkey, now)
1094                .map_err(|e| DeviceError::Certificate(e.to_string()))?;
1095            self.save_device(&stored, &signer, true).await?;
1096            let id = DeviceIdentity::from_stored(stored, trust, me, now)
1097                .map_err(|e| DeviceError::Certificate(e.to_string()))?;
1098            return Ok((id, signer));
1099        }
1100    }
1101}
1102
1103async fn blocking<T: Send + 'static>(
1104    f: impl FnOnce() -> Result<T, DeviceError> + Send + 'static,
1105) -> Result<T, DeviceError> {
1106    tokio::task::spawn_blocking(f)
1107        .await
1108        .map_err(|_| DeviceError::Store("blocking task failed".to_owned()))?
1109}
1110
1111fn auto_store(app_id: &str, dir: &Path, warnings: &mut Vec<DeviceWarning>) -> Arc<dyn SecretStore> {
1112    #[cfg(feature = "keyring-store")]
1113    {
1114        let os = OsSecretStore::new(app_id);
1115        if os.available() {
1116            return Arc::new(os);
1117        }
1118    }
1119    #[cfg(not(feature = "keyring-store"))]
1120    let _ = app_id;
1121    warnings.push(DeviceWarning::KeyStorageFile);
1122    Arc::new(FileSecretStore::new(dir.to_path_buf()))
1123}
1124
1125/// Every device the data directory `data_dir` holds a record of (the built-in stores' and a
1126/// hardware key's public records, `<data_dir>/sew-voice/<install_id>/device-<scope>.json`),
1127/// sorted. With a host store ([`StoreChoice::Host`]) the records are the host's, so they are not
1128/// listed here. Blocking (it reads the directory).
1129pub fn known_device_keys(data_dir: &Path) -> Result<Vec<DeviceKeyId>, DeviceError> {
1130    let root = data_dir.join("sew-voice");
1131    let installs = match std::fs::read_dir(&root) {
1132        Ok(d) => d,
1133        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1134        Err(e) => return Err(DeviceError::Store(format!("read dir: {}", e.kind()))),
1135    };
1136    let mut out = Vec::new();
1137    for entry in installs {
1138        let entry = entry.map_err(|e| DeviceError::Store(format!("read dir: {}", e.kind())))?;
1139        let Some(install_id) = entry
1140            .file_name()
1141            .to_str()
1142            .and_then(|n| n.parse::<u64>().ok())
1143        else {
1144            continue;
1145        };
1146        out.extend(
1147            install_files(&entry.path(), install_id)?
1148                .into_iter()
1149                .filter_map(|(_, id)| id),
1150        );
1151    }
1152    out.sort();
1153    Ok(out)
1154}
1155
1156/// One install's device files: each file's path and, when it holds a device, the device's id.
1157fn install_files(
1158    dir: &Path,
1159    install_id: u64,
1160) -> Result<Vec<(PathBuf, Option<DeviceKeyId>)>, DeviceError> {
1161    let io = |e: std::io::Error| DeviceError::Store(format!("read: {}", e.kind()));
1162    let entries = match std::fs::read_dir(dir) {
1163        Ok(d) => d,
1164        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1165        Err(e) => return Err(io(e)),
1166    };
1167    let mut out = Vec::new();
1168    for entry in entries {
1169        let entry = entry.map_err(io)?;
1170        let name = entry.file_name();
1171        let Some(scope) = name
1172            .to_str()
1173            .and_then(|n| n.strip_prefix("device-"))
1174            .and_then(|n| n.strip_suffix(".json"))
1175        else {
1176            continue;
1177        };
1178        // Only names the vault writes (a sanitized scope).
1179        if scope.is_empty() || sanitize(scope) != scope {
1180            continue;
1181        }
1182        let path = entry.path();
1183        let bytes = match std::fs::read(&path) {
1184            Ok(b) => b,
1185            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
1186            Err(e) => return Err(io(e)),
1187        };
1188        // A damaged file is no device (as the vault reads it), but still the install's file.
1189        let id = serde_json::from_slice::<FileData>(&bytes)
1190            .ok()
1191            .and_then(|d| d.device)
1192            .map(|d| DeviceKeyId {
1193                install_id,
1194                member_id: d.member_id,
1195                device_scope: scope.to_owned(),
1196            });
1197        out.push((path, id));
1198    }
1199    Ok(out)
1200}
1201
1202/// A sign-out from one Sew install: every device of `install_id` that the data directory holds
1203/// a record of is reset ([`DeviceVault::reset`]: its key is deleted from the store `cfg.store`
1204/// names, a hardware key through [`HardwareDeviceKey::delete`], and the device and the pins are
1205/// cleared), and the install's device files are removed (the pins of a device without a record
1206/// too). Answers the ids it reset, sorted. The next call to that install enrols a new device
1207/// and pins again on first sight.
1208///
1209/// A key that can't be deleted stops it with that error and leaves that device's record, so a
1210/// retry finds it again. With a host store ([`StoreChoice::Host`]) the devices are the host's
1211/// to clear; only the pins go here.
1212pub async fn forget_install(
1213    cfg: &VaultConfig,
1214    install_id: u64,
1215) -> Result<Vec<DeviceKeyId>, DeviceError> {
1216    let dir = cfg.data_dir.join("sew-voice").join(install_id.to_string());
1217    let listed = dir.clone();
1218    let files = blocking(move || install_files(&listed, install_id)).await?;
1219    let mut removed = Vec::new();
1220    for (path, id) in files {
1221        if let Some(id) = id {
1222            let mut vault =
1223                DeviceVault::open_async(cfg, install_id, id.member_id, &id.device_scope).await?;
1224            vault.reset().await?;
1225            removed.push(id);
1226        }
1227        blocking(move || match std::fs::remove_file(&path) {
1228            Ok(()) => Ok(()),
1229            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1230            Err(e) => Err(DeviceError::Store(format!("remove: {}", e.kind()))),
1231        })
1232        .await?;
1233    }
1234    // The directory goes too once it is empty (anything else in it is left alone).
1235    let _ = std::fs::remove_dir(&dir);
1236    removed.sort();
1237    Ok(removed)
1238}
1239
1240/// Whether a key or device route refused the device itself (revoked, or its certificate
1241/// failed): Sew 0.7.1's rule is to forget it, enrol once and retry once.
1242pub fn is_device_refused(f: &sew_e2ee::ApiFailure) -> bool {
1243    use reasons::key_package_check as kc;
1244    (f.status == 422 && f.is(reasons::DEVICE_REVOKED))
1245        || (f.status == 422
1246            && f.is(reasons::E2EE_KEY_PACKAGE_INVALID)
1247            && matches!(f.detail.as_deref(), Some(d) if d == kc::DEVICE_CERT || d == kc::DEVICE_SIG))
1248}