1use 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};
43pub 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#[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
75pub 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
86pub use sew_e2ee::StoredDevice;
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92#[non_exhaustive]
93pub enum KeyStorage {
94 Host,
96 Os,
98 File,
100 Memory,
102 Hardware,
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108#[non_exhaustive]
109pub enum DeviceWarning {
110 KeyStorageFile,
112 PinsReset,
114}
115
116impl DeviceWarning {
117 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
128#[non_exhaustive]
129pub enum DeviceError {
130 #[error("device store: {0}")]
132 Store(String),
133 #[error("enrolment refused ({status} {reason:?})")]
135 EnrollRefused {
136 status: u16,
138 reason: Option<String>,
140 },
141 #[error("certificate refused: {0}")]
143 Certificate(String),
144 #[error("hardware key unavailable: {0}")]
147 Unavailable(String),
148 #[error("a call is live")]
150 InCall,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
157pub struct DeviceKeyId {
158 pub install_id: u64,
160 pub member_id: MemberId,
162 pub device_scope: String,
164}
165
166impl DeviceKeyId {
167 pub fn account(&self) -> String {
170 format!(
171 "{}:{}:{}",
172 self.install_id, self.member_id, self.device_scope
173 )
174 }
175}
176
177#[derive(Clone)]
180pub struct DeviceKeyRecord {
181 pub key: Zeroizing<[u8; 32]>,
183 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
198pub trait DeviceKeyStore: Send + Sync + 'static {
215 fn load(&self, id: &DeviceKeyId) -> Result<Option<DeviceKeyRecord>, DeviceError>;
217 fn store(&self, id: &DeviceKeyId, record: &DeviceKeyRecord) -> Result<(), DeviceError>;
219 fn clear(&self, id: &DeviceKeyId) -> Result<(), DeviceError>;
221}
222
223#[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 pub fn new() -> MemoryDeviceKeyStore {
239 MemoryDeviceKeyStore::default()
240 }
241
242 pub fn len(&self) -> usize {
244 crate::e2ee::keys::lock(&self.entries).len()
245 }
246
247 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
269pub trait SecretStore: Send + Sync + 'static {
274 fn kind(&self) -> KeyStorage;
276 fn load(&self, account: &str) -> Result<Option<Zeroizing<[u8; 32]>>, DeviceError>;
278 fn save(&self, account: &str, scalar: &[u8; 32]) -> Result<(), DeviceError>;
280 fn delete(&self, account: &str) -> Result<(), DeviceError>;
282}
283
284#[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 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#[derive(Debug, Clone)]
325pub struct FileSecretStore {
326 dir: PathBuf,
327}
328
329impl FileSecretStore {
330 pub fn new(dir: impl Into<PathBuf>) -> FileSecretStore {
332 FileSecretStore { dir: dir.into() }
333 }
334
335 fn path(&self, account: &str) -> PathBuf {
336 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 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#[cfg(feature = "keyring-store")]
379#[derive(Debug, Clone)]
380pub struct OsSecretStore {
381 service: String,
382}
383
384#[cfg(feature = "keyring-store")]
385impl OsSecretStore {
386 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 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
474pub 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
539pub 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 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 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 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#[derive(Clone, Default)]
667#[non_exhaustive]
668pub enum StoreChoice {
669 #[default]
672 Auto,
673 File,
675 Custom(Arc<dyn SecretStore>),
677 Host(Arc<dyn DeviceKeyStore>),
679 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#[derive(Clone)]
698enum Keys {
699 Local(Arc<dyn SecretStore>),
701 Host(Arc<dyn DeviceKeyStore>),
703 Hardware(Arc<dyn HardwareDeviceKey>),
705}
706
707#[derive(Debug, Clone)]
709#[non_exhaustive]
710pub struct VaultConfig {
711 pub data_dir: PathBuf,
713 pub app_id: String,
716 pub store: StoreChoice,
718 pub label: String,
720 pub platform: DevicePlatform,
722}
723
724impl VaultConfig {
725 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
743pub 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
764pub 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 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 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 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 pub fn platform(&self) -> DevicePlatform {
849 self.platform
850 }
851
852 pub fn take_warnings(&mut self) -> Vec<DeviceWarning> {
854 std::mem::take(&mut self.warnings)
855 }
856
857 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 pub fn id(&self) -> &DeviceKeyId {
868 &self.id
869 }
870
871 pub fn file_mut(&mut self) -> &mut DeviceFile {
873 &mut self.file
874 }
875
876 pub fn file(&self) -> &DeviceFile {
878 &self.file
879 }
880
881 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 pub async fn device_key(&self) -> Result<Option<DeviceKey>, DeviceError> {
892 Ok(self.stored().await?.1)
893 }
894
895 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 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 Keys::Hardware(_) => self.file.save(stored).map_err(DeviceError::Store),
966 }
967 }
968
969 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 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 Keys::Host(_) => Ok(()),
1004 }
1005 }
1006
1007 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 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 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 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
1125pub 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
1156fn 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 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 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
1202pub 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 let _ = std::fs::remove_dir(&dir);
1236 removed.sort();
1237 Ok(removed)
1238}
1239
1240pub 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}