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    },
147    /// Ends the login session of `token`.
148    Logout {
149        /// The login token.
150        token: String,
151    },
152    /// Makes a registration token for the logged-in account: the relay keeps
153    /// the hash of its enrollment secret (the client keeps the secret), with
154    /// its expiry and uses.
155    TokenCreate {
156        /// The login token.
157        login: String,
158        /// The SHA-256 of the enrollment secret.
159        secret_hash: Vec<u8>,
160        /// Seconds until it stops working (at most [`MAX_TOKEN_LIFETIME`]).
161        expires_in: u64,
162        /// How many machines it registers (1 to [`MAX_TOKEN_USES`]).
163        uses: u32,
164    },
165    /// The registration tokens of the logged-in account.
166    TokenList {
167        /// The login token.
168        login: String,
169    },
170    /// Revokes a registration token of the logged-in account.
171    TokenRevoke {
172        /// The login token.
173        login: String,
174        /// The token's ID ([`TokenInfo::id`]).
175        id: String,
176    },
177    /// The public keys of the account a registration token belongs to, for
178    /// the machine to check against the token's fingerprint before it
179    /// registers. Uses nothing of the token.
180    TokenKeys {
181        /// The token's enrollment secret.
182        secret: Vec<u8>,
183    },
184    /// Registers a machine with a registration token, taking one of its
185    /// uses.
186    Register {
187        /// The token's enrollment secret.
188        secret: Vec<u8>,
189        /// The machine's Ed25519 public key, which it authenticates with.
190        machine_key: Vec<u8>,
191        /// The machine's display name, sealed to the account's X25519 key.
192        sealed_name: Vec<u8>,
193        /// Its proof it holds the token (#133): HMAC-SHA256 of
194        /// [`binding_bytes`] under the token's binding key, which never
195        /// reaches the relay. The device that made the token checks it
196        /// before it approves the machine.
197        #[serde(default)]
198        binding: Vec<u8>,
199    },
200    /// Approves a machine of the logged-in account (#133): the account's
201    /// signature of [`cert_bytes`], which devices check before they trust
202    /// the machine's key, name and records.
203    MachineApprove {
204        /// The login token.
205        login: String,
206        /// The machine's ID.
207        id: String,
208        /// The account's signature.
209        cert: Vec<u8>,
210    },
211    /// The logged-in account's machines.
212    MachineList {
213        /// The login token.
214        login: String,
215    },
216    /// Removes a machine of the logged-in account: it can no longer connect.
217    MachineRemove {
218        /// The login token.
219        login: String,
220        /// The machine's ID.
221        id: String,
222    },
223    /// The logged-in account's machines, each with the relay session it is
224    /// served on now (if it is connected) and its sessions' records (#87):
225    /// all a device needs to attach, nothing carried by hand.
226    Sessions {
227        /// The login token.
228        login: String,
229    },
230    /// Changes the logged-in account's password (#89): its new salt, auth
231    /// key and private keys wrapped under the new password, proven by the
232    /// current password's auth key. Every login of the account ends; the
233    /// reply holds a new one.
234    PasswordChange {
235        /// The login token.
236        login: String,
237        /// The current password's auth key.
238        auth_key: Vec<u8>,
239        /// The new salt and key derivation parameters.
240        salt: Vec<u8>,
241        /// The new password's auth key.
242        new_auth_key: Vec<u8>,
243        /// The private keys wrapped under the new password.
244        wrapped_keys: Vec<u8>,
245    },
246    /// Replaces the logged-in account's keys (#89): `rotation`, signed by the
247    /// current signing key, the new private keys wrapped under the password,
248    /// and each approved machine's name and approval under the new keys,
249    /// proven by the password's auth key. Every login of the account ends;
250    /// the reply holds a new one.
251    KeyRotate {
252        /// The login token.
253        login: String,
254        /// The password's auth key.
255        auth_key: Vec<u8>,
256        /// The rotation.
257        rotation: KeyRotation,
258        /// The new private keys, wrapped.
259        wrapped_keys: Vec<u8>,
260        /// The machines, re-approved.
261        machines: Vec<MachineRekey>,
262    },
263    /// A machine removes itself, proving it holds its key.
264    Unregister {
265        /// The machine's ID.
266        machine: String,
267        /// When it signed (Unix seconds); the relay takes it within
268        /// [`UNREGISTER_WINDOW`] of its own clock.
269        at: i64,
270        /// Its signature of [`unregister_message`].
271        signature: Vec<u8>,
272    },
273}
274
275/// A change of the account's keys (#89): the new public keys, signed by the
276/// old signing key. Machines pinned to the old keys follow it; a relay cannot
277/// make one without the account's old private key.
278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279pub struct KeyRotation {
280    /// The public keys it replaces (X25519, then Ed25519).
281    pub old_keys: Vec<u8>,
282    /// The public keys that replace them.
283    pub new_keys: Vec<u8>,
284    /// When it was signed (Unix seconds).
285    pub at: i64,
286    /// The old signing key's signature of [`rotation_bytes`].
287    pub signature: Vec<u8>,
288}
289
290/// What the old signing key signs for a [`KeyRotation`].
291pub fn rotation_bytes(old_keys: &[u8], new_keys: &[u8], at: i64) -> Vec<u8> {
292    let mut bytes = b"teter-key-rotation-v1 ".to_vec();
293    bytes.extend_from_slice(
294        &u32::try_from(old_keys.len())
295            .unwrap_or(u32::MAX)
296            .to_be_bytes(),
297    );
298    bytes.extend_from_slice(old_keys);
299    bytes.extend_from_slice(new_keys);
300    bytes.extend_from_slice(&at.to_be_bytes());
301    bytes
302}
303
304/// The most key rotations a relay keeps per account, newest last: a machine
305/// pinned to keys older than these registers again.
306pub const MAX_ROTATIONS: usize = 64;
307
308/// A machine's name and approval under the account's new keys, which the
309/// device that rotates them gives (#89).
310#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
311pub struct MachineRekey {
312    /// The machine's ID.
313    pub id: String,
314    /// Its display name, sealed to the new keys.
315    pub sealed_name: Vec<u8>,
316    /// The new keys' approval of it ([`cert_bytes`]).
317    pub cert: Vec<u8>,
318}
319
320/// How far a machine's `Unregister` time may be from the relay's, in seconds.
321pub const UNREGISTER_WINDOW: i64 = 300;
322
323/// What a machine signs to unregister: this prefix, its ID, and the time.
324pub fn unregister_message(machine: &str, at: i64) -> Vec<u8> {
325    let mut message = b"teter-unregister-v1 ".to_vec();
326    message.extend_from_slice(machine.as_bytes());
327    message.extend_from_slice(&at.to_be_bytes());
328    message
329}
330
331/// A machine as the relay lists it to its account.
332#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
333pub struct MachineInfo {
334    /// Its ID.
335    pub id: String,
336    /// Its display name, sealed to the account.
337    pub sealed_name: Vec<u8>,
338    /// When it last connected (Unix seconds), if it has.
339    pub last_seen: Option<i64>,
340    /// Its public key (#133).
341    #[serde(default)]
342    pub public_key: Vec<u8>,
343    /// Its proof it held the token (see [`AccountRequest::Register`]).
344    #[serde(default)]
345    pub binding: Vec<u8>,
346    /// The account's approval, empty before one.
347    #[serde(default)]
348    pub cert: Vec<u8>,
349}
350
351/// The longest a registration token works: 30 days.
352pub const MAX_TOKEN_LIFETIME: u64 = 30 * 24 * 3600;
353
354/// The most machines one registration token registers.
355pub const MAX_TOKEN_USES: u32 = 100;
356
357/// A registration token as the relay lists it: never its secret.
358#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
359pub struct TokenInfo {
360    /// Its ID: the SHA-256 of its secret, hex.
361    pub id: String,
362    /// When it was made (Unix seconds).
363    pub created: i64,
364    /// When it stops working (Unix seconds).
365    pub expires: i64,
366    /// How many more machines it registers.
367    pub uses_left: i64,
368}
369
370/// The relay's reply to an [`AccountRequest`].
371#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
372#[non_exhaustive]
373pub enum AccountReply {
374    /// The salt asked for.
375    Salt {
376        /// The salt and key derivation parameters.
377        salt: Vec<u8>,
378    },
379    /// The account was made.
380    SignedUp,
381    /// Logged in: a token for the relay, and the account's keys, the private
382    /// ones still wrapped.
383    LoggedIn {
384        /// The login token.
385        token: String,
386        /// The account's public keys.
387        public_keys: Vec<u8>,
388        /// The account's private keys, wrapped.
389        wrapped_keys: Vec<u8>,
390    },
391    /// The login session ended (or there was none).
392    LoggedOut,
393    /// The registration token was made.
394    TokenCreated,
395    /// The account's registration tokens, oldest first.
396    Tokens {
397        /// The tokens.
398        tokens: Vec<TokenInfo>,
399        /// The relay's clock (Unix seconds), which the expiries are on; 0
400        /// from a relay that does not send it.
401        #[serde(default)]
402        now: i64,
403    },
404    /// Whether a registration token was revoked (`false`: no such token).
405    TokenRevoked {
406        /// Whether it was.
407        revoked: bool,
408    },
409    /// The public keys of a registration token's account.
410    AccountKeys {
411        /// The account's public keys.
412        public_keys: Vec<u8>,
413    },
414    /// The machine is registered.
415    Registered {
416        /// Its ID, which it says hello with.
417        machine: String,
418    },
419    /// The account's machines.
420    Machines {
421        /// The machines.
422        machines: Vec<MachineInfo>,
423    },
424    /// Whether a machine was removed (`false`: no such machine).
425    MachineRemoved {
426        /// Whether it was.
427        removed: bool,
428    },
429    /// Whether a machine was approved (`false`: no such machine).
430    MachineApproved {
431        /// Whether it was.
432        approved: bool,
433    },
434    /// The account's machines and their sessions.
435    Sessions {
436        /// The machines.
437        machines: Vec<MachineSessions>,
438        /// The account's limits on this relay (#104); `None` from a relay
439        /// older than them.
440        #[serde(default, skip_serializing_if = "Option::is_none")]
441        limits: Option<AccountLimits>,
442    },
443    /// The password was changed: the new login (every other ended).
444    PasswordChanged {
445        /// The login token.
446        token: String,
447    },
448    /// The keys were replaced: the new login (every other ended).
449    KeysRotated {
450        /// The login token.
451        token: String,
452    },
453    /// Refused, and why. A failed login says only that the name or the
454    /// password is wrong, never which.
455    Refused {
456        /// Why.
457        reason: String,
458    },
459}
460
461/// The reason a login is refused, whatever was wrong.
462pub const WRONG_LOGIN: &str = "wrong account name or password";
463
464/// The reason an account request is refused when its login token is not
465/// (or no longer) a login.
466pub const NOT_LOGGED_IN: &str = "not logged in (or the login expired): run teter login";
467
468/// The prefix of a registration token's text.
469pub const REGISTRATION_PREFIX: &str = "teter-reg1";
470
471/// A registration token, as the logged-in user hands it to the machine to
472/// register: the relay's URL, the enrollment secret, and the fingerprint of
473/// the account's public keys, which the machine checks the keys the relay
474/// gives it against (#86), so a relay cannot swap the account's keys.
475#[derive(Clone, PartialEq, Eq)]
476pub struct Registration {
477    /// The relay's URL.
478    pub relay: String,
479    /// The enrollment secret.
480    pub secret: [u8; 32],
481    /// The fingerprint of the account's public keys.
482    pub fingerprint: [u8; 16],
483}
484
485impl std::fmt::Debug for Registration {
486    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
487        f.debug_struct("Registration")
488            .field("relay", &self.relay)
489            .finish_non_exhaustive()
490    }
491}
492
493impl Registration {
494    /// Its text: `teter-reg1.<relay, hex>.<secret, hex>.<fingerprint, hex>`.
495    pub fn to_text(&self) -> String {
496        format!(
497            "{REGISTRATION_PREFIX}.{}.{}.{}",
498            hex(self.relay.as_bytes()),
499            hex(&self.secret),
500            hex(&self.fingerprint)
501        )
502    }
503
504    /// The token `text` holds, if it is one.
505    pub fn parse(text: &str) -> Option<Self> {
506        let mut parts = text.trim().split('.');
507        let (Some(prefix), Some(relay), Some(secret), Some(fingerprint), None) = (
508            parts.next(),
509            parts.next(),
510            parts.next(),
511            parts.next(),
512            parts.next(),
513        ) else {
514            return None;
515        };
516        if prefix != REGISTRATION_PREFIX {
517            return None;
518        }
519        Some(Self {
520            relay: String::from_utf8(unhex(relay)?).ok()?,
521            secret: unhex(secret)?.try_into().ok()?,
522            fingerprint: unhex(fingerprint)?.try_into().ok()?,
523        })
524    }
525}
526
527/// `bytes`, hex.
528pub fn hex(bytes: &[u8]) -> String {
529    bytes.iter().map(|b| format!("{b:02x}")).collect()
530}
531
532/// The bytes `text` holds in hex, if it is hex.
533pub fn unhex(text: &str) -> Option<Vec<u8>> {
534    if !text.len().is_multiple_of(2) || !text.bytes().all(|b| b.is_ascii_hexdigit()) {
535        return None;
536    }
537    text.as_bytes()
538        .chunks(2)
539        .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok())
540        .collect()
541}
542
543/// The reason a relay refuses a machine it does not know (removed from its
544/// account, or never registered there): the one refusal after which a link
545/// stops for good (#138), not after a passing failure.
546pub const MACHINE_UNKNOWN: &str = "this relay does not know this machine (removed from its account, or registered with another relay?)";
547
548/// The reason a registration token is refused, whatever was wrong with it
549/// (unknown, expired, used up, revoked).
550pub const BAD_TOKEN: &str = "this registration token does not work (unknown, expired, used up or \
551     revoked; or made by a teter older than 26.11.3: make a new one)";
552
553/// An account's limits on its relay (#104), each `None` for none, and what
554/// it used this month: what a device checks before it asks for more (a new
555/// session past the limit would run on its machine, but the relay would keep
556/// no record of it).
557#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
558pub struct AccountLimits {
559    /// Machines registered.
560    pub machines: Option<u64>,
561    /// Sessions kept, over all its machines.
562    pub sessions: Option<u64>,
563    /// Bytes a second its machines and devices send through the relay.
564    pub rate: Option<u64>,
565    /// Bytes a month (UTC) they send.
566    pub monthly: Option<u64>,
567    /// Bytes they sent this month.
568    pub used: u64,
569}
570
571impl AccountLimits {
572    /// Why a new session is refused when the account keeps `kept` sessions
573    /// already, if it is.
574    #[must_use]
575    pub fn no_room_for_a_session(&self, kept: usize) -> Option<String> {
576        let at = self.sessions?;
577        (u64::try_from(kept).unwrap_or(u64::MAX) >= at).then(|| {
578            format!(
579                "this account has {kept} sessions, the most its relay allows it ({at}): end one \
580                 (teter kill machine:session), or ask the relay's admin for more"
581            )
582        })
583    }
584}
585
586/// A machine of the account and its sessions, as [`AccountReply::Sessions`]
587/// gives them.
588#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
589pub struct MachineSessions {
590    /// The machine's ID.
591    pub id: String,
592    /// Its display name, sealed to the account.
593    pub sealed_name: Vec<u8>,
594    /// Its public key (Ed25519), which signs its command challenges (#88);
595    /// empty from a relay older than that.
596    #[serde(default)]
597    pub public_key: Vec<u8>,
598    /// The account's approval of the machine (#133), empty before one.
599    #[serde(default)]
600    pub cert: Vec<u8>,
601    /// The relay session it is served on now, and the token a frontend joins
602    /// it with; `None` while it is not connected.
603    pub relay: Option<(crate::SessionId, String)>,
604    /// Its sessions.
605    pub sessions: Vec<SessionRecordInfo>,
606}
607
608/// One of a machine's sessions: its channel, its name and key sealed to the
609/// account.
610#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
611pub struct SessionRecordInfo {
612    /// The channel it travels on inside the machine's relay session.
613    pub channel: String,
614    /// The relay session that serves it now, and the token to join it;
615    /// `None` while no link of its machine serves it.
616    pub relay: Option<(crate::SessionId, String)>,
617    /// Its name, sealed to the account.
618    pub sealed_name: Vec<u8>,
619    /// Its end-to-end secret, sealed to the account for its channel.
620    pub sealed_key: Vec<u8>,
621    /// The machine's signature of [`record_bytes`] (#133).
622    #[serde(default)]
623    pub signature: Vec<u8>,
624    /// How many frontends are attached to it now (#135); `None` from a
625    /// relay older than the field.
626    #[serde(default)]
627    pub clients: Option<u32>,
628}
629
630/// What a machine signs to show it held its registration token: its key and
631/// its sealed name (#133).
632pub fn binding_bytes(machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
633    let mut bytes = b"teter-machine-bind-v1 ".to_vec();
634    bytes.extend_from_slice(machine_key);
635    bytes.extend_from_slice(sealed_name);
636    bytes
637}
638
639/// What the account signs to approve machine `id` (#133): its key and its
640/// sealed name, so a relay can neither swap a machine's key nor move its
641/// name.
642pub fn cert_bytes(id: &str, machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
643    let mut bytes = b"teter-machine-cert-v1 ".to_vec();
644    bytes.extend_from_slice(id.as_bytes());
645    bytes.push(0);
646    bytes.extend_from_slice(machine_key);
647    bytes.extend_from_slice(sealed_name);
648    bytes
649}
650
651/// What a machine's display name is sealed to the account with (#86).
652pub const MACHINE_NAME_INFO: &[u8] = b"machine name";
653
654/// What the name of machine `machine`'s session on `channel` is sealed to
655/// the account with (#87): bound to both, so a relay cannot move a name onto
656/// another record.
657pub fn session_name_info(machine: &str, channel: &str) -> Vec<u8> {
658    format!("session name {machine} {channel}").into_bytes()
659}
660
661/// What a session's end-to-end secret is sealed to the account with (#87),
662/// bound to its channel.
663pub fn session_key_info(channel: &str) -> Vec<u8> {
664    let mut info = b"session key ".to_vec();
665    info.extend_from_slice(channel.as_bytes());
666    info
667}
668
669/// What machine `machine` signs for its session on `channel` (#133).
670pub fn record_bytes(
671    machine: &str,
672    channel: &str,
673    sealed_name: &[u8],
674    sealed_key: &[u8],
675) -> Vec<u8> {
676    let mut bytes = b"teter-record-v1 ".to_vec();
677    bytes.extend_from_slice(machine.as_bytes());
678    bytes.push(0);
679    bytes.extend_from_slice(channel.as_bytes());
680    bytes.push(0);
681    bytes.extend_from_slice(
682        &u32::try_from(sealed_name.len())
683            .unwrap_or(u32::MAX)
684            .to_be_bytes(),
685    );
686    bytes.extend_from_slice(sealed_name);
687    bytes.extend_from_slice(sealed_key);
688    bytes
689}