Skip to main content

umbera_core/devlink/
session.rs

1// Desktop ↔ phone QR linking: hybrid key agreement, verification code, AEAD blobs.
2//
3// Flow (seq is a per-direction counter starting at zero):
4//   desktop : QR = {version, link_id, issued_at, desktop X25519, SHA-256(desktop ML-KEM), relay, checksum}
5//   dt→ph   : OFFER   seq 0  — desktop ML-KEM-1024 public key (1568 B), checked against the QR
6//   ph→dt   : ACCEPT  seq 0  — phone X25519 (ephemeral), ML-KEM ciphertext, phone MAC
7//   dt→ph   : CONFIRM seq 1  — desktop MAC
8//   both    : verification code (6 digits) on screens → the user taps "Link" on both
9//   then    : AEAD blobs (AES-256-GCM, per-direction key, nonce = seq,
10//             AAD = domain ‖ link_id ‖ seq ‖ kind ‖ direction)
11//
12// Keys: PRK = HKDF-Extract(salt = TH, IKM = X25519 ‖ ML-KEM), TH = SHA-256 of the transcript
13// (the whole QR, desktop ML-KEM key, phone X25519, ciphertext). PRK yields the direction keys,
14// the confirmation keys and the verification code. Changing any transcript byte yields different keys,
15// the confirmation fails and the verification code differs.
16
17use std::sync::{Arc, Mutex};
18
19use aes_gcm::{aead::Aead, aead::Payload, Aes256Gcm, KeyInit, Nonce};
20use base64::Engine as _;
21use hkdf::Hkdf;
22use hmac::{Hmac, Mac};
23use ml_kem::{Decapsulate as _, KeyExport as _};
24use sha2::Sha256;
25use zeroize::{Zeroize, Zeroizing};
26
27use super::codec::{label_from, Rd, W};
28use super::package::{PackageProgress, PackageReader, PackageWriter};
29use super::{cert, ct_eq, sha256, sha256_framed, LinkError, DOMAIN, LR};
30use crate::primitives::{mlkem_dk_from_seed, mlkem_ek_from_bytes, os_random};
31
32pub const LINK_VERSION: u8 = 1;
33/// QR lifetime: one minute, then a new one.
34pub const QR_TTL_SECS: u64 = 60;
35/// Allowed clock skew between desktop and phone (QR check on the phone).
36pub const MAX_CLOCK_SKEW_SECS: u64 = 300;
37/// How long we wait for "Link" to be tapped after the keys are agreed.
38pub const SAS_TTL_SECS: u64 = 180;
39pub const QR_TEXT_PREFIX: &str = "umbera-link:";
40const QR_MAGIC: &[u8; 2] = b"UL";
41const LINK_ID_MIN: usize = 16;
42const LINK_ID_MAX: usize = 32;
43const RELAY_MAX: usize = 200;
44const ABORT_MAX: usize = 256;
45
46pub const MLKEM_EK_LEN: usize = 1568;
47pub const MLKEM_CT_LEN: usize = 1568;
48
49// Blob kinds. The values are part of the format (the server does not interpret them, only stores them).
50pub const KIND_OFFER: u8 = 1;
51pub const KIND_ACCEPT: u8 = 2;
52pub const KIND_CONFIRM: u8 = 3;
53pub const KIND_DEVICE_REQUEST: u8 = 16;
54pub const KIND_DEVICE_CERT: u8 = 17;
55pub const KIND_MLS_JOIN_REQUESTS: u8 = 18;
56pub const KIND_MLS_JOIN_OFFERS: u8 = 19;
57pub const KIND_PACKAGE_HEADER: u8 = 32;
58pub const KIND_PACKAGE_PART: u8 = 33;
59pub const KIND_PACKAGE_END: u8 = 34;
60pub const KIND_PACKAGE_ACK: u8 = 35;
61pub const KIND_ABORT: u8 = 48;
62
63const DIR_PHONE_TO_PC: u8 = 1;
64const DIR_PC_TO_PHONE: u8 = 2;
65
66/// Blob that travels through the relay server. The server sees only these three fields.
67#[derive(uniffi::Record, Clone, Debug, PartialEq, Eq)]
68pub struct LinkBlob {
69    pub kind: u8,
70    pub seq: u64,
71    pub data: Vec<u8>,
72}
73
74#[derive(uniffi::Enum, Clone, Copy, Debug, PartialEq, Eq)]
75pub enum LinkRole {
76    /// New device (desktop): shows the QR.
77    Desktop,
78    /// Primary device (phone): scans the QR, signs the certificate, sends the package.
79    Phone,
80}
81
82/// Session state (exposed to the UI).
83#[derive(uniffi::Enum, Clone, Copy, Debug, PartialEq, Eq)]
84pub enum LinkState {
85    /// Desktop: QR shown, waiting for ACCEPT.
86    AwaitingAccept,
87    /// Phone: QR read, waiting for OFFER.
88    AwaitingOffer,
89    /// Phone: ACCEPT sent, waiting for CONFIRM.
90    AwaitingConfirm,
91    /// Keys agreed and confirmed, verification code on screen, waiting for "Link".
92    AwaitingSas,
93    /// The user confirmed the code: data may be transferred.
94    Established,
95    /// Session finished or destroyed (expired, tampering, cancelled). No secrets left in memory.
96    Closed,
97}
98
99/// Parsed content of the desktop's "sign my keys" request (the phone displays and signs it).
100#[derive(uniffi::Record, Clone, Debug, PartialEq, Eq)]
101pub struct DeviceRequest {
102    pub device_type: u8,
103    pub label: String,
104    pub keys: cert::DevicePublicKeys,
105}
106
107struct Keys {
108    send: Zeroizing<[u8; 32]>,
109    recv: Zeroizing<[u8; 32]>,
110    th: [u8; 32],
111    sas: String,
112}
113
114pub(crate) struct Inner {
115    role: LinkRole,
116    state: LinkState,
117    link_id: Vec<u8>,
118    relay: String,
119    issued_at: u64,
120    qr: Vec<u8>,
121    pc_x25519: [u8; 32],
122    ek_commit: [u8; 32],
123    // Desktop: ephemeral secrets until ACCEPT.
124    x_priv: Option<Zeroizing<[u8; 32]>>,
125    kem_seed: Option<Zeroizing<[u8; 64]>>,
126    ek: Vec<u8>,
127    // Phone: expected desktop MAC until CONFIRM.
128    expect_pc_tag: Option<Zeroizing<[u8; 32]>>,
129    keys: Option<Keys>,
130    send_seq: u64,
131    recv_seq: u64,
132    keyed_at: u64,
133    pkg_out: Option<PackageWriter>,
134    pkg_in: Option<PackageReader>,
135}
136
137/// Linking session, one side (desktop or phone). Secrets never leave the core and are wiped
138/// on close, on any mismatch and when the object is dropped.
139#[derive(uniffi::Object)]
140pub struct LinkSession {
141    inner: Mutex<Inner>,
142}
143
144/// No secrets: only the side and the state.
145impl std::fmt::Debug for LinkSession {
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        let g = self.lock();
148        write!(f, "LinkSession({:?}, {:?})", g.role, g.state)
149    }
150}
151
152impl Drop for Inner {
153    fn drop(&mut self) {
154        self.wipe();
155    }
156}
157
158fn kdf(prk: &Hkdf<Sha256>, label: &str) -> Zeroizing<[u8; 32]> {
159    let mut out = Zeroizing::new([0u8; 32]);
160    let info = [DOMAIN, label.as_bytes()].concat();
161    prk.expand(&info, out.as_mut()).expect("32 bytes is a valid HKDF length");
162    out
163}
164
165fn mac(key: &[u8; 32], th: &[u8; 32]) -> [u8; 32] {
166    let mut m = <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(key).expect("HMAC takes any key length");
167    m.update(th);
168    m.finalize().into_bytes().into()
169}
170
171/// Verification code: 8 bytes of PRK as a big-endian number modulo 10^6 (bias ~5·10^-14).
172fn sas_from(prk: &Hkdf<Sha256>) -> String {
173    let mut b = [0u8; 8];
174    let info = [DOMAIN, b"/sas".as_slice()].concat();
175    prk.expand(&info, &mut b).expect("8 bytes is a valid HKDF length");
176    format!("{:06}", u64::from_be_bytes(b) % 1_000_000)
177}
178
179pub(crate) fn ek_commitment(ek: &[u8]) -> [u8; 32] {
180    sha256(&[DOMAIN, b"/mlkem-ek", ek])
181}
182
183fn transcript(qr: &[u8], ek: &[u8], phone_x: &[u8; 32], ct: &[u8]) -> [u8; 32] {
184    let tag = [DOMAIN, b"/transcript".as_slice()].concat();
185    sha256_framed(&[&tag, qr, ek, phone_x, ct])
186}
187
188struct Derived {
189    p2d: Zeroizing<[u8; 32]>,
190    d2p: Zeroizing<[u8; 32]>,
191    phone_tag: [u8; 32],
192    pc_tag: [u8; 32],
193    sas: String,
194}
195
196fn derive(th: &[u8; 32], ss_x: &[u8; 32], ss_k: &[u8]) -> Derived {
197    let mut ikm = Zeroizing::new(Vec::with_capacity(64));
198    ikm.extend_from_slice(ss_x);
199    ikm.extend_from_slice(ss_k);
200    let prk = Hkdf::<Sha256>::new(Some(th), &ikm);
201    let ck_phone = kdf(&prk, "/confirm/phone");
202    let ck_pc = kdf(&prk, "/confirm/pc");
203    Derived {
204        p2d: kdf(&prk, "/key/phone->pc"),
205        d2p: kdf(&prk, "/key/pc->phone"),
206        phone_tag: mac(&ck_phone, th),
207        pc_tag: mac(&ck_pc, th),
208        sas: sas_from(&prk),
209    }
210}
211
212fn x25519(priv_: &[u8; 32], pub_: &[u8; 32]) -> LR<Zeroizing<[u8; 32]>> {
213    let ss = Zeroizing::new(x25519_dalek::x25519(*priv_, *pub_));
214    // A small-order point yields an all-zero shared secret: key substitution.
215    if ct_eq(ss.as_ref(), &[0u8; 32]) {
216        return Err(LinkError::Mismatch("x25519: low-order public key".into()));
217    }
218    Ok(ss)
219}
220
221fn blob_aad(link_id: &[u8], seq: u64, kind: u8, dir: u8) -> Vec<u8> {
222    let mut w = W::new();
223    w.raw(DOMAIN).raw(b"/blob").b8(link_id).u64(seq).u8(kind).u8(dir);
224    w.done()
225}
226
227fn nonce(seq: u64) -> [u8; 12] {
228    let mut n = [0u8; 12];
229    n[4..].copy_from_slice(&seq.to_be_bytes());
230    n
231}
232
233/// Which encrypted kinds a side may send.
234fn may_send(role: LinkRole, kind: u8) -> bool {
235    match role {
236        LinkRole::Desktop => matches!(
237            kind,
238            KIND_DEVICE_REQUEST | KIND_MLS_JOIN_OFFERS | KIND_PACKAGE_ACK | KIND_ABORT
239        ),
240        LinkRole::Phone => matches!(
241            kind,
242            KIND_DEVICE_CERT
243                | KIND_MLS_JOIN_REQUESTS
244                | KIND_PACKAGE_HEADER
245                | KIND_PACKAGE_PART
246                | KIND_PACKAGE_END
247                | KIND_ABORT
248        ),
249    }
250}
251
252fn peer(role: LinkRole) -> LinkRole {
253    match role {
254        LinkRole::Desktop => LinkRole::Phone,
255        LinkRole::Phone => LinkRole::Desktop,
256    }
257}
258
259fn dir_of(sender: LinkRole) -> u8 {
260    match sender {
261        LinkRole::Phone => DIR_PHONE_TO_PC,
262        LinkRole::Desktop => DIR_PC_TO_PHONE,
263    }
264}
265
266/// Parsed QR (magic, version, lengths and checksum verified).
267pub(crate) struct Qr {
268    pub link_id: Vec<u8>,
269    pub issued_at: u64,
270    pub pc_x25519: [u8; 32],
271    pub ek_commit: [u8; 32],
272    pub relay: String,
273}
274
275pub(crate) fn qr_encode(link_id: &[u8], issued_at: u64, pc_x: &[u8; 32], commit: &[u8; 32], relay: &str) -> Vec<u8> {
276    let mut w = W::new();
277    w.raw(QR_MAGIC).u8(LINK_VERSION).b8(link_id).u64(issued_at).raw(pc_x).raw(commit).b8(relay.as_bytes());
278    let mut body = w.done();
279    let sum = sha256(&[DOMAIN, b"/qr-check", &body]);
280    body.extend_from_slice(&sum[..4]);
281    body
282}
283
284pub(crate) fn qr_decode(bytes: &[u8]) -> LR<Qr> {
285    if bytes.len() < 4 {
286        return Err(LinkError::Malformed("qr: too short".into()));
287    }
288    let (body, sum) = bytes.split_at(bytes.len() - 4);
289    if !ct_eq(&sha256(&[DOMAIN, b"/qr-check", body])[..4], sum) {
290        return Err(LinkError::Malformed("qr: checksum".into()));
291    }
292    let mut r = Rd::new(body, "qr");
293    if r.raw(2)? != QR_MAGIC {
294        return Err(LinkError::Malformed("qr: not an Umbera link code".into()));
295    }
296    let v = r.u8()?;
297    if v != LINK_VERSION {
298        return Err(LinkError::Malformed(format!("qr: unsupported version {v}")));
299    }
300    let link_id = r.b8(LINK_ID_MAX)?.to_vec();
301    if link_id.len() < LINK_ID_MIN {
302        return Err(LinkError::Malformed("qr: link id too short".into()));
303    }
304    let issued_at = r.u64()?;
305    let pc_x25519 = r.arr::<32>()?;
306    let ek_commit = r.arr::<32>()?;
307    let relay = label_from(r.b8(RELAY_MAX)?, "qr relay")?;
308    r.end()?;
309    Ok(Qr { link_id, issued_at, pc_x25519, ek_commit, relay })
310}
311
312pub(crate) fn qr_text_of(qr: &[u8]) -> String {
313    format!("{QR_TEXT_PREFIX}{}", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(qr))
314}
315
316pub(crate) fn qr_bytes_of(text: &str) -> LR<Vec<u8>> {
317    let t = text.trim();
318    let b64 = t
319        .strip_prefix(QR_TEXT_PREFIX)
320        .ok_or_else(|| LinkError::Malformed("qr: not an Umbera link code".into()))?;
321    base64::engine::general_purpose::URL_SAFE_NO_PAD
322        .decode(b64)
323        .map_err(|_| LinkError::Malformed("qr: base64".into()))
324}
325
326impl Inner {
327    fn wipe(&mut self) {
328        self.x_priv = None;
329        self.kem_seed = None;
330        self.expect_pc_tag = None;
331        if let Some(k) = self.keys.as_mut() {
332            k.th.zeroize();
333            k.sas.zeroize();
334        }
335        self.keys = None;
336        self.pkg_out = None;
337        self.pkg_in = None;
338    }
339
340    fn close(&mut self) {
341        self.wipe();
342        self.state = LinkState::Closed;
343    }
344
345    /// Destroy the session and return an error, for any mismatch.
346    fn fail<T>(&mut self, e: LinkError) -> LR<T> {
347        self.close();
348        Err(e)
349    }
350
351    fn need(&self, role: LinkRole, st: LinkState, what: &str) -> LR<()> {
352        if self.role != role {
353            return Err(LinkError::State(format!("{what}: wrong side")));
354        }
355        if self.state != st {
356            return Err(LinkError::State(format!("{what}: session is {:?}", self.state)));
357        }
358        Ok(())
359    }
360
361    fn desktop_with(link_id: Vec<u8>, relay: String, now: u64, x_priv: [u8; 32], kem_seed: [u8; 64]) -> LR<Inner> {
362        if !(LINK_ID_MIN..=LINK_ID_MAX).contains(&link_id.len()) {
363            return Err(LinkError::Malformed(format!("link id must be {LINK_ID_MIN}..{LINK_ID_MAX} bytes")));
364        }
365        if relay.len() > RELAY_MAX {
366            return Err(LinkError::Malformed("relay hint too long".into()));
367        }
368        label_from(relay.as_bytes(), "relay hint")?;
369        let x_priv = Zeroizing::new(x_priv);
370        let kem_seed = Zeroizing::new(kem_seed);
371        let pc_x25519 = x25519_dalek::x25519(*x_priv, x25519_dalek::X25519_BASEPOINT_BYTES);
372        let dk = ml_kem::DecapsulationKey1024::from_seed((*kem_seed).into());
373        let ek = dk.encapsulation_key().to_bytes().to_vec();
374        let ek_commit = ek_commitment(&ek);
375        let qr = qr_encode(&link_id, now, &pc_x25519, &ek_commit, &relay);
376        Ok(Inner {
377            role: LinkRole::Desktop,
378            state: LinkState::AwaitingAccept,
379            link_id,
380            relay,
381            issued_at: now,
382            qr,
383            pc_x25519,
384            ek_commit,
385            x_priv: Some(x_priv),
386            kem_seed: Some(kem_seed),
387            ek,
388            expect_pc_tag: None,
389            keys: None,
390            // OFFER is desktop seq 0, CONFIRM is seq 1.
391            send_seq: 1,
392            recv_seq: 0,
393            keyed_at: 0,
394            pkg_out: None,
395            pkg_in: None,
396        })
397    }
398
399    fn phone_from(qr_text: &str, now: u64) -> LR<Inner> {
400        let qr = qr_bytes_of(qr_text)?;
401        let q = qr_decode(&qr)?;
402        check_qr_age(q.issued_at, now)?;
403        Ok(Inner {
404            role: LinkRole::Phone,
405            state: LinkState::AwaitingOffer,
406            link_id: q.link_id,
407            relay: q.relay,
408            issued_at: q.issued_at,
409            qr,
410            pc_x25519: q.pc_x25519,
411            ek_commit: q.ek_commit,
412            x_priv: None,
413            kem_seed: None,
414            ek: Vec::new(),
415            expect_pc_tag: None,
416            keys: None,
417            send_seq: 0,
418            recv_seq: 0,
419            keyed_at: 0,
420            pkg_out: None,
421            pkg_in: None,
422        })
423    }
424
425    fn phone_accept_with(&mut self, offer: &LinkBlob, now: u64, eph: [u8; 32], m: [u8; 32]) -> LR<LinkBlob> {
426        self.need(LinkRole::Phone, LinkState::AwaitingOffer, "accept")?;
427        if offer.kind != KIND_OFFER || offer.seq != 0 {
428            return self.fail(LinkError::Malformed(format!("expected OFFER seq 0, got kind {} seq {}", offer.kind, offer.seq)));
429        }
430        if let Err(e) = check_qr_age(self.issued_at, now) {
431            return self.fail(e);
432        }
433        if offer.data.len() != MLKEM_EK_LEN || !ct_eq(&ek_commitment(&offer.data), &self.ek_commit) {
434            return self.fail(LinkError::Mismatch("ML-KEM key does not match the QR code".into()));
435        }
436        let ek = match mlkem_ek_from_bytes(&offer.data) {
437            Ok(k) => k,
438            Err(_) => return self.fail(LinkError::Mismatch("ML-KEM key failed FIPS 203 validation".into())),
439        };
440        let eph = Zeroizing::new(eph);
441        let phone_x = x25519_dalek::x25519(*eph, x25519_dalek::X25519_BASEPOINT_BYTES);
442        let ss_x = match x25519(&eph, &self.pc_x25519) {
443            Ok(s) => s,
444            Err(e) => return self.fail(e),
445        };
446        let (ct, ss_k) = ek.encapsulate_deterministic(&m.into());
447        let ss_k = Zeroizing::new(ss_k.to_vec());
448        let th = transcript(&self.qr, &offer.data, &phone_x, &ct);
449        let d = derive(&th, &ss_x, &ss_k);
450        let mut w = W::new();
451        w.u8(LINK_VERSION).raw(&phone_x).raw(&ct).raw(&d.phone_tag);
452        self.ek = offer.data.clone();
453        self.expect_pc_tag = Some(Zeroizing::new(d.pc_tag));
454        self.keys = Some(Keys { send: d.p2d, recv: d.d2p, th, sas: d.sas });
455        self.state = LinkState::AwaitingConfirm;
456        self.recv_seq = 1;
457        self.send_seq = 1;
458        Ok(LinkBlob { kind: KIND_ACCEPT, seq: 0, data: w.done() })
459    }
460
461    fn desktop_accept(&mut self, accept: &LinkBlob, now: u64) -> LR<LinkBlob> {
462        self.need(LinkRole::Desktop, LinkState::AwaitingAccept, "accept")?;
463        if now.saturating_sub(self.issued_at) > QR_TTL_SECS {
464            return self.fail(LinkError::Expired("QR code is older than 60 seconds".into()));
465        }
466        if accept.kind != KIND_ACCEPT || accept.seq != 0 {
467            return self.fail(LinkError::Malformed(format!("expected ACCEPT seq 0, got kind {} seq {}", accept.kind, accept.seq)));
468        }
469        let parsed = (|| {
470            let mut r = Rd::new(&accept.data, "accept");
471            let v = r.u8()?;
472            if v != LINK_VERSION {
473                return Err(LinkError::Malformed(format!("accept: version {v}")));
474            }
475            let px = r.arr::<32>()?;
476            let ct = r.arr::<MLKEM_CT_LEN>()?;
477            let tag = r.arr::<32>()?;
478            r.end()?;
479            Ok((px, ct, tag))
480        })();
481        let (phone_x, ct, tag) = match parsed {
482            Ok(p) => p,
483            Err(e) => return self.fail(e),
484        };
485        // Take the ephemeral secrets out of the session: whatever happens next, they are gone.
486        let x_priv = self.x_priv.take().expect("present in AwaitingAccept");
487        let kem_seed = self.kem_seed.take().expect("present in AwaitingAccept");
488        let ss_x = match x25519(&x_priv, &phone_x) {
489            Ok(s) => s,
490            Err(e) => return self.fail(e),
491        };
492        let dk = match mlkem_dk_from_seed(kem_seed.as_ref()) {
493            Ok(k) => k,
494            Err(e) => return self.fail(e.into()),
495        };
496        // ML-KEM implicit rejection: a corrupted ciphertext yields a random secret → the MAC will not match.
497        let ss_k = Zeroizing::new(dk.decapsulate(&ct.into()).to_vec());
498        let th = transcript(&self.qr, &self.ek, &phone_x, &ct);
499        let d = derive(&th, &ss_x, &ss_k);
500        if !ct_eq(&d.phone_tag, &tag) {
501            return self.fail(LinkError::Mismatch("phone key confirmation failed".into()));
502        }
503        self.keys = Some(Keys { send: d.d2p, recv: d.p2d, th, sas: d.sas });
504        self.state = LinkState::AwaitingSas;
505        self.keyed_at = now;
506        self.recv_seq = 1;
507        let seq = self.send_seq;
508        self.send_seq += 1;
509        Ok(LinkBlob { kind: KIND_CONFIRM, seq, data: d.pc_tag.to_vec() })
510    }
511
512    fn phone_confirm(&mut self, confirm: &LinkBlob, now: u64) -> LR<()> {
513        self.need(LinkRole::Phone, LinkState::AwaitingConfirm, "confirm")?;
514        if confirm.kind != KIND_CONFIRM || confirm.seq != 1 {
515            return self.fail(LinkError::Malformed(format!("expected CONFIRM seq 1, got kind {} seq {}", confirm.kind, confirm.seq)));
516        }
517        let want = self.expect_pc_tag.take().expect("present in AwaitingConfirm");
518        if !ct_eq(want.as_ref(), &confirm.data) {
519            return self.fail(LinkError::Mismatch("desktop key confirmation failed".into()));
520        }
521        self.state = LinkState::AwaitingSas;
522        self.keyed_at = now;
523        self.recv_seq = 2;
524        Ok(())
525    }
526
527    fn confirm_sas(&mut self, now: u64) -> LR<()> {
528        if self.state != LinkState::AwaitingSas {
529            return Err(LinkError::State(format!("confirm_sas: session is {:?}", self.state)));
530        }
531        if now.saturating_sub(self.keyed_at) > SAS_TTL_SECS {
532            return self.fail(LinkError::Expired("verification code was not confirmed in time".into()));
533        }
534        self.state = LinkState::Established;
535        Ok(())
536    }
537
538    pub(crate) fn seal(&mut self, kind: u8, pt: &[u8]) -> LR<LinkBlob> {
539        let ok_state = match self.state {
540            LinkState::Established => true,
541            LinkState::AwaitingSas => kind == KIND_ABORT,
542            _ => false,
543        };
544        if !ok_state {
545            return Err(LinkError::State(format!("seal: session is {:?}", self.state)));
546        }
547        if !may_send(self.role, kind) {
548            return Err(LinkError::State(format!("seal: kind {kind} is not ours to send")));
549        }
550        if kind == KIND_ABORT && pt.len() > ABORT_MAX {
551            return Err(LinkError::Malformed("abort reason too long".into()));
552        }
553        let keys = self.keys.as_ref().expect("keyed state");
554        let seq = self.send_seq;
555        let aad = blob_aad(&self.link_id, seq, kind, dir_of(self.role));
556        let ct = Aes256Gcm::new_from_slice(keys.send.as_ref())
557            .expect("32-byte key")
558            .encrypt(&Nonce::try_from(&nonce(seq)[..]).expect("12-byte nonce"), Payload { msg: pt, aad: &aad })
559            .map_err(|_| LinkError::Crypto("aes-gcm encrypt".into()))?;
560        self.send_seq += 1;
561        if kind == KIND_ABORT {
562            self.close();
563        }
564        Ok(LinkBlob { kind, seq, data: ct })
565    }
566
567    /// Decrypt the peer's next blob. A replay yields Replay (session intact); anything else
568    /// invalid (gap, wrong kind, corruption) destroys the session.
569    pub(crate) fn open_any(&mut self, blob: &LinkBlob) -> LR<Zeroizing<Vec<u8>>> {
570        let ok_state = match self.state {
571            LinkState::Established => true,
572            LinkState::AwaitingSas => blob.kind == KIND_ABORT,
573            _ => false,
574        };
575        if !ok_state {
576            return Err(LinkError::State(format!("open: session is {:?}", self.state)));
577        }
578        if blob.seq < self.recv_seq {
579            return Err(LinkError::Replay(format!("seq {} already received (next {})", blob.seq, self.recv_seq)));
580        }
581        if blob.seq > self.recv_seq {
582            return self.fail(LinkError::Mismatch(format!("seq gap: got {}, expected {}", blob.seq, self.recv_seq)));
583        }
584        let sender = peer(self.role);
585        if !may_send(sender, blob.kind) {
586            return self.fail(LinkError::Mismatch(format!("kind {} cannot come from the other side", blob.kind)));
587        }
588        let keys = self.keys.as_ref().expect("keyed state");
589        let aad = blob_aad(&self.link_id, blob.seq, blob.kind, dir_of(sender));
590        let pt = Aes256Gcm::new_from_slice(keys.recv.as_ref())
591            .expect("32-byte key")
592            .decrypt(&Nonce::try_from(&nonce(blob.seq)[..]).expect("12-byte nonce"), Payload { msg: &blob.data, aad: &aad });
593        let pt = match pt {
594            Ok(p) => Zeroizing::new(p),
595            Err(_) => return self.fail(LinkError::Mismatch("blob authentication failed".into())),
596        };
597        self.recv_seq += 1;
598        if blob.kind == KIND_ABORT {
599            self.close();
600        }
601        Ok(pt)
602    }
603
604    fn th(&self) -> LR<[u8; 32]> {
605        self.keys.as_ref().map(|k| k.th).ok_or_else(|| LinkError::State("no keys".into()))
606    }
607}
608
609fn check_qr_age(issued_at: u64, now: u64) -> LR<()> {
610    if issued_at > now.saturating_add(MAX_CLOCK_SKEW_SECS) {
611        return Err(LinkError::Expired("QR code is from the future (check the clock)".into()));
612    }
613    if now.saturating_sub(issued_at) > QR_TTL_SECS + MAX_CLOCK_SKEW_SECS {
614        return Err(LinkError::Expired("QR code has expired".into()));
615    }
616    Ok(())
617}
618
619impl LinkSession {
620    fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
621        // A panic inside the call must not leave the session open: a poisoned mutex
622        // is recovered, but the state is already closed or untouched (parsing does not panic).
623        self.inner.lock().unwrap_or_else(|p| p.into_inner())
624    }
625
626    pub(crate) fn desktop_with(link_id: Vec<u8>, relay: String, now: u64, x_priv: [u8; 32], kem_seed: [u8; 64]) -> LR<Arc<Self>> {
627        Ok(Arc::new(LinkSession { inner: Mutex::new(Inner::desktop_with(link_id, relay, now, x_priv, kem_seed)?) }))
628    }
629
630    pub(crate) fn phone_accept_with(&self, offer: &LinkBlob, now: u64, eph: [u8; 32], m: [u8; 32]) -> LR<LinkBlob> {
631        self.lock().phone_accept_with(offer, now, eph, m)
632    }
633
634    #[cfg(test)]
635    pub(crate) fn lock_for_tests(&self) -> std::sync::MutexGuard<'_, Inner> {
636        self.lock()
637    }
638
639    #[cfg(test)]
640    pub(crate) fn package_digest_for_tests(&self) -> Option<Vec<u8>> {
641        self.lock().pkg_out.as_ref().and_then(|w| w.digest())
642    }
643
644    #[cfg(test)]
645    pub(crate) fn transcript_hash(&self) -> LR<[u8; 32]> {
646        self.lock().th()
647    }
648
649    pub(crate) fn package_begin_with(&self, include_history: bool, package_id: [u8; 16]) -> LR<LinkBlob> {
650        let mut g = self.lock();
651        g.need(LinkRole::Phone, LinkState::Established, "package_begin")?;
652        if g.pkg_out.is_some() {
653            return Err(LinkError::State("package already started".into()));
654        }
655        let (w, header) = PackageWriter::begin(package_id, include_history);
656        let blob = g.seal(KIND_PACKAGE_HEADER, &header)?;
657        g.pkg_out = Some(w);
658        Ok(blob)
659    }
660
661    pub(crate) fn device_request_with(&self, device_seed: &[u8], device_type: u8, label: &str) -> LR<LinkBlob> {
662        let mut g = self.lock();
663        g.need(LinkRole::Desktop, LinkState::Established, "device_request")?;
664        let th = g.th()?;
665        let pt = cert::device_request_encode(&th, device_seed, device_type, label)?;
666        g.seal(KIND_DEVICE_REQUEST, &pt)
667    }
668}
669
670#[uniffi::export]
671impl LinkSession {
672    /// Desktop: new session with ephemeral keys. `link_id` is 16..32 bytes (issued by the server or
673    /// random), `relay_hint` is the relay address for the phone (part of the transcript),
674    /// `now_secs` is the desktop's Unix time.
675    #[uniffi::constructor]
676    pub fn desktop(link_id: Vec<u8>, relay_hint: String, now_secs: u64) -> LR<Arc<Self>> {
677        Self::desktop_with(link_id, relay_hint, now_secs, os_random(), os_random())
678    }
679
680    /// Phone: session from the QR text. Checks format, checksum and validity window (with clock tolerance).
681    #[uniffi::constructor]
682    pub fn phone(qr_text: String, now_secs: u64) -> LR<Arc<Self>> {
683        Ok(Arc::new(LinkSession { inner: Mutex::new(Inner::phone_from(&qr_text, now_secs)?) }))
684    }
685
686    pub fn role(&self) -> LinkRole {
687        self.lock().role
688    }
689
690    pub fn state(&self) -> LinkState {
691        self.lock().state
692    }
693
694    pub fn link_id(&self) -> Vec<u8> {
695        self.lock().link_id.clone()
696    }
697
698    pub fn relay_hint(&self) -> String {
699        self.lock().relay.clone()
700    }
701
702    pub fn issued_at(&self) -> u64 {
703        self.lock().issued_at
704    }
705
706    /// Desktop: text for the QR ("umbera-link:" + base64url).
707    pub fn qr_text(&self) -> LR<String> {
708        let g = self.lock();
709        g.need(LinkRole::Desktop, LinkState::AwaitingAccept, "qr_text")?;
710        Ok(qr_text_of(&g.qr))
711    }
712
713    /// Desktop: OFFER blob (ML-KEM key). May be resent; it is always the same.
714    pub fn offer(&self) -> LR<LinkBlob> {
715        let g = self.lock();
716        g.need(LinkRole::Desktop, LinkState::AwaitingAccept, "offer")?;
717        Ok(LinkBlob { kind: KIND_OFFER, seq: 0, data: g.ek.clone() })
718    }
719
720    /// Phone: check OFFER against the QR, encapsulate, return ACCEPT.
721    pub fn phone_accept(&self, offer: LinkBlob, now_secs: u64) -> LR<LinkBlob> {
722        self.phone_accept_with(&offer, now_secs, os_random(), os_random())
723    }
724
725    /// Desktop: accept ACCEPT (no later than 60 s after the QR was shown), verify the phone's confirmation,
726    /// return CONFIRM. Any mismatch destroys the session.
727    pub fn desktop_accept(&self, accept: LinkBlob, now_secs: u64) -> LR<LinkBlob> {
728        self.lock().desktop_accept(&accept, now_secs)
729    }
730
731    /// Phone: verify the desktop's CONFIRM.
732    pub fn phone_confirm(&self, confirm: LinkBlob, now_secs: u64) -> LR<()> {
733        self.lock().phone_confirm(&confirm, now_secs)
734    }
735
736    /// Verification code (6 digits), after mutual key confirmation.
737    pub fn sas(&self) -> LR<String> {
738        let g = self.lock();
739        match g.state {
740            LinkState::AwaitingSas | LinkState::Established => Ok(g.keys.as_ref().expect("keyed").sas.clone()),
741            s => Err(LinkError::State(format!("sas: session is {s:?}"))),
742        }
743    }
744
745    /// The user saw matching codes and tapped "Link".
746    pub fn confirm_sas(&self, now_secs: u64) -> LR<()> {
747        self.lock().confirm_sas(now_secs)
748    }
749
750    /// Encrypt a blob of one's own kind (see KIND_*). The package goes only through package_*.
751    pub fn seal(&self, kind: u8, plaintext: Vec<u8>) -> LR<LinkBlob> {
752        if matches!(kind, KIND_PACKAGE_HEADER | KIND_PACKAGE_PART | KIND_PACKAGE_END | KIND_DEVICE_REQUEST) {
753            return Err(LinkError::State(format!("seal: kind {kind} has its own method")));
754        }
755        self.lock().seal(kind, &plaintext)
756    }
757
758    /// Decrypt a peer blob (except package parts and the device request).
759    pub fn open(&self, blob: LinkBlob) -> LR<Vec<u8>> {
760        if matches!(blob.kind, KIND_PACKAGE_HEADER | KIND_PACKAGE_PART | KIND_PACKAGE_END | KIND_DEVICE_REQUEST) {
761            return Err(LinkError::State(format!("open: kind {} has its own method", blob.kind)));
762        }
763        Ok(self.lock().open_any(&blob)?.to_vec())
764    }
765
766    /// Desktop: "sign my keys" request: device public keys from `device_seed` and
767    /// proof of possession (Ed25519 + ML-DSA-65 signatures over the linking transcript).
768    pub fn device_request(&self, device_seed: Vec<u8>, device_type: u8, label: String) -> LR<LinkBlob> {
769        self.device_request_with(&device_seed, device_type, &label)
770    }
771
772    /// Phone: open the desktop's request and verify the proof of possession.
773    pub fn open_device_request(&self, blob: LinkBlob) -> LR<DeviceRequest> {
774        let mut g = self.lock();
775        g.need(LinkRole::Phone, LinkState::Established, "open_device_request")?;
776        if blob.kind != KIND_DEVICE_REQUEST {
777            return Err(LinkError::State(format!("open_device_request: kind {}", blob.kind)));
778        }
779        let th = g.th()?;
780        let pt = g.open_any(&blob)?;
781        match cert::device_request_decode(&th, &pt) {
782            Ok(r) => Ok(r),
783            Err(e) => g.fail(e),
784        }
785    }
786
787    /// Phone: start a transfer package. `include_history`: the user chose "with history".
788    pub fn package_begin(&self, include_history: bool) -> LR<LinkBlob> {
789        self.package_begin_with(include_history, os_random())
790    }
791
792    /// Phone: add a record. Returns parts ready to send (may be empty).
793    pub fn package_add(&self, section: u8, id: Vec<u8>, body: Vec<u8>) -> LR<Vec<LinkBlob>> {
794        let mut g = self.lock();
795        g.need(LinkRole::Phone, LinkState::Established, "package_add")?;
796        let w = g.pkg_out.as_mut().ok_or_else(|| LinkError::State("package not started".into()))?;
797        let parts = w.add(section, &id, &body)?;
798        parts.iter().map(|p| g.seal(KIND_PACKAGE_PART, p)).collect()
799    }
800
801    /// Phone: finish the package: the last parts and END with the final checksum.
802    pub fn package_finish(&self) -> LR<Vec<LinkBlob>> {
803        let mut g = self.lock();
804        g.need(LinkRole::Phone, LinkState::Established, "package_finish")?;
805        let w = g.pkg_out.as_mut().ok_or_else(|| LinkError::State("package not started".into()))?;
806        let (parts, end) = w.finish()?;
807        let mut out: Vec<LinkBlob> = parts.iter().map(|p| g.seal(KIND_PACKAGE_PART, p)).collect::<LR<_>>()?;
808        out.push(g.seal(KIND_PACKAGE_END, &end)?);
809        Ok(out)
810    }
811
812    /// Desktop: accept HEADER/PART/END. Records are returned as they arrive; commit them to the database
813    /// only once `done` (the final checksum matched).
814    pub fn package_receive(&self, blob: LinkBlob) -> LR<PackageProgress> {
815        let mut g = self.lock();
816        g.need(LinkRole::Desktop, LinkState::Established, "package_receive")?;
817        if !matches!(blob.kind, KIND_PACKAGE_HEADER | KIND_PACKAGE_PART | KIND_PACKAGE_END) {
818            return Err(LinkError::State(format!("package_receive: kind {}", blob.kind)));
819        }
820        // AEAD and ordering first (a replay is REPLAY, harmless to the session), then semantics.
821        let pt = g.open_any(&blob)?;
822        if blob.kind == KIND_PACKAGE_HEADER && g.pkg_in.is_some() {
823            return g.fail(LinkError::Mismatch("second package header".into()));
824        }
825        if blob.kind != KIND_PACKAGE_HEADER && g.pkg_in.is_none() {
826            return g.fail(LinkError::Mismatch("package part before header".into()));
827        }
828        let res = match blob.kind {
829            KIND_PACKAGE_HEADER => PackageReader::begin(&pt).map(|(r, p)| {
830                g.pkg_in = Some(r);
831                p
832            }),
833            KIND_PACKAGE_PART => g.pkg_in.as_mut().expect("checked").part(&pt),
834            _ => g.pkg_in.as_mut().expect("checked").end(&pt),
835        };
836        match res {
837            Ok(p) => Ok(p),
838            Err(e) => g.fail(e),
839        }
840    }
841
842    /// Desktop: "package received in full" acknowledgement (package checksum inside), after done.
843    pub fn package_ack(&self) -> LR<LinkBlob> {
844        let mut g = self.lock();
845        g.need(LinkRole::Desktop, LinkState::Established, "package_ack")?;
846        let digest = g
847            .pkg_in
848            .as_ref()
849            .and_then(|r| r.digest())
850            .ok_or_else(|| LinkError::State("package is not complete".into()))?;
851        g.seal(KIND_PACKAGE_ACK, &digest)
852    }
853
854    /// Phone: verify the desktop's acknowledgement: the package checksum must match the one sent.
855    pub fn package_check_ack(&self, blob: LinkBlob) -> LR<()> {
856        let mut g = self.lock();
857        g.need(LinkRole::Phone, LinkState::Established, "package_check_ack")?;
858        let want = g
859            .pkg_out
860            .as_ref()
861            .and_then(|w| w.digest())
862            .ok_or_else(|| LinkError::State("package is not finished".into()))?;
863        if blob.kind != KIND_PACKAGE_ACK {
864            return Err(LinkError::State(format!("package_check_ack: kind {}", blob.kind)));
865        }
866        let got = g.open_any(&blob)?;
867        if !ct_eq(&got, &want) {
868            return g.fail(LinkError::Mismatch("package digest acknowledged by the desktop differs".into()));
869        }
870        Ok(())
871    }
872
873    /// Cancel and wipe secrets (without notifying the peer; to notify, seal(KIND_ABORT)).
874    /// Not named `close`: in the Kotlin bindings that name is taken by AutoCloseable.
875    pub fn wipe(&self) {
876        self.lock().close();
877    }
878}
879