teter-common 26.11.6

Shared types and protocol definitions for teter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
//! The account protocol, on the relay's `/account` path: one request, one
//! reply, per connection (JSON text frames, like the rest of the protocol).
//!
//! The password never leaves the client (model C, decided in #57): the client
//! derives a master key from it (Argon2id, with the parameters and salt the
//! account carries), and from the master key an auth key, which it presents,
//! and a wrapping key, which wraps the account's private keys before they
//! reach the relay. The relay keeps a hash of the auth key, the public keys
//! and the wrapped private keys, and can read none of what they protect.

use serde::{Deserialize, Serialize};

/// The relay path the account protocol is served on.
pub const PATH: &str = "/account";

/// The longest account name, in bytes.
pub const MAX_NAME: usize = 64;

/// Whether `name` can be an account's name: 1 to [`MAX_NAME`] ASCII letters,
/// digits, `.`, `_` or `-`, starting with a letter or a digit.
pub fn valid_name(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= MAX_NAME
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
        && name
            .bytes()
            .next()
            .is_some_and(|b| b.is_ascii_alphanumeric())
}

/// The version of a salt's layout.
pub const SALT_VERSION: u8 = 1;

/// The random part of a salt, in bytes.
pub const SALT_RANDOM_LEN: usize = 16;

/// A salt's length: the version, the Argon2id parameters (memory in KiB,
/// passes, lanes, each 4 bytes big-endian) and the random bytes.
pub const SALT_LEN: usize = 1 + 12 + SALT_RANDOM_LEN;

/// Argon2id's cost parameters, carried in an account's salt.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KdfParams {
    /// Memory, in KiB.
    pub memory_kib: u32,
    /// Passes over the memory.
    pub passes: u32,
    /// Lanes.
    pub lanes: u32,
}

/// Argon2id's parameters for new accounts: 64 MiB, 3 passes, 1 lane (the
/// second recommended set of RFC 9106, for memory-constrained devices).
pub const DEFAULT_KDF: KdfParams = KdfParams {
    memory_kib: 64 * 1024,
    passes: 3,
    lanes: 1,
};

/// The least Argon2id cost a client accepts, or a relay takes at signup:
/// [`DEFAULT_KDF`]. A relay is not trusted (#57): one that answered a salt
/// with a lower cost would make the auth key cheap to guess the password
/// from.
pub const MIN_KDF: KdfParams = DEFAULT_KDF;

/// The most Argon2id cost a client accepts: 1 GiB, 10 passes, 8 lanes. A
/// relay that answered more would have the client run out of memory or
/// spin.
pub const MAX_KDF: KdfParams = KdfParams {
    memory_kib: 1024 * 1024,
    passes: 10,
    lanes: 8,
};

/// Whether `params` is within [`MIN_KDF`] and [`MAX_KDF`].
pub fn acceptable_kdf(params: KdfParams) -> bool {
    (MIN_KDF.memory_kib..=MAX_KDF.memory_kib).contains(&params.memory_kib)
        && (MIN_KDF.passes..=MAX_KDF.passes).contains(&params.passes)
        && (MIN_KDF.lanes..=MAX_KDF.lanes).contains(&params.lanes)
}

/// A salt for `params` with `random` as its random bytes.
pub fn salt_blob(params: KdfParams, random: &[u8; SALT_RANDOM_LEN]) -> Vec<u8> {
    let mut blob = Vec::with_capacity(SALT_LEN);
    blob.push(SALT_VERSION);
    blob.extend_from_slice(&params.memory_kib.to_be_bytes());
    blob.extend_from_slice(&params.passes.to_be_bytes());
    blob.extend_from_slice(&params.lanes.to_be_bytes());
    blob.extend_from_slice(random);
    blob
}

/// The parameters and random bytes of `salt`, if it has this build's layout.
pub fn parse_salt(salt: &[u8]) -> Option<(KdfParams, &[u8])> {
    let (header, random) = salt.split_at_checked(13)?;
    let [version, m0, m1, m2, m3, t0, t1, t2, t3, p0, p1, p2, p3] = *header else {
        return None;
    };
    (version == SALT_VERSION && random.len() == SALT_RANDOM_LEN).then_some((
        KdfParams {
            memory_kib: u32::from_be_bytes([m0, m1, m2, m3]),
            passes: u32::from_be_bytes([t0, t1, t2, t3]),
            lanes: u32::from_be_bytes([p0, p1, p2, p3]),
        },
        random,
    ))
}

/// A request to the relay's account service.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum AccountRequest {
    /// The salt (with its key derivation parameters) of account `name`, to
    /// derive its keys before logging in. A name with no account gets a salt
    /// all the same, always the same for that name, so the answer does not
    /// tell which names have accounts.
    Salt {
        /// The account's name.
        name: String,
    },
    /// Makes account `name`.
    Signup {
        /// The account's name.
        name: String,
        /// The salt and key derivation parameters the client used.
        salt: Vec<u8>,
        /// The auth key the client derived; the relay keeps only its hash.
        auth_key: Vec<u8>,
        /// The account's public keys.
        public_keys: Vec<u8>,
        /// The account's private keys, wrapped by the client.
        wrapped_keys: Vec<u8>,
        /// The invite the relay's admin gave (#103): signup is closed
        /// without one.
        #[serde(default)]
        invite: String,
    },
    /// Logs in to account `name` with the auth key derived from its password.
    Login {
        /// The account's name.
        name: String,
        /// The auth key.
        auth_key: Vec<u8>,
    },
    /// Ends the login session of `token`.
    Logout {
        /// The login token.
        token: String,
    },
    /// Makes a registration token for the logged-in account: the relay keeps
    /// the hash of its enrollment secret (the client keeps the secret), with
    /// its expiry and uses.
    TokenCreate {
        /// The login token.
        login: String,
        /// The SHA-256 of the enrollment secret.
        secret_hash: Vec<u8>,
        /// Seconds until it stops working (at most [`MAX_TOKEN_LIFETIME`]).
        expires_in: u64,
        /// How many machines it registers (1 to [`MAX_TOKEN_USES`]).
        uses: u32,
    },
    /// The registration tokens of the logged-in account.
    TokenList {
        /// The login token.
        login: String,
    },
    /// Revokes a registration token of the logged-in account.
    TokenRevoke {
        /// The login token.
        login: String,
        /// The token's ID ([`TokenInfo::id`]).
        id: String,
    },
    /// The public keys of the account a registration token belongs to, for
    /// the machine to check against the token's fingerprint before it
    /// registers. Uses nothing of the token.
    TokenKeys {
        /// The token's enrollment secret.
        secret: Vec<u8>,
    },
    /// Registers a machine with a registration token, taking one of its
    /// uses.
    Register {
        /// The token's enrollment secret.
        secret: Vec<u8>,
        /// The machine's Ed25519 public key, which it authenticates with.
        machine_key: Vec<u8>,
        /// The machine's display name, sealed to the account's X25519 key.
        sealed_name: Vec<u8>,
        /// Its proof it holds the token (#133): HMAC-SHA256 of
        /// [`binding_bytes`] under the token's binding key, which never
        /// reaches the relay. The device that made the token checks it
        /// before it approves the machine.
        #[serde(default)]
        binding: Vec<u8>,
    },
    /// Approves a machine of the logged-in account (#133): the account's
    /// signature of [`cert_bytes`], which devices check before they trust
    /// the machine's key, name and records.
    MachineApprove {
        /// The login token.
        login: String,
        /// The machine's ID.
        id: String,
        /// The account's signature.
        cert: Vec<u8>,
    },
    /// The logged-in account's machines.
    MachineList {
        /// The login token.
        login: String,
    },
    /// Removes a machine of the logged-in account: it can no longer connect.
    MachineRemove {
        /// The login token.
        login: String,
        /// The machine's ID.
        id: String,
    },
    /// The logged-in account's machines, each with the relay session it is
    /// served on now (if it is connected) and its sessions' records (#87):
    /// all a device needs to attach, nothing carried by hand.
    Sessions {
        /// The login token.
        login: String,
    },
    /// Changes the logged-in account's password (#89): its new salt, auth
    /// key and private keys wrapped under the new password, proven by the
    /// current password's auth key. Every login of the account ends; the
    /// reply holds a new one.
    PasswordChange {
        /// The login token.
        login: String,
        /// The current password's auth key.
        auth_key: Vec<u8>,
        /// The new salt and key derivation parameters.
        salt: Vec<u8>,
        /// The new password's auth key.
        new_auth_key: Vec<u8>,
        /// The private keys wrapped under the new password.
        wrapped_keys: Vec<u8>,
    },
    /// Replaces the logged-in account's keys (#89): `rotation`, signed by the
    /// current signing key, the new private keys wrapped under the password,
    /// and each approved machine's name and approval under the new keys,
    /// proven by the password's auth key. Every login of the account ends;
    /// the reply holds a new one.
    KeyRotate {
        /// The login token.
        login: String,
        /// The password's auth key.
        auth_key: Vec<u8>,
        /// The rotation.
        rotation: KeyRotation,
        /// The new private keys, wrapped.
        wrapped_keys: Vec<u8>,
        /// The machines, re-approved.
        machines: Vec<MachineRekey>,
    },
    /// A machine removes itself, proving it holds its key.
    Unregister {
        /// The machine's ID.
        machine: String,
        /// When it signed (Unix seconds); the relay takes it within
        /// [`UNREGISTER_WINDOW`] of its own clock.
        at: i64,
        /// Its signature of [`unregister_message`].
        signature: Vec<u8>,
    },
}

/// A change of the account's keys (#89): the new public keys, signed by the
/// old signing key. Machines pinned to the old keys follow it; a relay cannot
/// make one without the account's old private key.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KeyRotation {
    /// The public keys it replaces (X25519, then Ed25519).
    pub old_keys: Vec<u8>,
    /// The public keys that replace them.
    pub new_keys: Vec<u8>,
    /// When it was signed (Unix seconds).
    pub at: i64,
    /// The old signing key's signature of [`rotation_bytes`].
    pub signature: Vec<u8>,
}

/// What the old signing key signs for a [`KeyRotation`].
pub fn rotation_bytes(old_keys: &[u8], new_keys: &[u8], at: i64) -> Vec<u8> {
    let mut bytes = b"teter-key-rotation-v1 ".to_vec();
    bytes.extend_from_slice(
        &u32::try_from(old_keys.len())
            .unwrap_or(u32::MAX)
            .to_be_bytes(),
    );
    bytes.extend_from_slice(old_keys);
    bytes.extend_from_slice(new_keys);
    bytes.extend_from_slice(&at.to_be_bytes());
    bytes
}

/// The most key rotations a relay keeps per account, newest last: a machine
/// pinned to keys older than these registers again.
pub const MAX_ROTATIONS: usize = 64;

/// A machine's name and approval under the account's new keys, which the
/// device that rotates them gives (#89).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MachineRekey {
    /// The machine's ID.
    pub id: String,
    /// Its display name, sealed to the new keys.
    pub sealed_name: Vec<u8>,
    /// The new keys' approval of it ([`cert_bytes`]).
    pub cert: Vec<u8>,
}

/// How far a machine's `Unregister` time may be from the relay's, in seconds.
pub const UNREGISTER_WINDOW: i64 = 300;

/// What a machine signs to unregister: this prefix, its ID, and the time.
pub fn unregister_message(machine: &str, at: i64) -> Vec<u8> {
    let mut message = b"teter-unregister-v1 ".to_vec();
    message.extend_from_slice(machine.as_bytes());
    message.extend_from_slice(&at.to_be_bytes());
    message
}

/// A machine as the relay lists it to its account.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MachineInfo {
    /// Its ID.
    pub id: String,
    /// Its display name, sealed to the account.
    pub sealed_name: Vec<u8>,
    /// When it last connected (Unix seconds), if it has.
    pub last_seen: Option<i64>,
    /// Its public key (#133).
    #[serde(default)]
    pub public_key: Vec<u8>,
    /// Its proof it held the token (see [`AccountRequest::Register`]).
    #[serde(default)]
    pub binding: Vec<u8>,
    /// The account's approval, empty before one.
    #[serde(default)]
    pub cert: Vec<u8>,
}

/// The longest a registration token works: 30 days.
pub const MAX_TOKEN_LIFETIME: u64 = 30 * 24 * 3600;

/// The most machines one registration token registers.
pub const MAX_TOKEN_USES: u32 = 100;

/// A registration token as the relay lists it: never its secret.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenInfo {
    /// Its ID: the SHA-256 of its secret, hex.
    pub id: String,
    /// When it was made (Unix seconds).
    pub created: i64,
    /// When it stops working (Unix seconds).
    pub expires: i64,
    /// How many more machines it registers.
    pub uses_left: i64,
}

/// The relay's reply to an [`AccountRequest`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum AccountReply {
    /// The salt asked for.
    Salt {
        /// The salt and key derivation parameters.
        salt: Vec<u8>,
    },
    /// The account was made.
    SignedUp,
    /// Logged in: a token for the relay, and the account's keys, the private
    /// ones still wrapped.
    LoggedIn {
        /// The login token.
        token: String,
        /// The account's public keys.
        public_keys: Vec<u8>,
        /// The account's private keys, wrapped.
        wrapped_keys: Vec<u8>,
    },
    /// The login session ended (or there was none).
    LoggedOut,
    /// The registration token was made.
    TokenCreated,
    /// The account's registration tokens, oldest first.
    Tokens {
        /// The tokens.
        tokens: Vec<TokenInfo>,
        /// The relay's clock (Unix seconds), which the expiries are on; 0
        /// from a relay that does not send it.
        #[serde(default)]
        now: i64,
    },
    /// Whether a registration token was revoked (`false`: no such token).
    TokenRevoked {
        /// Whether it was.
        revoked: bool,
    },
    /// The public keys of a registration token's account.
    AccountKeys {
        /// The account's public keys.
        public_keys: Vec<u8>,
    },
    /// The machine is registered.
    Registered {
        /// Its ID, which it says hello with.
        machine: String,
    },
    /// The account's machines.
    Machines {
        /// The machines.
        machines: Vec<MachineInfo>,
    },
    /// Whether a machine was removed (`false`: no such machine).
    MachineRemoved {
        /// Whether it was.
        removed: bool,
    },
    /// Whether a machine was approved (`false`: no such machine).
    MachineApproved {
        /// Whether it was.
        approved: bool,
    },
    /// The account's machines and their sessions.
    Sessions {
        /// The machines.
        machines: Vec<MachineSessions>,
        /// The account's limits on this relay (#104); `None` from a relay
        /// older than them.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        limits: Option<AccountLimits>,
    },
    /// The password was changed: the new login (every other ended).
    PasswordChanged {
        /// The login token.
        token: String,
    },
    /// The keys were replaced: the new login (every other ended).
    KeysRotated {
        /// The login token.
        token: String,
    },
    /// Refused, and why. A failed login says only that the name or the
    /// password is wrong, never which.
    Refused {
        /// Why.
        reason: String,
    },
}

/// The reason a login is refused, whatever was wrong.
pub const WRONG_LOGIN: &str = "wrong account name or password";

/// The reason an account request is refused when its login token is not
/// (or no longer) a login.
pub const NOT_LOGGED_IN: &str = "not logged in (or the login expired): run teter login";

/// The prefix of a registration token's text.
pub const REGISTRATION_PREFIX: &str = "teter-reg1";

/// A registration token, as the logged-in user hands it to the machine to
/// register: the relay's URL, the enrollment secret, and the fingerprint of
/// the account's public keys, which the machine checks the keys the relay
/// gives it against (#86), so a relay cannot swap the account's keys.
#[derive(Clone, PartialEq, Eq)]
pub struct Registration {
    /// The relay's URL.
    pub relay: String,
    /// The enrollment secret.
    pub secret: [u8; 32],
    /// The fingerprint of the account's public keys.
    pub fingerprint: [u8; 16],
}

impl std::fmt::Debug for Registration {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Registration")
            .field("relay", &self.relay)
            .finish_non_exhaustive()
    }
}

impl Registration {
    /// Its text: `teter-reg1.<relay, hex>.<secret, hex>.<fingerprint, hex>`.
    pub fn to_text(&self) -> String {
        format!(
            "{REGISTRATION_PREFIX}.{}.{}.{}",
            hex(self.relay.as_bytes()),
            hex(&self.secret),
            hex(&self.fingerprint)
        )
    }

    /// The token `text` holds, if it is one.
    pub fn parse(text: &str) -> Option<Self> {
        let mut parts = text.trim().split('.');
        let (Some(prefix), Some(relay), Some(secret), Some(fingerprint), None) = (
            parts.next(),
            parts.next(),
            parts.next(),
            parts.next(),
            parts.next(),
        ) else {
            return None;
        };
        if prefix != REGISTRATION_PREFIX {
            return None;
        }
        Some(Self {
            relay: String::from_utf8(unhex(relay)?).ok()?,
            secret: unhex(secret)?.try_into().ok()?,
            fingerprint: unhex(fingerprint)?.try_into().ok()?,
        })
    }
}

/// `bytes`, hex.
pub fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// The bytes `text` holds in hex, if it is hex.
pub fn unhex(text: &str) -> Option<Vec<u8>> {
    if !text.len().is_multiple_of(2) || !text.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    text.as_bytes()
        .chunks(2)
        .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok())
        .collect()
}

/// The reason a relay refuses a machine it does not know (removed from its
/// account, or never registered there): the one refusal after which a link
/// stops for good (#138), not after a passing failure.
pub const MACHINE_UNKNOWN: &str = "this relay does not know this machine (removed from its account, or registered with another relay?)";

/// The reason a registration token is refused, whatever was wrong with it
/// (unknown, expired, used up, revoked).
pub const BAD_TOKEN: &str = "this registration token does not work (unknown, expired, used up or \
     revoked; or made by a teter older than 26.11.3: make a new one)";

/// An account's limits on its relay (#104), each `None` for none, and what
/// it used this month: what a device checks before it asks for more (a new
/// session past the limit would run on its machine, but the relay would keep
/// no record of it).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct AccountLimits {
    /// Machines registered.
    pub machines: Option<u64>,
    /// Sessions kept, over all its machines.
    pub sessions: Option<u64>,
    /// Bytes a second its machines and devices send through the relay.
    pub rate: Option<u64>,
    /// Bytes a month (UTC) they send.
    pub monthly: Option<u64>,
    /// Bytes they sent this month.
    pub used: u64,
}

impl AccountLimits {
    /// Why a new session is refused when the account keeps `kept` sessions
    /// already, if it is.
    #[must_use]
    pub fn no_room_for_a_session(&self, kept: usize) -> Option<String> {
        let at = self.sessions?;
        (u64::try_from(kept).unwrap_or(u64::MAX) >= at).then(|| {
            format!(
                "this account has {kept} sessions, the most its relay allows it ({at}): end one \
                 (teter kill machine:session), or ask the relay's admin for more"
            )
        })
    }
}

/// A machine of the account and its sessions, as [`AccountReply::Sessions`]
/// gives them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MachineSessions {
    /// The machine's ID.
    pub id: String,
    /// Its display name, sealed to the account.
    pub sealed_name: Vec<u8>,
    /// Its public key (Ed25519), which signs its command challenges (#88);
    /// empty from a relay older than that.
    #[serde(default)]
    pub public_key: Vec<u8>,
    /// The account's approval of the machine (#133), empty before one.
    #[serde(default)]
    pub cert: Vec<u8>,
    /// The relay session it is served on now, and the token a frontend joins
    /// it with; `None` while it is not connected.
    pub relay: Option<(crate::SessionId, String)>,
    /// Its sessions.
    pub sessions: Vec<SessionRecordInfo>,
}

/// One of a machine's sessions: its channel, its name and key sealed to the
/// account.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionRecordInfo {
    /// The channel it travels on inside the machine's relay session.
    pub channel: String,
    /// The relay session that serves it now, and the token to join it;
    /// `None` while no link of its machine serves it.
    pub relay: Option<(crate::SessionId, String)>,
    /// Its name, sealed to the account.
    pub sealed_name: Vec<u8>,
    /// Its end-to-end secret, sealed to the account for its channel.
    pub sealed_key: Vec<u8>,
    /// The machine's signature of [`record_bytes`] (#133).
    #[serde(default)]
    pub signature: Vec<u8>,
    /// How many frontends are attached to it now (#135); `None` from a
    /// relay older than the field.
    #[serde(default)]
    pub clients: Option<u32>,
}

/// What a machine signs to show it held its registration token: its key and
/// its sealed name (#133).
pub fn binding_bytes(machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
    let mut bytes = b"teter-machine-bind-v1 ".to_vec();
    bytes.extend_from_slice(machine_key);
    bytes.extend_from_slice(sealed_name);
    bytes
}

/// What the account signs to approve machine `id` (#133): its key and its
/// sealed name, so a relay can neither swap a machine's key nor move its
/// name.
pub fn cert_bytes(id: &str, machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
    let mut bytes = b"teter-machine-cert-v1 ".to_vec();
    bytes.extend_from_slice(id.as_bytes());
    bytes.push(0);
    bytes.extend_from_slice(machine_key);
    bytes.extend_from_slice(sealed_name);
    bytes
}

/// What a machine's display name is sealed to the account with (#86).
pub const MACHINE_NAME_INFO: &[u8] = b"machine name";

/// What the name of machine `machine`'s session on `channel` is sealed to
/// the account with (#87): bound to both, so a relay cannot move a name onto
/// another record.
pub fn session_name_info(machine: &str, channel: &str) -> Vec<u8> {
    format!("session name {machine} {channel}").into_bytes()
}

/// What a session's end-to-end secret is sealed to the account with (#87),
/// bound to its channel.
pub fn session_key_info(channel: &str) -> Vec<u8> {
    let mut info = b"session key ".to_vec();
    info.extend_from_slice(channel.as_bytes());
    info
}

/// What machine `machine` signs for its session on `channel` (#133).
pub fn record_bytes(
    machine: &str,
    channel: &str,
    sealed_name: &[u8],
    sealed_key: &[u8],
) -> Vec<u8> {
    let mut bytes = b"teter-record-v1 ".to_vec();
    bytes.extend_from_slice(machine.as_bytes());
    bytes.push(0);
    bytes.extend_from_slice(channel.as_bytes());
    bytes.push(0);
    bytes.extend_from_slice(
        &u32::try_from(sealed_name.len())
            .unwrap_or(u32::MAX)
            .to_be_bytes(),
    );
    bytes.extend_from_slice(sealed_name);
    bytes.extend_from_slice(sealed_key);
    bytes
}