Skip to main content

teter_common/
account.rs

1//! The account protocol, on the relay's `/account` path: one request, one
2//! reply, per connection (JSON text frames, like the rest of the protocol).
3//!
4//! The password never leaves the client (model C, decided in #57): the client
5//! derives a master key from it (Argon2id, with the parameters and salt the
6//! account carries), and from the master key an auth key, which it presents,
7//! and a wrapping key, which wraps the account's private keys before they
8//! reach the relay. The relay keeps a hash of the auth key, the public keys
9//! and the wrapped private keys, and can read none of what they protect.
10
11use serde::{Deserialize, Serialize};
12
13/// The relay path the account protocol is served on.
14pub const PATH: &str = "/account";
15
16/// The longest account name, in bytes.
17pub const MAX_NAME: usize = 64;
18
19/// Whether `name` can be an account's name: 1 to [`MAX_NAME`] ASCII letters,
20/// digits, `.`, `_` or `-`, starting with a letter or a digit.
21pub fn valid_name(name: &str) -> bool {
22    !name.is_empty()
23        && name.len() <= MAX_NAME
24        && name
25            .bytes()
26            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
27        && name
28            .bytes()
29            .next()
30            .is_some_and(|b| b.is_ascii_alphanumeric())
31}
32
33/// The version of a salt's layout.
34pub const SALT_VERSION: u8 = 1;
35
36/// The random part of a salt, in bytes.
37pub const SALT_RANDOM_LEN: usize = 16;
38
39/// A salt's length: the version, the Argon2id parameters (memory in KiB,
40/// passes, lanes, each 4 bytes big-endian) and the random bytes.
41pub const SALT_LEN: usize = 1 + 12 + SALT_RANDOM_LEN;
42
43/// Argon2id's cost parameters, carried in an account's salt.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct KdfParams {
46    /// Memory, in KiB.
47    pub memory_kib: u32,
48    /// Passes over the memory.
49    pub passes: u32,
50    /// Lanes.
51    pub lanes: u32,
52}
53
54/// Argon2id's parameters for new accounts: 64 MiB, 3 passes, 1 lane (the
55/// second recommended set of RFC 9106, for memory-constrained devices).
56pub const DEFAULT_KDF: KdfParams = KdfParams {
57    memory_kib: 64 * 1024,
58    passes: 3,
59    lanes: 1,
60};
61
62/// The least Argon2id cost a client accepts, or a relay takes at signup:
63/// [`DEFAULT_KDF`]. A relay is not trusted (#57): one that answered a salt
64/// with a lower cost would make the auth key cheap to guess the password
65/// from.
66pub const MIN_KDF: KdfParams = DEFAULT_KDF;
67
68/// The most Argon2id cost a client accepts: 1 GiB, 10 passes, 8 lanes. A
69/// relay that answered more would have the client run out of memory or
70/// spin.
71pub const MAX_KDF: KdfParams = KdfParams {
72    memory_kib: 1024 * 1024,
73    passes: 10,
74    lanes: 8,
75};
76
77/// Whether `params` is within [`MIN_KDF`] and [`MAX_KDF`].
78pub fn acceptable_kdf(params: KdfParams) -> bool {
79    (MIN_KDF.memory_kib..=MAX_KDF.memory_kib).contains(&params.memory_kib)
80        && (MIN_KDF.passes..=MAX_KDF.passes).contains(&params.passes)
81        && (MIN_KDF.lanes..=MAX_KDF.lanes).contains(&params.lanes)
82}
83
84/// A salt for `params` with `random` as its random bytes.
85pub fn salt_blob(params: KdfParams, random: &[u8; SALT_RANDOM_LEN]) -> Vec<u8> {
86    let mut blob = Vec::with_capacity(SALT_LEN);
87    blob.push(SALT_VERSION);
88    blob.extend_from_slice(&params.memory_kib.to_be_bytes());
89    blob.extend_from_slice(&params.passes.to_be_bytes());
90    blob.extend_from_slice(&params.lanes.to_be_bytes());
91    blob.extend_from_slice(random);
92    blob
93}
94
95/// The parameters and random bytes of `salt`, if it has this build's layout.
96pub fn parse_salt(salt: &[u8]) -> Option<(KdfParams, &[u8])> {
97    let (header, random) = salt.split_at_checked(13)?;
98    let [version, m0, m1, m2, m3, t0, t1, t2, t3, p0, p1, p2, p3] = *header else {
99        return None;
100    };
101    (version == SALT_VERSION && random.len() == SALT_RANDOM_LEN).then_some((
102        KdfParams {
103            memory_kib: u32::from_be_bytes([m0, m1, m2, m3]),
104            passes: u32::from_be_bytes([t0, t1, t2, t3]),
105            lanes: u32::from_be_bytes([p0, p1, p2, p3]),
106        },
107        random,
108    ))
109}
110
111/// A request to the relay's account service.
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113#[non_exhaustive]
114pub enum AccountRequest {
115    /// The salt (with its key derivation parameters) of account `name`, to
116    /// derive its keys before logging in. A name with no account gets a salt
117    /// all the same, always the same for that name, so the answer does not
118    /// tell which names have accounts.
119    Salt {
120        /// The account's name.
121        name: String,
122    },
123    /// Makes account `name`.
124    Signup {
125        /// The account's name.
126        name: String,
127        /// The salt and key derivation parameters the client used.
128        salt: Vec<u8>,
129        /// The auth key the client derived; the relay keeps only its hash.
130        auth_key: Vec<u8>,
131        /// The account's public keys.
132        public_keys: Vec<u8>,
133        /// The account's private keys, wrapped by the client.
134        wrapped_keys: Vec<u8>,
135        /// The invite the relay's admin gave (#103): signup is closed
136        /// without one.
137        #[serde(default)]
138        invite: String,
139    },
140    /// Logs in to account `name` with the auth key derived from its password.
141    Login {
142        /// The account's name.
143        name: String,
144        /// The auth key.
145        auth_key: Vec<u8>,
146        /// This device's Ed25519 public key (#158): the login's token works
147        /// only in a [`AccountRequest::Proven`] this key signed. A login
148        /// without one is refused.
149        #[serde(default)]
150        device_key: Vec<u8>,
151    },
152    /// Ends the login session of `token`.
153    Logout {
154        /// The login token.
155        token: String,
156    },
157    /// Makes a registration token for the logged-in account: the relay keeps
158    /// the hash of its enrollment secret (the client keeps the secret), with
159    /// its expiry and uses.
160    TokenCreate {
161        /// The login token.
162        login: String,
163        /// The SHA-256 of the enrollment secret.
164        secret_hash: Vec<u8>,
165        /// Seconds until it stops working (at most [`MAX_TOKEN_LIFETIME`]).
166        expires_in: u64,
167        /// How many machines it registers (1 to [`MAX_TOKEN_USES`]).
168        uses: u32,
169    },
170    /// The registration tokens of the logged-in account.
171    TokenList {
172        /// The login token.
173        login: String,
174    },
175    /// Revokes a registration token of the logged-in account.
176    TokenRevoke {
177        /// The login token.
178        login: String,
179        /// The token's ID ([`TokenInfo::id`]).
180        id: String,
181    },
182    /// The public keys of the account a registration token belongs to, for
183    /// the machine to check against the token's fingerprint before it
184    /// registers. Uses nothing of the token.
185    TokenKeys {
186        /// The token's enrollment secret.
187        secret: Vec<u8>,
188    },
189    /// Registers a machine with a registration token, taking one of its
190    /// uses.
191    Register {
192        /// The token's enrollment secret.
193        secret: Vec<u8>,
194        /// The machine's Ed25519 public key, which it authenticates with.
195        machine_key: Vec<u8>,
196        /// The machine's display name, sealed to the account's X25519 key.
197        sealed_name: Vec<u8>,
198        /// Its proof it holds the token (#133): HMAC-SHA256 of
199        /// [`binding_bytes`] under the token's binding key, which never
200        /// reaches the relay. The device that made the token checks it
201        /// before it approves the machine.
202        #[serde(default)]
203        binding: Vec<u8>,
204    },
205    /// Approves a machine of the logged-in account (#133): the account's
206    /// signature of [`cert_bytes`], which devices check before they trust
207    /// the machine's key, name and records.
208    MachineApprove {
209        /// The login token.
210        login: String,
211        /// The machine's ID.
212        id: String,
213        /// The account's signature.
214        cert: Vec<u8>,
215    },
216    /// The logged-in account's machines.
217    MachineList {
218        /// The login token.
219        login: String,
220    },
221    /// Removes a machine of the logged-in account: it can no longer connect.
222    MachineRemove {
223        /// The login token.
224        login: String,
225        /// The machine's ID.
226        id: String,
227    },
228    /// The logged-in account's machines, each with the relay session it is
229    /// served on now (if it is connected) and its sessions' records (#87):
230    /// all a device needs to attach, nothing carried by hand.
231    Sessions {
232        /// The login token.
233        login: String,
234    },
235    /// Changes the logged-in account's password (#89): its new salt, auth
236    /// key and private keys wrapped under the new password, proven by the
237    /// current password's auth key. Every login of the account ends; the
238    /// reply holds a new one.
239    PasswordChange {
240        /// The login token.
241        login: String,
242        /// The current password's auth key.
243        auth_key: Vec<u8>,
244        /// The new salt and key derivation parameters.
245        salt: Vec<u8>,
246        /// The new password's auth key.
247        new_auth_key: Vec<u8>,
248        /// The private keys wrapped under the new password.
249        wrapped_keys: Vec<u8>,
250    },
251    /// Replaces the logged-in account's keys (#89): `rotation`, signed by the
252    /// current signing key, the new private keys wrapped under the password,
253    /// and each approved machine's name and approval under the new keys,
254    /// proven by the password's auth key. Every login of the account ends;
255    /// the reply holds a new one.
256    KeyRotate {
257        /// The login token.
258        login: String,
259        /// The password's auth key.
260        auth_key: Vec<u8>,
261        /// The rotation.
262        rotation: KeyRotation,
263        /// The new private keys, wrapped.
264        wrapped_keys: Vec<u8>,
265        /// The machines, re-approved.
266        machines: Vec<MachineRekey>,
267    },
268    /// A machine removes itself, proving it holds its key.
269    Unregister {
270        /// The machine's ID.
271        machine: String,
272        /// When it signed (Unix seconds); the relay takes it within
273        /// [`UNREGISTER_WINDOW`] of its own clock.
274        at: i64,
275        /// Its signature of [`unregister_message`].
276        signature: Vec<u8>,
277    },
278    /// A request that carries a login token, signed by the device the login
279    /// was made on (#158): a token without its device's signature is
280    /// refused, so a copied token, or a copied account file, works nowhere
281    /// else.
282    Proven {
283        /// The request, as the JSON text that was signed.
284        request: String,
285        /// When it was signed (Unix seconds); the relay takes it within
286        /// [`PROOF_WINDOW`] of its own clock, and each nonce once.
287        at: i64,
288        /// [`PROOF_NONCE_LEN`] random bytes.
289        nonce: Vec<u8>,
290        /// The device key's signature of [`proof_bytes`].
291        signature: Vec<u8>,
292    },
293}
294
295impl AccountRequest {
296    /// The login token this request uses, if it is one that needs a login
297    /// (`Logout`'s token included).
298    pub fn login_token(&self) -> Option<&str> {
299        match self {
300            Self::Logout { token } => Some(token),
301            Self::TokenCreate { login, .. }
302            | Self::TokenList { login }
303            | Self::TokenRevoke { login, .. }
304            | Self::MachineApprove { login, .. }
305            | Self::MachineList { login }
306            | Self::MachineRemove { login, .. }
307            | Self::Sessions { login }
308            | Self::PasswordChange { login, .. }
309            | Self::KeyRotate { login, .. } => Some(login),
310            Self::Salt { .. }
311            | Self::Signup { .. }
312            | Self::Login { .. }
313            | Self::TokenKeys { .. }
314            | Self::Register { .. }
315            | Self::Unregister { .. }
316            | Self::Proven { .. } => None,
317        }
318    }
319}
320
321/// How far a [`AccountRequest::Proven`]'s time may be from the relay's, in
322/// seconds.
323pub const PROOF_WINDOW: i64 = 300;
324
325/// The length of a [`AccountRequest::Proven`]'s nonce.
326pub const PROOF_NONCE_LEN: usize = 16;
327
328/// What a device signs to prove a request (#158): this prefix, the time,
329/// the nonce, and the request's JSON text.
330pub fn proof_bytes(request: &str, at: i64, nonce: &[u8]) -> Vec<u8> {
331    let mut bytes = b"teter-device-proof-v1 ".to_vec();
332    bytes.extend_from_slice(&at.to_be_bytes());
333    bytes.extend_from_slice(&u32::try_from(nonce.len()).unwrap_or(u32::MAX).to_be_bytes());
334    bytes.extend_from_slice(nonce);
335    bytes.extend_from_slice(request.as_bytes());
336    bytes
337}
338
339/// The reason a request with a login token but without its device's
340/// signature is refused (#158).
341pub const NOT_PROVEN: &str = "this login needs this device's signature: log in again (with a teter \
342                              that signs its requests)";
343
344/// The reason a login without a device key is refused (#158).
345pub const NO_DEVICE_KEY: &str = "a login needs this device's key: upgrade teter";
346
347/// A change of the account's keys (#89): the new public keys, signed by the
348/// old signing key. Machines pinned to the old keys follow it; a relay cannot
349/// make one without the account's old private key.
350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
351pub struct KeyRotation {
352    /// The public keys it replaces (X25519, then Ed25519).
353    pub old_keys: Vec<u8>,
354    /// The public keys that replace them.
355    pub new_keys: Vec<u8>,
356    /// When it was signed (Unix seconds).
357    pub at: i64,
358    /// The old signing key's signature of [`rotation_bytes`].
359    pub signature: Vec<u8>,
360}
361
362/// What the old signing key signs for a [`KeyRotation`].
363pub fn rotation_bytes(old_keys: &[u8], new_keys: &[u8], at: i64) -> Vec<u8> {
364    let mut bytes = b"teter-key-rotation-v1 ".to_vec();
365    bytes.extend_from_slice(
366        &u32::try_from(old_keys.len())
367            .unwrap_or(u32::MAX)
368            .to_be_bytes(),
369    );
370    bytes.extend_from_slice(old_keys);
371    bytes.extend_from_slice(new_keys);
372    bytes.extend_from_slice(&at.to_be_bytes());
373    bytes
374}
375
376/// The most key rotations a relay keeps per account, newest last: a machine
377/// pinned to keys older than these registers again.
378pub const MAX_ROTATIONS: usize = 64;
379
380/// A machine's name and approval under the account's new keys, which the
381/// device that rotates them gives (#89).
382#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
383pub struct MachineRekey {
384    /// The machine's ID.
385    pub id: String,
386    /// Its display name, sealed to the new keys.
387    pub sealed_name: Vec<u8>,
388    /// The new keys' approval of it ([`cert_bytes`]).
389    pub cert: Vec<u8>,
390}
391
392/// How far a machine's `Unregister` time may be from the relay's, in seconds.
393pub const UNREGISTER_WINDOW: i64 = 300;
394
395/// What a machine signs to unregister: this prefix, its ID, and the time.
396pub fn unregister_message(machine: &str, at: i64) -> Vec<u8> {
397    let mut message = b"teter-unregister-v1 ".to_vec();
398    message.extend_from_slice(machine.as_bytes());
399    message.extend_from_slice(&at.to_be_bytes());
400    message
401}
402
403/// A machine as the relay lists it to its account.
404#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
405pub struct MachineInfo {
406    /// Its ID.
407    pub id: String,
408    /// Its display name, sealed to the account.
409    pub sealed_name: Vec<u8>,
410    /// When it last connected (Unix seconds), if it has.
411    pub last_seen: Option<i64>,
412    /// Its public key (#133).
413    #[serde(default)]
414    pub public_key: Vec<u8>,
415    /// Its proof it held the token (see [`AccountRequest::Register`]).
416    #[serde(default)]
417    pub binding: Vec<u8>,
418    /// The account's approval, empty before one.
419    #[serde(default)]
420    pub cert: Vec<u8>,
421}
422
423/// The longest a registration token works: 30 days.
424pub const MAX_TOKEN_LIFETIME: u64 = 30 * 24 * 3600;
425
426/// The most machines one registration token registers.
427pub const MAX_TOKEN_USES: u32 = 100;
428
429/// A registration token as the relay lists it: never its secret.
430#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
431pub struct TokenInfo {
432    /// Its ID: the SHA-256 of its secret, hex.
433    pub id: String,
434    /// When it was made (Unix seconds).
435    pub created: i64,
436    /// When it stops working (Unix seconds).
437    pub expires: i64,
438    /// How many more machines it registers.
439    pub uses_left: i64,
440}
441
442/// The relay's reply to an [`AccountRequest`].
443#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
444#[non_exhaustive]
445pub enum AccountReply {
446    /// The salt asked for.
447    Salt {
448        /// The salt and key derivation parameters.
449        salt: Vec<u8>,
450    },
451    /// The account was made.
452    SignedUp,
453    /// Logged in: a token for the relay, and the account's keys, the private
454    /// ones still wrapped.
455    LoggedIn {
456        /// The login token.
457        token: String,
458        /// The account's public keys.
459        public_keys: Vec<u8>,
460        /// The account's private keys, wrapped.
461        wrapped_keys: Vec<u8>,
462    },
463    /// The login session ended (or there was none).
464    LoggedOut,
465    /// The registration token was made.
466    TokenCreated,
467    /// The account's registration tokens, oldest first.
468    Tokens {
469        /// The tokens.
470        tokens: Vec<TokenInfo>,
471        /// The relay's clock (Unix seconds), which the expiries are on; 0
472        /// from a relay that does not send it.
473        #[serde(default)]
474        now: i64,
475    },
476    /// Whether a registration token was revoked (`false`: no such token).
477    TokenRevoked {
478        /// Whether it was.
479        revoked: bool,
480    },
481    /// The public keys of a registration token's account.
482    AccountKeys {
483        /// The account's public keys.
484        public_keys: Vec<u8>,
485    },
486    /// The machine is registered.
487    Registered {
488        /// Its ID, which it says hello with.
489        machine: String,
490    },
491    /// The account's machines.
492    Machines {
493        /// The machines.
494        machines: Vec<MachineInfo>,
495    },
496    /// Whether a machine was removed (`false`: no such machine).
497    MachineRemoved {
498        /// Whether it was.
499        removed: bool,
500    },
501    /// Whether a machine was approved (`false`: no such machine).
502    MachineApproved {
503        /// Whether it was.
504        approved: bool,
505    },
506    /// The account's machines and their sessions.
507    Sessions {
508        /// The machines.
509        machines: Vec<MachineSessions>,
510        /// The account's limits on this relay (#104); `None` from a relay
511        /// older than them.
512        #[serde(default, skip_serializing_if = "Option::is_none")]
513        limits: Option<AccountLimits>,
514    },
515    /// The password was changed: the new login (every other ended).
516    PasswordChanged {
517        /// The login token.
518        token: String,
519    },
520    /// The keys were replaced: the new login (every other ended).
521    KeysRotated {
522        /// The login token.
523        token: String,
524    },
525    /// Refused, and why. A failed login says only that the name or the
526    /// password is wrong, never which.
527    Refused {
528        /// Why.
529        reason: String,
530    },
531}
532
533/// The reason a login is refused, whatever was wrong.
534pub const WRONG_LOGIN: &str = "wrong account name or password";
535
536/// The reason an account request is refused when its login token is not
537/// (or no longer) a login.
538pub const NOT_LOGGED_IN: &str = "not logged in (or the login expired): run teter login";
539
540/// The prefix of a registration token's text.
541pub const REGISTRATION_PREFIX: &str = "teter-reg1";
542
543/// A registration token, as the logged-in user hands it to the machine to
544/// register: the relay's URL, the enrollment secret, and the fingerprint of
545/// the account's public keys, which the machine checks the keys the relay
546/// gives it against (#86), so a relay cannot swap the account's keys.
547#[derive(Clone, PartialEq, Eq)]
548pub struct Registration {
549    /// The relay's URL.
550    pub relay: String,
551    /// The enrollment secret.
552    pub secret: [u8; 32],
553    /// The fingerprint of the account's public keys.
554    pub fingerprint: [u8; 16],
555}
556
557impl std::fmt::Debug for Registration {
558    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
559        f.debug_struct("Registration")
560            .field("relay", &self.relay)
561            .finish_non_exhaustive()
562    }
563}
564
565impl Registration {
566    /// Its text: `teter-reg1.<relay, hex>.<secret, hex>.<fingerprint, hex>`.
567    pub fn to_text(&self) -> String {
568        format!(
569            "{REGISTRATION_PREFIX}.{}.{}.{}",
570            hex(self.relay.as_bytes()),
571            hex(&self.secret),
572            hex(&self.fingerprint)
573        )
574    }
575
576    /// The token `text` holds, if it is one.
577    pub fn parse(text: &str) -> Option<Self> {
578        let mut parts = text.trim().split('.');
579        let (Some(prefix), Some(relay), Some(secret), Some(fingerprint), None) = (
580            parts.next(),
581            parts.next(),
582            parts.next(),
583            parts.next(),
584            parts.next(),
585        ) else {
586            return None;
587        };
588        if prefix != REGISTRATION_PREFIX {
589            return None;
590        }
591        Some(Self {
592            relay: String::from_utf8(unhex(relay)?).ok()?,
593            secret: unhex(secret)?.try_into().ok()?,
594            fingerprint: unhex(fingerprint)?.try_into().ok()?,
595        })
596    }
597}
598
599/// `bytes`, hex.
600pub fn hex(bytes: &[u8]) -> String {
601    bytes.iter().map(|b| format!("{b:02x}")).collect()
602}
603
604/// The bytes `text` holds in hex, if it is hex.
605pub fn unhex(text: &str) -> Option<Vec<u8>> {
606    if !text.len().is_multiple_of(2) || !text.bytes().all(|b| b.is_ascii_hexdigit()) {
607        return None;
608    }
609    text.as_bytes()
610        .chunks(2)
611        .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok())
612        .collect()
613}
614
615/// The reason a relay refuses a machine it does not know (removed from its
616/// account, or never registered there): the one refusal after which a link
617/// stops for good (#138), not after a passing failure.
618pub const MACHINE_UNKNOWN: &str = "this relay does not know this machine (removed from its account, or registered with another relay?)";
619
620/// The reason a relay refuses a machine's proof: a signature its registered
621/// key did not make (#147). It begins as the other authentication failures
622/// do, which links before it looked for.
623pub const PROOF_REFUSED: &str = "authentication failed: the machine's proof does not match the key registered for it (another machine's key?)";
624
625/// The reason a registration token is refused, whatever was wrong with it
626/// (unknown, expired, used up, revoked).
627pub const BAD_TOKEN: &str = "this registration token does not work (unknown, expired, used up or \
628     revoked; or made by a teter older than 26.11.3: make a new one)";
629
630/// An account's limits on its relay (#104), each `None` for none, and what
631/// it used this month: what a device checks before it asks for more (a new
632/// session past the limit would run on its machine, but the relay would keep
633/// no record of it).
634#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
635pub struct AccountLimits {
636    /// Machines registered.
637    pub machines: Option<u64>,
638    /// Sessions kept, over all its machines.
639    pub sessions: Option<u64>,
640    /// Bytes a second its machines and devices send through the relay.
641    pub rate: Option<u64>,
642    /// Bytes a month (UTC) they send.
643    pub monthly: Option<u64>,
644    /// Bytes they sent this month.
645    pub used: u64,
646}
647
648impl AccountLimits {
649    /// Why a new session is refused when the account keeps `kept` sessions
650    /// already, if it is.
651    #[must_use]
652    pub fn no_room_for_a_session(&self, kept: usize) -> Option<String> {
653        let at = self.sessions?;
654        (u64::try_from(kept).unwrap_or(u64::MAX) >= at).then(|| {
655            format!(
656                "this account has {kept} sessions, the most its relay allows it ({at}): end one \
657                 (teter kill machine:session), or ask the relay's admin for more"
658            )
659        })
660    }
661}
662
663/// A machine of the account and its sessions, as [`AccountReply::Sessions`]
664/// gives them.
665#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
666pub struct MachineSessions {
667    /// The machine's ID.
668    pub id: String,
669    /// Its display name, sealed to the account.
670    pub sealed_name: Vec<u8>,
671    /// Its public key (Ed25519), which signs its command challenges (#88);
672    /// empty from a relay older than that.
673    #[serde(default)]
674    pub public_key: Vec<u8>,
675    /// The account's approval of the machine (#133), empty before one.
676    #[serde(default)]
677    pub cert: Vec<u8>,
678    /// The relay session it is served on now, and the token a frontend joins
679    /// it with; `None` while it is not connected.
680    pub relay: Option<(crate::SessionId, String)>,
681    /// Its sessions.
682    pub sessions: Vec<SessionRecordInfo>,
683}
684
685/// One of a machine's sessions: its channel, its name and key sealed to the
686/// account.
687#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
688pub struct SessionRecordInfo {
689    /// The channel it travels on inside the machine's relay session.
690    pub channel: String,
691    /// The relay session that serves it now, and the token to join it;
692    /// `None` while no link of its machine serves it.
693    pub relay: Option<(crate::SessionId, String)>,
694    /// Its name, sealed to the account.
695    pub sealed_name: Vec<u8>,
696    /// Its end-to-end secret, sealed to the account for its channel.
697    pub sealed_key: Vec<u8>,
698    /// The machine's signature of [`record_bytes`] (#133).
699    #[serde(default)]
700    pub signature: Vec<u8>,
701    /// How many frontends are attached to it now (#135); `None` from a
702    /// relay older than the field.
703    #[serde(default)]
704    pub clients: Option<u32>,
705}
706
707/// What a machine signs to show it held its registration token: its key and
708/// its sealed name (#133).
709pub fn binding_bytes(machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
710    let mut bytes = b"teter-machine-bind-v1 ".to_vec();
711    bytes.extend_from_slice(machine_key);
712    bytes.extend_from_slice(sealed_name);
713    bytes
714}
715
716/// What the account signs to approve machine `id` (#133): its key and its
717/// sealed name, so a relay can neither swap a machine's key nor move its
718/// name.
719pub fn cert_bytes(id: &str, machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
720    let mut bytes = b"teter-machine-cert-v1 ".to_vec();
721    bytes.extend_from_slice(id.as_bytes());
722    bytes.push(0);
723    bytes.extend_from_slice(machine_key);
724    bytes.extend_from_slice(sealed_name);
725    bytes
726}
727
728/// What a machine's display name is sealed to the account with (#86).
729pub const MACHINE_NAME_INFO: &[u8] = b"machine name";
730
731/// What the name of machine `machine`'s session on `channel` is sealed to
732/// the account with (#87): bound to both, so a relay cannot move a name onto
733/// another record.
734pub fn session_name_info(machine: &str, channel: &str) -> Vec<u8> {
735    format!("session name {machine} {channel}").into_bytes()
736}
737
738/// What a session's end-to-end secret is sealed to the account with (#87),
739/// bound to its channel.
740pub fn session_key_info(channel: &str) -> Vec<u8> {
741    let mut info = b"session key ".to_vec();
742    info.extend_from_slice(channel.as_bytes());
743    info
744}
745
746/// What machine `machine` signs for its session on `channel` (#133).
747pub fn record_bytes(
748    machine: &str,
749    channel: &str,
750    sealed_name: &[u8],
751    sealed_key: &[u8],
752) -> Vec<u8> {
753    let mut bytes = b"teter-record-v1 ".to_vec();
754    bytes.extend_from_slice(machine.as_bytes());
755    bytes.push(0);
756    bytes.extend_from_slice(channel.as_bytes());
757    bytes.push(0);
758    bytes.extend_from_slice(
759        &u32::try_from(sealed_name.len())
760            .unwrap_or(u32::MAX)
761            .to_be_bytes(),
762    );
763    bytes.extend_from_slice(sealed_name);
764    bytes.extend_from_slice(sealed_key);
765    bytes
766}
767
768#[cfg(test)]
769mod proof_tests {
770    use super::*;
771
772    #[test]
773    fn requests_with_a_login_name_their_token_and_the_others_none() {
774        let list = AccountRequest::MachineList {
775            login: "tok".into(),
776        };
777        assert_eq!(list.login_token(), Some("tok"));
778        let logout = AccountRequest::Logout {
779            token: "out".into(),
780        };
781        assert_eq!(logout.login_token(), Some("out"));
782        let salt = AccountRequest::Salt { name: "n".into() };
783        assert_eq!(salt.login_token(), None);
784    }
785
786    #[test]
787    fn proof_bytes_bind_time_nonce_and_request() {
788        let base = proof_bytes("{}", 1, &[0; PROOF_NONCE_LEN]);
789        assert!(base.starts_with(b"teter-device-proof-v1 "));
790        assert_ne!(base, proof_bytes("{} ", 1, &[0; PROOF_NONCE_LEN]));
791        assert_ne!(base, proof_bytes("{}", 2, &[0; PROOF_NONCE_LEN]));
792        assert_ne!(base, proof_bytes("{}", 1, &[1; PROOF_NONCE_LEN]));
793        // The nonce's length is in it: bytes cannot move between nonce and request.
794        assert_ne!(proof_bytes("b{}", 1, b"a"), proof_bytes("{}", 1, b"ab"));
795    }
796
797    #[test]
798    fn a_login_from_before_device_keys_reads_with_none() {
799        let old = r#"{"Login":{"name":"n","auth_key":[1]}}"#;
800        let request: AccountRequest = serde_json::from_str(old).unwrap_or_else(|e| panic!("{e}"));
801        assert_eq!(
802            request,
803            AccountRequest::Login {
804                name: "n".into(),
805                auth_key: vec![1],
806                device_key: Vec::new(),
807            }
808        );
809    }
810}