1use aes_gcm::{aead::Aead, aead::Payload, Aes256Gcm, KeyInit, Nonce};
20use hkdf::Hkdf;
21use sha2::Sha256;
22use zeroize::Zeroizing;
23
24use super::codec::{label_from, Rd, W};
25use super::{sha256, LinkError, DOMAIN, LR};
26use crate::primitives as p;
27
28pub const DEVICE_TYPE_PHONE: u8 = 1;
29pub const DEVICE_TYPE_DESKTOP: u8 = 2;
30pub const LABEL_MAX: usize = 64;
31
32const ED_PUB: usize = 32;
33const DSA_PUB: usize = 1952;
34const DSA_SIG: usize = 3309;
35const X_PUB: usize = 32;
36const KEM_PUB: usize = 1568;
37const SECP_PUB: usize = 65;
38const SECP_SIG: usize = 64;
39const CERT_MAGIC: &[u8; 3] = b"UDC";
40const CERT_VERSION: u8 = 1;
41const SEED_SALT: &[u8] = b"umbera-device-seed-v1";
42const KEYS_DIGEST_DOMAIN: &[u8] = b"umbera-device-keys-v1";
43const LINK_SIG_DOMAIN: &str = "umbera-device-link-v1|";
44const LABEL_SEALED_MAX: usize = 512;
45
46pub const ALG_ED25519: &str = "ed25519";
48pub const ALG_MLDSA65: &str = "ml-dsa-65";
49pub const ALG_X25519: &str = "x25519";
50pub const ALG_MLKEM1024: &str = "ml-kem-1024";
51
52#[derive(uniffi::Record, Clone, Debug, PartialEq, Eq)]
54pub struct DevicePublicKeys {
55 pub ed25519: Vec<u8>,
56 pub mldsa65: Vec<u8>,
57 pub x25519: Vec<u8>,
58 pub mlkem1024: Vec<u8>,
59}
60
61#[derive(uniffi::Record, Clone, Debug, PartialEq, Eq)]
63pub struct DeviceKey {
64 pub alg: String,
65 pub key: Vec<u8>,
66}
67
68#[derive(uniffi::Record, Clone, Debug, PartialEq, Eq)]
71pub struct DeviceCertInfo {
72 pub user_id: String,
73 pub device_id: String,
74 pub keys: DevicePublicKeys,
75 pub wire_keys: Vec<DeviceKey>,
76 pub primary_sig: Vec<u8>,
77 pub pq_sig: Vec<u8>,
78 pub account_secp256k1: Vec<u8>,
80 pub account_mldsa65: Vec<u8>,
81 pub account_address: String,
83 pub label_sealed: Vec<u8>,
84 pub issued_at: u64,
85}
86
87#[derive(uniffi::Record)]
89pub struct DeviceEncryptionKeys {
90 pub x25519_private: Vec<u8>,
91 pub mlkem1024_seed: Vec<u8>,
92}
93
94#[derive(uniffi::Record, Clone, Debug, PartialEq, Eq)]
96pub struct DeviceLabel {
97 pub device_type: u8,
98 pub label: String,
99}
100
101pub(crate) struct DeviceSecrets {
102 pub ed_seed: Zeroizing<[u8; 32]>,
103 pub dsa_seed: Zeroizing<[u8; 32]>,
104 pub x_priv: Zeroizing<[u8; 32]>,
105 pub kem_seed: Zeroizing<[u8; 64]>,
106}
107
108pub(crate) fn device_secrets(seed: &[u8]) -> LR<DeviceSecrets> {
109 if seed.len() != 32 {
110 return Err(LinkError::Crypto(format!("device seed must be 32 bytes, got {}", seed.len())));
111 }
112 let h = Hkdf::<Sha256>::new(Some(SEED_SALT), seed);
113 let mut s = DeviceSecrets {
114 ed_seed: Zeroizing::new([0; 32]),
115 dsa_seed: Zeroizing::new([0; 32]),
116 x_priv: Zeroizing::new([0; 32]),
117 kem_seed: Zeroizing::new([0; 64]),
118 };
119 h.expand(b"ed25519", s.ed_seed.as_mut()).expect("hkdf len");
120 h.expand(b"mldsa65", s.dsa_seed.as_mut()).expect("hkdf len");
121 h.expand(b"x25519", s.x_priv.as_mut()).expect("hkdf len");
122 h.expand(b"mlkem1024", s.kem_seed.as_mut()).expect("hkdf len");
123 Ok(s)
124}
125
126fn public_of(s: &DeviceSecrets) -> LR<DevicePublicKeys> {
127 Ok(DevicePublicKeys {
128 ed25519: p::ed25519_public_from_seed(s.ed_seed.to_vec())?,
129 mldsa65: p::mldsa65_public_key(s.dsa_seed.to_vec())?,
130 x25519: p::x25519_public_key(s.x_priv.to_vec())?,
131 mlkem1024: p::mlkem1024_public_key(s.kem_seed.to_vec())?,
132 })
133}
134
135fn check_type(t: u8) -> LR<()> {
136 if t != DEVICE_TYPE_PHONE && t != DEVICE_TYPE_DESKTOP {
137 return Err(LinkError::Malformed(format!("unknown device type {t}")));
138 }
139 Ok(())
140}
141
142fn check_label(label: &str) -> LR<()> {
143 if label.len() > LABEL_MAX {
144 return Err(LinkError::Malformed(format!("device label longer than {LABEL_MAX} bytes")));
145 }
146 label_from(label.as_bytes(), "device label").map(|_| ())
147}
148
149fn check_uuid(s: &str, what: &str) -> LR<()> {
151 let b = s.as_bytes();
152 let ok = b.len() == 36
153 && b.iter().enumerate().all(|(i, c)| match i {
154 8 | 13 | 18 | 23 => *c == b'-',
155 _ => c.is_ascii_digit() || (b'a'..=b'f').contains(c),
156 });
157 if !ok {
158 return Err(LinkError::Malformed(format!("{what} must be a lowercase UUID")));
159 }
160 Ok(())
161}
162
163fn check_keys(k: &DevicePublicKeys) -> LR<()> {
164 if k.ed25519.len() != ED_PUB || k.mldsa65.len() != DSA_PUB || k.x25519.len() != X_PUB || k.mlkem1024.len() != KEM_PUB {
165 return Err(LinkError::Malformed("device public key lengths".into()));
166 }
167 if !p::mlkem1024_validate_public_key(k.mlkem1024.clone()) {
168 return Err(LinkError::Malformed("device ML-KEM key failed FIPS 203 validation".into()));
169 }
170 Ok(())
171}
172
173fn write_keys(w: &mut W, k: &DevicePublicKeys) {
174 w.raw(&k.ed25519).raw(&k.mldsa65).raw(&k.x25519).raw(&k.mlkem1024);
175}
176
177fn read_keys(r: &mut Rd) -> LR<DevicePublicKeys> {
178 let k = DevicePublicKeys {
179 ed25519: r.raw(ED_PUB)?.to_vec(),
180 mldsa65: r.raw(DSA_PUB)?.to_vec(),
181 x25519: r.raw(X_PUB)?.to_vec(),
182 mlkem1024: r.raw(KEM_PUB)?.to_vec(),
183 };
184 check_keys(&k)?;
185 Ok(k)
186}
187
188fn wire_of(k: &DevicePublicKeys) -> Vec<DeviceKey> {
189 vec![
190 DeviceKey { alg: ALG_ED25519.into(), key: k.ed25519.clone() },
191 DeviceKey { alg: ALG_MLDSA65.into(), key: k.mldsa65.clone() },
192 DeviceKey { alg: ALG_X25519.into(), key: k.x25519.clone() },
193 DeviceKey { alg: ALG_MLKEM1024.into(), key: k.mlkem1024.clone() },
194 ]
195}
196
197fn keys_from_wire(w: &[DeviceKey]) -> LR<DevicePublicKeys> {
199 let algs: Vec<&str> = w.iter().map(|k| k.alg.as_str()).collect();
200 if algs != [ALG_ED25519, ALG_MLDSA65, ALG_X25519, ALG_MLKEM1024] {
201 return Err(LinkError::Malformed(format!("unexpected device key set {algs:?}")));
202 }
203 let k = DevicePublicKeys {
204 ed25519: w[0].key.clone(),
205 mldsa65: w[1].key.clone(),
206 x25519: w[2].key.clone(),
207 mlkem1024: w[3].key.clone(),
208 };
209 check_keys(&k)?;
210 Ok(k)
211}
212
213fn keys_digest_of(w: &[DeviceKey]) -> [u8; 32] {
214 use sha2::Digest;
215 let mut h = Sha256::new();
216 h.update(KEYS_DIGEST_DOMAIN);
217 for k in w {
218 h.update([k.alg.len() as u8]);
219 h.update(k.alg.as_bytes());
220 h.update((k.key.len() as u32).to_be_bytes());
221 h.update(&k.key);
222 }
223 h.finalize().into()
224}
225
226fn link_message(user_id: &str, device_id: &str, w: &[DeviceKey]) -> String {
227 let d = keys_digest_of(w);
228 let hexd: String = d.iter().map(|x| format!("{x:02x}")).collect();
229 format!("{LINK_SIG_DOMAIN}{user_id}|{device_id}|{hexd}")
230}
231
232fn hex_of(b: &[u8]) -> String {
233 b.iter().map(|x| format!("{x:02x}")).collect()
234}
235
236fn address_of(secp_pub: &[u8], dsa_pub: &[u8]) -> LR<String> {
237 crate::quant_address(hex_of(secp_pub), hex_of(dsa_pub)).map_err(|e| LinkError::Crypto(e.to_string()))
238}
239
240fn hybrid_device_verify(k: &DevicePublicKeys, msg: &[u8], ed_sig: &[u8], dsa_sig: &[u8]) -> bool {
241 let a = p::ed25519_verify(k.ed25519.clone(), msg.to_vec(), ed_sig.to_vec());
243 let b = p::mldsa65_verify(msg.to_vec(), dsa_sig.to_vec(), k.mldsa65.clone());
244 a & b
245}
246
247fn verify_link_sigs(
249 user_id: &str,
250 device_id: &str,
251 wire: &[DeviceKey],
252 primary_sig: &[u8],
253 pq_sig: &[u8],
254 secp_pub: &[u8],
255 dsa_pub: &[u8],
256) -> LR<DevicePublicKeys> {
257 check_uuid(user_id, "user id")?;
258 check_uuid(device_id, "device id")?;
259 let keys = keys_from_wire(wire)?;
260 if primary_sig.len() != SECP_SIG || pq_sig.len() != DSA_SIG {
261 return Err(LinkError::Mismatch("device certificate needs both account signatures".into()));
262 }
263 let m = link_message(user_id, device_id, wire);
264 let a = p::secp256k1_verify_hash(p::sha256(m.as_bytes().to_vec()), primary_sig.to_vec(), secp_pub.to_vec());
265 let b = p::mldsa65_verify(m.into_bytes(), pq_sig.to_vec(), dsa_pub.to_vec());
266 if !(a & b) {
267 return Err(LinkError::Mismatch("device certificate signature is invalid".into()));
268 }
269 Ok(keys)
270}
271
272fn pop_message(th: &[u8; 32], body: &[u8]) -> Vec<u8> {
275 [DOMAIN, b"/device-pop".as_slice(), th, body].concat()
276}
277
278pub(crate) fn device_request_encode(th: &[u8; 32], seed: &[u8], device_type: u8, label: &str) -> LR<Vec<u8>> {
279 check_type(device_type)?;
280 check_label(label)?;
281 let s = device_secrets(seed)?;
282 let keys = public_of(&s)?;
283 let mut w = W::new();
284 w.u8(CERT_VERSION).u8(device_type).b8(label.as_bytes());
285 write_keys(&mut w, &keys);
286 let mut body = w.done();
287 let msg = pop_message(th, &body);
288 body.extend(p::ed25519_sign(msg.clone(), s.ed_seed.to_vec())?);
289 body.extend(p::mldsa65_sign(msg, s.dsa_seed.to_vec())?);
290 Ok(body)
291}
292
293pub(crate) fn device_request_decode(th: &[u8; 32], pt: &[u8]) -> LR<super::session::DeviceRequest> {
294 let mut r = Rd::new(pt, "device request");
295 let v = r.u8()?;
296 if v != CERT_VERSION {
297 return Err(LinkError::Malformed(format!("device request version {v}")));
298 }
299 let device_type = r.u8()?;
300 check_type(device_type)?;
301 let label = label_from(r.b8(LABEL_MAX)?, "device label")?;
302 let keys = read_keys(&mut r)?;
303 let body_len = r.pos();
304 let ed_sig = r.raw(64)?;
305 let dsa_sig = r.raw(DSA_SIG)?;
306 r.end()?;
307 if !hybrid_device_verify(&keys, &pop_message(th, &pt[..body_len]), ed_sig, dsa_sig) {
308 return Err(LinkError::Mismatch("device proof of possession failed".into()));
309 }
310 Ok(super::session::DeviceRequest { device_type, label, keys })
311}
312
313fn cert_check(cert: &[u8]) -> LR<DeviceCertInfo> {
323 let mut r = Rd::new(cert, "device cert");
324 if r.raw(3)? != CERT_MAGIC {
325 return Err(LinkError::Malformed("not a device certificate".into()));
326 }
327 let v = r.u8()?;
328 if v != CERT_VERSION {
329 return Err(LinkError::Malformed(format!("device cert version {v}")));
330 }
331 let user_id = label_from(r.b8(36)?, "user id")?;
332 let device_id = label_from(r.b8(36)?, "device id")?;
333 let account_secp256k1 = r.raw(SECP_PUB)?.to_vec();
334 let account_mldsa65 = r.raw(DSA_PUB)?.to_vec();
335 let keys = read_keys(&mut r)?;
336 let primary_sig = r.raw(SECP_SIG)?.to_vec();
337 let pq_sig = r.raw(DSA_SIG)?.to_vec();
338 let label_sealed = r.b16(LABEL_SEALED_MAX)?.to_vec();
339 let issued_at = r.u64()?;
340 r.end()?;
341 let wire_keys = wire_of(&keys);
342 verify_link_sigs(&user_id, &device_id, &wire_keys, &primary_sig, &pq_sig, &account_secp256k1, &account_mldsa65)?;
343 let account_address = address_of(&account_secp256k1, &account_mldsa65)?;
344 Ok(DeviceCertInfo {
345 user_id,
346 device_id,
347 keys,
348 wire_keys,
349 primary_sig,
350 pq_sig,
351 account_secp256k1,
352 account_mldsa65,
353 account_address,
354 label_sealed,
355 issued_at,
356 })
357}
358
359#[uniffi::export]
364pub fn device_cert_issue(
365 request: super::session::DeviceRequest,
366 user_id: String,
367 device_id: String,
368 account_secp256k1_private: Vec<u8>,
369 account_mldsa65_seed: Vec<u8>,
370 label_sealed: Vec<u8>,
371 issued_at: u64,
372) -> LR<Vec<u8>> {
373 check_type(request.device_type)?;
374 check_label(&request.label)?;
375 check_uuid(&user_id, "user id")?;
376 check_uuid(&device_id, "device id")?;
377 check_keys(&request.keys)?;
378 if label_sealed.len() > LABEL_SEALED_MAX {
379 return Err(LinkError::Malformed("label_sealed longer than 512 bytes".into()));
380 }
381 let secp_pub = p::secp256k1_public_key(account_secp256k1_private.clone())?;
382 let dsa_pub = p::mldsa65_public_key(account_mldsa65_seed.clone())?;
383 let wire = wire_of(&request.keys);
384 let m = link_message(&user_id, &device_id, &wire);
385 let primary_sig = p::secp256k1_sign_hash(p::sha256(m.as_bytes().to_vec()), account_secp256k1_private)?;
386 let pq_sig = p::mldsa65_sign(m.into_bytes(), account_mldsa65_seed)?;
387 let mut w = W::new();
388 w.raw(CERT_MAGIC).u8(CERT_VERSION).b8(user_id.as_bytes()).b8(device_id.as_bytes());
389 w.raw(&secp_pub).raw(&dsa_pub);
390 write_keys(&mut w, &request.keys);
391 w.raw(&primary_sig).raw(&pq_sig).b16(&label_sealed).u64(issued_at);
392 Ok(w.done())
393}
394
395#[uniffi::export]
397pub fn device_cert_verify(cert: Vec<u8>, expected_account_address: String) -> LR<DeviceCertInfo> {
398 let info = cert_check(&cert)?;
399 if info.account_address != expected_account_address.trim() {
400 return Err(LinkError::Mismatch("device certificate belongs to another account".into()));
401 }
402 Ok(info)
403}
404
405#[uniffi::export]
408pub fn device_cert_verify_for_device(cert: Vec<u8>, device_seed: Vec<u8>) -> LR<DeviceCertInfo> {
409 let info = cert_check(&cert)?;
410 let own = public_of(&device_secrets(&device_seed)?)?;
411 if info.keys != own {
412 return Err(LinkError::Mismatch("certificate was issued for other device keys".into()));
413 }
414 Ok(info)
415}
416
417#[uniffi::export]
422#[allow(clippy::too_many_arguments)]
423pub fn device_listing_verify(
424 user_id: String,
425 device_id: String,
426 wire_keys: Vec<DeviceKey>,
427 primary_sig: Vec<u8>,
428 pq_sig: Vec<u8>,
429 account_secp256k1: Vec<u8>,
430 account_mldsa65: Vec<u8>,
431 expected_account_address: String,
432) -> LR<DevicePublicKeys> {
433 if address_of(&account_secp256k1, &account_mldsa65)? != expected_account_address.trim() {
434 return Err(LinkError::Mismatch("account keys do not match the contact address".into()));
435 }
436 verify_link_sigs(&user_id, &device_id, &wire_keys, &primary_sig, &pq_sig, &account_secp256k1, &account_mldsa65)
437}
438
439#[uniffi::export]
441pub fn device_wire_keys(keys: DevicePublicKeys) -> LR<Vec<DeviceKey>> {
442 check_keys(&keys)?;
443 Ok(wire_of(&keys))
444}
445
446#[uniffi::export]
448pub fn device_keys_digest(wire_keys: Vec<DeviceKey>) -> Vec<u8> {
449 keys_digest_of(&wire_keys).to_vec()
450}
451
452#[uniffi::export]
454pub fn device_seed_generate() -> Vec<u8> {
455 p::os_random::<32>().to_vec()
456}
457
458#[uniffi::export]
460pub fn device_public_keys(device_seed: Vec<u8>) -> LR<DevicePublicKeys> {
461 public_of(&device_secrets(&device_seed)?)
462}
463
464#[uniffi::export]
467pub fn device_encryption_keys(device_seed: Vec<u8>) -> LR<DeviceEncryptionKeys> {
468 let s = device_secrets(&device_seed)?;
469 Ok(DeviceEncryptionKeys { x25519_private: s.x_priv.to_vec(), mlkem1024_seed: s.kem_seed.to_vec() })
470}
471
472fn device_sig_message(context: &str, message: &[u8]) -> LR<Vec<u8>> {
473 if context.is_empty() || context.len() > 64 {
474 return Err(LinkError::Malformed("signature context must be 1..64 bytes".into()));
475 }
476 let mut w = W::new();
477 w.raw(DOMAIN).raw(b"/device-sig").b8(context.as_bytes()).raw(message);
478 Ok(w.done())
479}
480
481#[uniffi::export]
483pub fn device_sign(device_seed: Vec<u8>, context: String, message: Vec<u8>) -> LR<Vec<u8>> {
484 let s = device_secrets(&device_seed)?;
485 let msg = device_sig_message(&context, &message)?;
486 let mut out = p::ed25519_sign(msg.clone(), s.ed_seed.to_vec())?;
487 out.extend(p::mldsa65_sign(msg, s.dsa_seed.to_vec())?);
488 Ok(out)
489}
490
491#[uniffi::export]
493pub fn device_verify(keys: DevicePublicKeys, context: String, message: Vec<u8>, signature: Vec<u8>) -> bool {
494 let Ok(msg) = device_sig_message(&context, &message) else { return false };
495 if signature.len() != 64 + DSA_SIG {
496 return false;
497 }
498 hybrid_device_verify(&keys, &msg, &signature[..64], &signature[64..])
499}
500
501#[uniffi::export]
509pub fn account_sync_key(account_x25519_private: Vec<u8>, account_mlkem_seed: Vec<u8>) -> LR<Vec<u8>> {
510 if account_x25519_private.len() != 32 || account_mlkem_seed.len() != 64 {
511 return Err(LinkError::Crypto("account keys must be 32 + 64 bytes".into()));
512 }
513 let ikm = Zeroizing::new([account_x25519_private, account_mlkem_seed].concat());
514 let mut out = vec![0u8; 32];
515 Hkdf::<Sha256>::new(Some(b"umbera-account-devices-v1"), &ikm)
516 .expand(b"sync-key", &mut out)
517 .expect("hkdf len");
518 Ok(out)
519}
520
521fn label_key(sync_key: &[u8]) -> LR<Zeroizing<[u8; 32]>> {
522 if sync_key.len() != 32 {
523 return Err(LinkError::Crypto("sync key must be 32 bytes".into()));
524 }
525 let mut k = Zeroizing::new([0u8; 32]);
526 Hkdf::<Sha256>::new(None, sync_key).expand(b"umbera-device-label-v1", k.as_mut()).expect("hkdf len");
527 Ok(k)
528}
529
530#[uniffi::export]
532pub fn device_label_seal(sync_key: Vec<u8>, device_id: String, device_type: u8, label: String) -> LR<Vec<u8>> {
533 check_type(device_type)?;
534 check_label(&label)?;
535 check_uuid(&device_id, "device id")?;
536 let k = label_key(&sync_key)?;
537 let mut pt = W::new();
538 pt.u8(device_type).b8(label.as_bytes());
539 let nonce: [u8; 12] = p::os_random();
540 let aad = sha256(&[DOMAIN, b"/device-label", device_id.as_bytes()]);
541 let ct = Aes256Gcm::new_from_slice(k.as_ref())
542 .expect("32-byte key")
543 .encrypt(&Nonce::try_from(&nonce[..]).expect("12-byte nonce"), Payload { msg: &pt.done(), aad: &aad })
544 .map_err(|_| LinkError::Crypto("aes-gcm encrypt".into()))?;
545 Ok([nonce.to_vec(), ct].concat())
546}
547
548#[uniffi::export]
549pub fn device_label_open(sync_key: Vec<u8>, device_id: String, sealed: Vec<u8>) -> LR<DeviceLabel> {
550 check_uuid(&device_id, "device id")?;
551 if sealed.len() < 12 + 16 || sealed.len() > LABEL_SEALED_MAX {
552 return Err(LinkError::Malformed("label_sealed length".into()));
553 }
554 let k = label_key(&sync_key)?;
555 let aad = sha256(&[DOMAIN, b"/device-label", device_id.as_bytes()]);
556 let pt = Aes256Gcm::new_from_slice(k.as_ref())
557 .expect("32-byte key")
558 .decrypt(&Nonce::try_from(&sealed[..12]).expect("12-byte nonce"), Payload { msg: &sealed[12..], aad: &aad })
559 .map_err(|_| LinkError::Mismatch("device label authentication failed".into()))?;
560 let mut r = Rd::new(&pt, "device label");
561 let device_type = r.u8()?;
562 check_type(device_type)?;
563 let label = label_from(r.b8(LABEL_MAX)?, "device label")?;
564 r.end()?;
565 Ok(DeviceLabel { device_type, label })
566}
567
568#[cfg(test)]
569pub(crate) fn link_message_for_tests(user_id: &str, device_id: &str, w: &[DeviceKey]) -> String {
570 link_message(user_id, device_id, w)
571}