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(¶ms.memory_kib)
80 && (MIN_KDF.passes..=MAX_KDF.passes).contains(¶ms.passes)
81 && (MIN_KDF.lanes..=MAX_KDF.lanes).contains(¶ms.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(¶ms.memory_kib.to_be_bytes());
89 blob.extend_from_slice(¶ms.passes.to_be_bytes());
90 blob.extend_from_slice(¶ms.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 /// The signing-up device's Ed25519 public key (#154, #158): the
140 /// account's first device, approved by the signup itself.
141 #[serde(default)]
142 device_key: Vec<u8>,
143 /// That device's name, sealed to the account ([`DEVICE_NAME_INFO`]).
144 #[serde(default)]
145 device_name: Vec<u8>,
146 /// The recovery codes (#154), each as the relay keeps it.
147 #[serde(default)]
148 recovery: Vec<RecoveryCode>,
149 },
150 /// Logs in to account `name` with the auth key derived from its password.
151 Login {
152 /// The account's name.
153 name: String,
154 /// The auth key.
155 auth_key: Vec<u8>,
156 /// This device's Ed25519 public key (#158): the login's token works
157 /// only in a [`AccountRequest::Proven`] this key signed. A login
158 /// without one is refused. It is also the device on the account
159 /// (#154): a key the account approved gets a login; another waits
160 /// for an approved device's approval
161 /// ([`AccountReply::PairingPending`]).
162 #[serde(default)]
163 device_key: Vec<u8>,
164 /// When the device signed `device_proof` (Unix seconds); the relay
165 /// takes it within [`DEVICE_PROOF_WINDOW`] of its own clock.
166 #[serde(default)]
167 at: i64,
168 /// The device's proof it holds its key: its Ed25519 signature of
169 /// [`device_login_bytes`] (#154). A public key alone logs nothing in.
170 #[serde(default)]
171 device_proof: Vec<u8>,
172 /// A recovery code's auth key ([`RecoveryCode::auth_hash`] is its
173 /// SHA-256), to log in with no approved device left: used once, it
174 /// approves the device and answers the keys it wraps.
175 #[serde(default, skip_serializing_if = "Vec::is_empty")]
176 recovery: Vec<u8>,
177 },
178 /// Ends the login session of `token`; with `all`, every login of its
179 /// account (#157).
180 Logout {
181 /// The login token.
182 token: String,
183 /// Every login of the account, not only this one.
184 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
185 all: bool,
186 },
187 /// Asks whether a pairing request was approved (#154), with the secret
188 /// [`AccountReply::PairingPending`] gave.
189 PairingPoll {
190 /// The request's secret.
191 request: String,
192 },
193 /// The logged-in account's devices, approved and waiting (#154).
194 DeviceList {
195 /// The login token.
196 login: String,
197 },
198 /// Approves a device waiting to log in (#154), sending it the account's
199 /// private keys sealed to its key ([`device_keys_info`]).
200 DeviceApprove {
201 /// The login token.
202 login: String,
203 /// The waiting device's ID.
204 id: String,
205 /// The account's private keys, sealed to the device.
206 sealed_keys: Vec<u8>,
207 },
208 /// Removes a device of the logged-in account (#154): its logins end and
209 /// its connections are cut off at once.
210 DeviceRemove {
211 /// The login token.
212 login: String,
213 /// The device's ID.
214 id: String,
215 },
216 /// Names the logged-in device (#154), sealed to the account.
217 DeviceRename {
218 /// The login token.
219 login: String,
220 /// Its name, sealed to the account ([`DEVICE_NAME_INFO`]).
221 sealed_name: Vec<u8>,
222 },
223 /// Replaces the logged-in account's recovery codes (#154); needs a
224 /// recent [`AccountRequest::Reauth`].
225 RecoveryCodes {
226 /// The login token.
227 login: String,
228 /// The new codes, each as the relay keeps it.
229 codes: Vec<RecoveryCode>,
230 },
231 /// Proves the password again (#157): the sensitive requests of this
232 /// login work for [`REAUTH_WINDOW`] seconds after.
233 Reauth {
234 /// The login token.
235 login: String,
236 /// The password's auth key.
237 auth_key: Vec<u8>,
238 },
239 /// Makes a registration token for the logged-in account: the relay keeps
240 /// the hash of its enrollment secret (the client keeps the secret), with
241 /// its expiry and uses.
242 TokenCreate {
243 /// The login token.
244 login: String,
245 /// The SHA-256 of the enrollment secret.
246 secret_hash: Vec<u8>,
247 /// Seconds until it stops working (at most [`MAX_TOKEN_LIFETIME`]).
248 expires_in: u64,
249 /// How many machines it registers (1 to [`MAX_TOKEN_USES`]).
250 uses: u32,
251 },
252 /// The registration tokens of the logged-in account.
253 TokenList {
254 /// The login token.
255 login: String,
256 },
257 /// Revokes a registration token of the logged-in account.
258 TokenRevoke {
259 /// The login token.
260 login: String,
261 /// The token's ID ([`TokenInfo::id`]).
262 id: String,
263 },
264 /// The public keys of the account a registration token belongs to, for
265 /// the machine to check against the token's fingerprint before it
266 /// registers. Uses nothing of the token.
267 TokenKeys {
268 /// The token's enrollment secret.
269 secret: Vec<u8>,
270 },
271 /// Registers a machine with a registration token, taking one of its
272 /// uses.
273 Register {
274 /// The token's enrollment secret.
275 secret: Vec<u8>,
276 /// The machine's Ed25519 public key, which it authenticates with.
277 machine_key: Vec<u8>,
278 /// The machine's display name, sealed to the account's X25519 key.
279 sealed_name: Vec<u8>,
280 /// Its proof it holds the token (#133): HMAC-SHA256 of
281 /// [`binding_bytes`] under the token's binding key, which never
282 /// reaches the relay. The device that made the token checks it
283 /// before it approves the machine.
284 #[serde(default)]
285 binding: Vec<u8>,
286 },
287 /// Approves a machine of the logged-in account (#133): the account's
288 /// signature of [`cert_bytes`], which devices check before they trust
289 /// the machine's key, name and records.
290 MachineApprove {
291 /// The login token.
292 login: String,
293 /// The machine's ID.
294 id: String,
295 /// The account's signature.
296 cert: Vec<u8>,
297 },
298 /// The logged-in account's machines.
299 MachineList {
300 /// The login token.
301 login: String,
302 },
303 /// Removes a machine of the logged-in account: it can no longer connect.
304 MachineRemove {
305 /// The login token.
306 login: String,
307 /// The machine's ID.
308 id: String,
309 },
310 /// The logged-in account's machines, each with the relay session it is
311 /// served on now (if it is connected) and its sessions' records (#87):
312 /// all a device needs to attach, nothing carried by hand.
313 Sessions {
314 /// The login token.
315 login: String,
316 },
317 /// Changes the logged-in account's password (#89): its new salt, auth
318 /// key and private keys wrapped under the new password, proven by the
319 /// current password's auth key. Every login of the account ends; the
320 /// reply holds a new one.
321 PasswordChange {
322 /// The login token.
323 login: String,
324 /// The current password's auth key.
325 auth_key: Vec<u8>,
326 /// The new salt and key derivation parameters.
327 salt: Vec<u8>,
328 /// The new password's auth key.
329 new_auth_key: Vec<u8>,
330 /// The private keys wrapped under the new password.
331 wrapped_keys: Vec<u8>,
332 },
333 /// Replaces the logged-in account's keys (#89): `rotation`, signed by the
334 /// current signing key, the new private keys wrapped under the password,
335 /// and each approved machine's name and approval under the new keys,
336 /// proven by the password's auth key. Every login of the account ends;
337 /// the reply holds a new one.
338 KeyRotate {
339 /// The login token.
340 login: String,
341 /// The password's auth key.
342 auth_key: Vec<u8>,
343 /// The rotation.
344 rotation: KeyRotation,
345 /// The new private keys, wrapped.
346 wrapped_keys: Vec<u8>,
347 /// The machines, re-approved.
348 machines: Vec<MachineRekey>,
349 /// New recovery codes wrapping the new keys (#154); the old ones,
350 /// which wrap the old keys, go either way.
351 #[serde(default)]
352 recovery: Vec<RecoveryCode>,
353 },
354 /// A machine removes itself, proving it holds its key.
355 Unregister {
356 /// The machine's ID.
357 machine: String,
358 /// When it signed (Unix seconds); the relay takes it within
359 /// [`UNREGISTER_WINDOW`] of its own clock.
360 at: i64,
361 /// Its signature of [`unregister_message`].
362 signature: Vec<u8>,
363 },
364 /// A request that carries a login token, signed by the device the login
365 /// was made on (#158): a token without its device's signature is
366 /// refused, so a copied token, or a copied account file, works nowhere
367 /// else.
368 Proven {
369 /// The request, as the JSON text that was signed.
370 request: String,
371 /// When it was signed (Unix seconds); the relay takes it within
372 /// [`PROOF_WINDOW`] of its own clock, and each nonce once.
373 at: i64,
374 /// [`PROOF_NONCE_LEN`] random bytes.
375 nonce: Vec<u8>,
376 /// The device key's signature of [`proof_bytes`].
377 signature: Vec<u8>,
378 },
379}
380
381impl AccountRequest {
382 /// The login token this request uses, if it is one that needs a login
383 /// (`Logout`'s token included).
384 pub fn login_token(&self) -> Option<&str> {
385 match self {
386 Self::Logout { token, .. } => Some(token),
387 Self::TokenCreate { login, .. }
388 | Self::DeviceList { login }
389 | Self::DeviceApprove { login, .. }
390 | Self::DeviceRemove { login, .. }
391 | Self::DeviceRename { login, .. }
392 | Self::RecoveryCodes { login, .. }
393 | Self::Reauth { login, .. }
394 | Self::TokenList { login }
395 | Self::TokenRevoke { login, .. }
396 | Self::MachineApprove { login, .. }
397 | Self::MachineList { login }
398 | Self::MachineRemove { login, .. }
399 | Self::Sessions { login }
400 | Self::PasswordChange { login, .. }
401 | Self::KeyRotate { login, .. } => Some(login),
402 Self::Salt { .. }
403 | Self::Signup { .. }
404 | Self::Login { .. }
405 | Self::TokenKeys { .. }
406 | Self::Register { .. }
407 | Self::Unregister { .. }
408 | Self::PairingPoll { .. }
409 | Self::Proven { .. } => None,
410 }
411 }
412}
413
414/// How far a [`AccountRequest::Proven`]'s time may be from the relay's, in
415/// seconds.
416pub const PROOF_WINDOW: i64 = 300;
417
418/// The length of a [`AccountRequest::Proven`]'s nonce.
419pub const PROOF_NONCE_LEN: usize = 16;
420
421/// What a device signs to prove a request (#158): this prefix, the time,
422/// the nonce, and the request's JSON text.
423pub fn proof_bytes(request: &str, at: i64, nonce: &[u8]) -> Vec<u8> {
424 let mut bytes = b"teter-device-proof-v1 ".to_vec();
425 bytes.extend_from_slice(&at.to_be_bytes());
426 bytes.extend_from_slice(&u32::try_from(nonce.len()).unwrap_or(u32::MAX).to_be_bytes());
427 bytes.extend_from_slice(nonce);
428 bytes.extend_from_slice(request.as_bytes());
429 bytes
430}
431
432/// The reason a request with a login token but without its device's
433/// signature is refused (#158).
434pub const NOT_PROVEN: &str = "this login needs this device's signature: log in again (with a teter \
435 that signs its requests)";
436
437/// The reason a login without a device key is refused (#158).
438pub const NO_DEVICE_KEY: &str = "a login needs this device's key: upgrade teter";
439
440/// A change of the account's keys (#89): the new public keys, signed by the
441/// old signing key. Machines pinned to the old keys follow it; a relay cannot
442/// make one without the account's old private key.
443#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
444pub struct KeyRotation {
445 /// The public keys it replaces (X25519, then Ed25519).
446 pub old_keys: Vec<u8>,
447 /// The public keys that replace them.
448 pub new_keys: Vec<u8>,
449 /// When it was signed (Unix seconds).
450 pub at: i64,
451 /// The old signing key's signature of [`rotation_bytes`].
452 pub signature: Vec<u8>,
453}
454
455/// What the old signing key signs for a [`KeyRotation`].
456pub fn rotation_bytes(old_keys: &[u8], new_keys: &[u8], at: i64) -> Vec<u8> {
457 let mut bytes = b"teter-key-rotation-v1 ".to_vec();
458 bytes.extend_from_slice(
459 &u32::try_from(old_keys.len())
460 .unwrap_or(u32::MAX)
461 .to_be_bytes(),
462 );
463 bytes.extend_from_slice(old_keys);
464 bytes.extend_from_slice(new_keys);
465 bytes.extend_from_slice(&at.to_be_bytes());
466 bytes
467}
468
469/// The most key rotations a relay keeps per account, newest last: a machine
470/// pinned to keys older than these registers again.
471pub const MAX_ROTATIONS: usize = 64;
472
473/// A machine's name and approval under the account's new keys, which the
474/// device that rotates them gives (#89).
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476pub struct MachineRekey {
477 /// The machine's ID.
478 pub id: String,
479 /// Its display name, sealed to the new keys.
480 pub sealed_name: Vec<u8>,
481 /// The new keys' approval of it ([`cert_bytes`]).
482 pub cert: Vec<u8>,
483}
484
485/// How far a machine's `Unregister` time may be from the relay's, in seconds.
486pub const UNREGISTER_WINDOW: i64 = 300;
487
488/// What a machine signs to unregister: this prefix, its ID, and the time.
489pub fn unregister_message(machine: &str, at: i64) -> Vec<u8> {
490 let mut message = b"teter-unregister-v1 ".to_vec();
491 message.extend_from_slice(machine.as_bytes());
492 message.extend_from_slice(&at.to_be_bytes());
493 message
494}
495
496/// A machine as the relay lists it to its account.
497#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
498pub struct MachineInfo {
499 /// Its ID.
500 pub id: String,
501 /// Its display name, sealed to the account.
502 pub sealed_name: Vec<u8>,
503 /// When it last connected (Unix seconds), if it has.
504 pub last_seen: Option<i64>,
505 /// Its public key (#133).
506 #[serde(default)]
507 pub public_key: Vec<u8>,
508 /// Its proof it held the token (see [`AccountRequest::Register`]).
509 #[serde(default)]
510 pub binding: Vec<u8>,
511 /// The account's approval, empty before one.
512 #[serde(default)]
513 pub cert: Vec<u8>,
514}
515
516/// The longest a registration token works: 30 days.
517pub const MAX_TOKEN_LIFETIME: u64 = 30 * 24 * 3600;
518
519/// The most machines one registration token registers.
520pub const MAX_TOKEN_USES: u32 = 100;
521
522/// A registration token as the relay lists it: never its secret.
523#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
524pub struct TokenInfo {
525 /// Its ID: the SHA-256 of its secret, hex.
526 pub id: String,
527 /// When it was made (Unix seconds).
528 pub created: i64,
529 /// When it stops working (Unix seconds).
530 pub expires: i64,
531 /// How many more machines it registers.
532 pub uses_left: i64,
533}
534
535/// The relay's reply to an [`AccountRequest`].
536#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
537#[non_exhaustive]
538pub enum AccountReply {
539 /// The salt asked for.
540 Salt {
541 /// The salt and key derivation parameters.
542 salt: Vec<u8>,
543 },
544 /// The account was made.
545 SignedUp,
546 /// Logged in: a token for the relay, and the account's keys, the private
547 /// ones still wrapped.
548 LoggedIn {
549 /// The login token.
550 token: String,
551 /// The account's public keys.
552 public_keys: Vec<u8>,
553 /// The account's private keys, wrapped.
554 wrapped_keys: Vec<u8>,
555 /// The device's ID on the relay (#154).
556 #[serde(default)]
557 device: String,
558 /// After a pairing (#154): the account's private keys, sealed to the
559 /// device by the device that approved it ([`device_keys_info`]);
560 /// after a recovery, the keys the recovery code wraps. Empty
561 /// otherwise.
562 #[serde(default, skip_serializing_if = "Vec::is_empty")]
563 sealed_keys: Vec<u8>,
564 },
565 /// The login waits for an approved device's approval (#154).
566 PairingPending {
567 /// The secret to ask with ([`AccountRequest::PairingPoll`]); empty
568 /// in the answer to a poll.
569 request: String,
570 /// The device's ID.
571 device: String,
572 /// When the request expires (Unix seconds).
573 expires: i64,
574 },
575 /// The account's devices (#154).
576 Devices {
577 /// The devices, oldest first.
578 devices: Vec<DeviceInfo>,
579 /// The relay's clock (Unix seconds).
580 now: i64,
581 },
582 /// Whether a waiting device was approved (`false`: none such waits).
583 DeviceApproved {
584 /// Whether it was.
585 approved: bool,
586 },
587 /// Whether a device was removed (`false`: no such device).
588 DeviceRemoved {
589 /// Whether it was.
590 removed: bool,
591 },
592 /// The device was named.
593 DeviceRenamed,
594 /// The recovery codes were replaced.
595 RecoveryCodesSet,
596 /// The password was proven again: sensitive requests work until
597 /// `until` (Unix seconds).
598 Reauthed {
599 /// When the re-authentication ends.
600 until: i64,
601 },
602 /// The login session ended (or there was none).
603 LoggedOut,
604 /// The registration token was made.
605 TokenCreated,
606 /// The account's registration tokens, oldest first.
607 Tokens {
608 /// The tokens.
609 tokens: Vec<TokenInfo>,
610 /// The relay's clock (Unix seconds), which the expiries are on; 0
611 /// from a relay that does not send it.
612 #[serde(default)]
613 now: i64,
614 },
615 /// Whether a registration token was revoked (`false`: no such token).
616 TokenRevoked {
617 /// Whether it was.
618 revoked: bool,
619 },
620 /// The public keys of a registration token's account.
621 AccountKeys {
622 /// The account's public keys.
623 public_keys: Vec<u8>,
624 },
625 /// The machine is registered.
626 Registered {
627 /// Its ID, which it says hello with.
628 machine: String,
629 },
630 /// The account's machines.
631 Machines {
632 /// The machines.
633 machines: Vec<MachineInfo>,
634 },
635 /// Whether a machine was removed (`false`: no such machine).
636 MachineRemoved {
637 /// Whether it was.
638 removed: bool,
639 },
640 /// Whether a machine was approved (`false`: no such machine).
641 MachineApproved {
642 /// Whether it was.
643 approved: bool,
644 },
645 /// The account's machines and their sessions.
646 Sessions {
647 /// The machines.
648 machines: Vec<MachineSessions>,
649 /// The account's limits on this relay (#104); `None` from a relay
650 /// older than them.
651 #[serde(default, skip_serializing_if = "Option::is_none")]
652 limits: Option<AccountLimits>,
653 },
654 /// The password was changed: the new login (every other ended).
655 PasswordChanged {
656 /// The login token.
657 token: String,
658 },
659 /// The keys were replaced: the new login (every other ended).
660 KeysRotated {
661 /// The login token.
662 token: String,
663 },
664 /// Refused, and why. A failed login says only that the name or the
665 /// password is wrong, never which.
666 Refused {
667 /// Why.
668 reason: String,
669 },
670}
671
672/// A device of an account, as the relay lists it (#154).
673#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
674pub struct DeviceInfo {
675 /// Its ID.
676 pub id: String,
677 /// Its Ed25519 public key (#158), whose pairing code it shows
678 /// (`teter_core::account::pairing_code`); the account's keys are sealed
679 /// to its X25519 form when it is approved.
680 pub public_key: Vec<u8>,
681 /// Its name, sealed to the account by itself; empty before it named
682 /// itself (a device waiting has none).
683 pub sealed_name: Vec<u8>,
684 /// When it asked to log in (Unix seconds).
685 pub created: i64,
686 /// When it last used a login (Unix seconds).
687 pub last_seen: Option<i64>,
688 /// Whether the account approved it; else it waits until `expires`.
689 pub approved: bool,
690 /// When its pairing request expires, while it waits.
691 pub expires: Option<i64>,
692 /// The address its login came from, as the relay saw it.
693 pub address: String,
694 /// Whether it is the device asking.
695 pub current: bool,
696}
697
698/// A recovery code as the relay keeps it (#154): the SHA-256 of its auth key
699/// to check it, and the account's private keys wrapped under its wrapping
700/// key, to give a device back the keys when no approved device is left.
701/// Both keys come from the code (HKDF), which never reaches the relay.
702#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
703pub struct RecoveryCode {
704 /// The SHA-256 of the code's auth key.
705 pub auth_hash: Vec<u8>,
706 /// The account's private keys, wrapped under the code's wrapping key.
707 pub wrapped_keys: Vec<u8>,
708}
709
710/// How many recovery codes signup makes (#154).
711pub const RECOVERY_CODES: usize = 10;
712
713/// How long a device waits for its approval (#154), in seconds.
714pub const PAIRING_WAIT: i64 = 600;
715
716/// The most devices waiting for an approval at once, per account (#154).
717pub const MAX_PENDING_DEVICES: usize = 5;
718
719/// The most devices an account has (#154).
720pub const MAX_DEVICES: usize = 64;
721
722/// How long a login lasts unused (#157), in seconds: 7 days, renewed while
723/// it is used.
724pub const LOGIN_LIFETIME: i64 = 7 * 24 * 3600;
725
726/// How long a login lasts at most, however much it is used (#157): 30 days.
727pub const LOGIN_MAX_AGE: i64 = 30 * 24 * 3600;
728
729/// How long a re-authentication lasts (#157), in seconds.
730pub const REAUTH_WINDOW: i64 = 300;
731
732/// The reason a sensitive request is refused without a recent
733/// re-authentication (#157).
734pub const REAUTH_NEEDED: &str = "this needs the password again (teter asks it): re-authenticate";
735
736/// How far a login's device proof time may be from the relay's, in seconds
737/// (#154).
738pub const DEVICE_PROOF_WINDOW: i64 = 300;
739
740/// What a device signs to log in to account `name` (#154): this prefix, the
741/// name, the time, and the SHA-256 of the auth key it presents, so the
742/// signature goes with that login only.
743pub fn device_login_bytes(name: &str, at: i64, auth_key_hash: &[u8]) -> Vec<u8> {
744 let mut bytes = b"teter-device-login-v1 ".to_vec();
745 bytes.extend_from_slice(name.as_bytes());
746 bytes.push(0);
747 bytes.extend_from_slice(&at.to_be_bytes());
748 bytes.extend_from_slice(auth_key_hash);
749 bytes
750}
751
752/// What a device's name is sealed to the account with (#154).
753pub const DEVICE_NAME_INFO: &[u8] = b"device name";
754
755/// What the account's private keys are sealed to device `device` with
756/// when an approved device approves it (#154): bound to it.
757pub fn device_keys_info(device: &str) -> Vec<u8> {
758 format!("device keys {device}").into_bytes()
759}
760
761/// The reason a login is refused, whatever was wrong.
762pub const WRONG_LOGIN: &str = "wrong account name or password";
763
764/// The reason an account request is refused when its login token is not
765/// (or no longer) a login.
766pub const NOT_LOGGED_IN: &str = "not logged in (or the login expired): run teter login";
767
768/// The prefix of a registration token's text.
769pub const REGISTRATION_PREFIX: &str = "teter-reg1";
770
771/// A registration token, as the logged-in user hands it to the machine to
772/// register: the relay's URL, the enrollment secret, and the fingerprint of
773/// the account's public keys, which the machine checks the keys the relay
774/// gives it against (#86), so a relay cannot swap the account's keys.
775#[derive(Clone, PartialEq, Eq)]
776pub struct Registration {
777 /// The relay's URL.
778 pub relay: String,
779 /// The enrollment secret.
780 pub secret: [u8; 32],
781 /// The fingerprint of the account's public keys.
782 pub fingerprint: [u8; 16],
783}
784
785impl std::fmt::Debug for Registration {
786 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
787 f.debug_struct("Registration")
788 .field("relay", &self.relay)
789 .finish_non_exhaustive()
790 }
791}
792
793impl Registration {
794 /// Its text: `teter-reg1.<relay, hex>.<secret, hex>.<fingerprint, hex>`.
795 pub fn to_text(&self) -> String {
796 format!(
797 "{REGISTRATION_PREFIX}.{}.{}.{}",
798 hex(self.relay.as_bytes()),
799 hex(&self.secret),
800 hex(&self.fingerprint)
801 )
802 }
803
804 /// The token `text` holds, if it is one.
805 pub fn parse(text: &str) -> Option<Self> {
806 let mut parts = text.trim().split('.');
807 let (Some(prefix), Some(relay), Some(secret), Some(fingerprint), None) = (
808 parts.next(),
809 parts.next(),
810 parts.next(),
811 parts.next(),
812 parts.next(),
813 ) else {
814 return None;
815 };
816 if prefix != REGISTRATION_PREFIX {
817 return None;
818 }
819 Some(Self {
820 relay: String::from_utf8(unhex(relay)?).ok()?,
821 secret: unhex(secret)?.try_into().ok()?,
822 fingerprint: unhex(fingerprint)?.try_into().ok()?,
823 })
824 }
825}
826
827/// `bytes`, hex.
828pub fn hex(bytes: &[u8]) -> String {
829 bytes.iter().map(|b| format!("{b:02x}")).collect()
830}
831
832/// The bytes `text` holds in hex, if it is hex.
833pub fn unhex(text: &str) -> Option<Vec<u8>> {
834 if !text.len().is_multiple_of(2) || !text.bytes().all(|b| b.is_ascii_hexdigit()) {
835 return None;
836 }
837 text.as_bytes()
838 .chunks(2)
839 .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok())
840 .collect()
841}
842
843/// The reason a relay refuses a machine it does not know (removed from its
844/// account, or never registered there): the one refusal after which a link
845/// stops for good (#138), not after a passing failure.
846pub const MACHINE_UNKNOWN: &str = "this relay does not know this machine (removed from its account, or registered with another relay?)";
847
848/// The reason a relay refuses a machine's proof: a signature its registered
849/// key did not make (#147). It begins as the other authentication failures
850/// do, which links before it looked for.
851pub const PROOF_REFUSED: &str = "authentication failed: the machine's proof does not match the key registered for it (another machine's key?)";
852
853/// The reason a registration token is refused, whatever was wrong with it
854/// (unknown, expired, used up, revoked).
855pub const BAD_TOKEN: &str = "this registration token does not work (unknown, expired, used up or \
856 revoked; or made by a teter older than 26.11.3: make a new one)";
857
858/// An account's limits on its relay (#104), each `None` for none, and what
859/// it used this month: what a device checks before it asks for more (a new
860/// session past the limit would run on its machine, but the relay would keep
861/// no record of it).
862#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
863pub struct AccountLimits {
864 /// Machines registered.
865 pub machines: Option<u64>,
866 /// Sessions kept, over all its machines.
867 pub sessions: Option<u64>,
868 /// Bytes a second its machines and devices send through the relay.
869 pub rate: Option<u64>,
870 /// Bytes a month (UTC) they send.
871 pub monthly: Option<u64>,
872 /// Bytes they sent this month.
873 pub used: u64,
874}
875
876impl AccountLimits {
877 /// Why a new session is refused when the account keeps `kept` sessions
878 /// already, if it is.
879 #[must_use]
880 pub fn no_room_for_a_session(&self, kept: usize) -> Option<String> {
881 let at = self.sessions?;
882 (u64::try_from(kept).unwrap_or(u64::MAX) >= at).then(|| {
883 format!(
884 "this account has {kept} sessions, the most its relay allows it ({at}): end one \
885 (teter kill machine:session), or ask the relay's admin for more"
886 )
887 })
888 }
889}
890
891/// A machine of the account and its sessions, as [`AccountReply::Sessions`]
892/// gives them.
893#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
894pub struct MachineSessions {
895 /// The machine's ID.
896 pub id: String,
897 /// Its display name, sealed to the account.
898 pub sealed_name: Vec<u8>,
899 /// Its public key (Ed25519), which signs its command challenges (#88);
900 /// empty from a relay older than that.
901 #[serde(default)]
902 pub public_key: Vec<u8>,
903 /// The account's approval of the machine (#133), empty before one.
904 #[serde(default)]
905 pub cert: Vec<u8>,
906 /// The relay session it is served on now, and the token a frontend joins
907 /// it with; `None` while it is not connected.
908 pub relay: Option<(crate::SessionId, String)>,
909 /// Its sessions.
910 pub sessions: Vec<SessionRecordInfo>,
911}
912
913/// One of a machine's sessions: its channel, its name and key sealed to the
914/// account.
915#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
916pub struct SessionRecordInfo {
917 /// The channel it travels on inside the machine's relay session.
918 pub channel: String,
919 /// The relay session that serves it now, and the token to join it;
920 /// `None` while no link of its machine serves it.
921 pub relay: Option<(crate::SessionId, String)>,
922 /// Its name, sealed to the account.
923 pub sealed_name: Vec<u8>,
924 /// Its end-to-end secret, sealed to the account for its channel.
925 pub sealed_key: Vec<u8>,
926 /// The machine's signature of [`record_bytes`] (#133).
927 #[serde(default)]
928 pub signature: Vec<u8>,
929 /// How many frontends are attached to it now (#135); `None` from a
930 /// relay older than the field.
931 #[serde(default)]
932 pub clients: Option<u32>,
933}
934
935/// What a machine signs to show it held its registration token: its key and
936/// its sealed name (#133).
937pub fn binding_bytes(machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
938 let mut bytes = b"teter-machine-bind-v1 ".to_vec();
939 bytes.extend_from_slice(machine_key);
940 bytes.extend_from_slice(sealed_name);
941 bytes
942}
943
944/// What the account signs to approve machine `id` (#133): its key and its
945/// sealed name, so a relay can neither swap a machine's key nor move its
946/// name.
947pub fn cert_bytes(id: &str, machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
948 let mut bytes = b"teter-machine-cert-v1 ".to_vec();
949 bytes.extend_from_slice(id.as_bytes());
950 bytes.push(0);
951 bytes.extend_from_slice(machine_key);
952 bytes.extend_from_slice(sealed_name);
953 bytes
954}
955
956/// What a machine's display name is sealed to the account with (#86).
957pub const MACHINE_NAME_INFO: &[u8] = b"machine name";
958
959/// What the name of machine `machine`'s session on `channel` is sealed to
960/// the account with (#87): bound to both, so a relay cannot move a name onto
961/// another record.
962pub fn session_name_info(machine: &str, channel: &str) -> Vec<u8> {
963 format!("session name {machine} {channel}").into_bytes()
964}
965
966/// What a session's end-to-end secret is sealed to the account with (#87),
967/// bound to its channel.
968pub fn session_key_info(channel: &str) -> Vec<u8> {
969 let mut info = b"session key ".to_vec();
970 info.extend_from_slice(channel.as_bytes());
971 info
972}
973
974/// What machine `machine` signs for its session on `channel` (#133).
975pub fn record_bytes(
976 machine: &str,
977 channel: &str,
978 sealed_name: &[u8],
979 sealed_key: &[u8],
980) -> Vec<u8> {
981 let mut bytes = b"teter-record-v1 ".to_vec();
982 bytes.extend_from_slice(machine.as_bytes());
983 bytes.push(0);
984 bytes.extend_from_slice(channel.as_bytes());
985 bytes.push(0);
986 bytes.extend_from_slice(
987 &u32::try_from(sealed_name.len())
988 .unwrap_or(u32::MAX)
989 .to_be_bytes(),
990 );
991 bytes.extend_from_slice(sealed_name);
992 bytes.extend_from_slice(sealed_key);
993 bytes
994}
995
996#[cfg(test)]
997mod proof_tests {
998 use super::*;
999
1000 #[test]
1001 fn requests_with_a_login_name_their_token_and_the_others_none() {
1002 let list = AccountRequest::MachineList {
1003 login: "tok".into(),
1004 };
1005 assert_eq!(list.login_token(), Some("tok"));
1006 let logout = AccountRequest::Logout {
1007 token: "out".into(),
1008 all: false,
1009 };
1010 assert_eq!(logout.login_token(), Some("out"));
1011 let salt = AccountRequest::Salt { name: "n".into() };
1012 assert_eq!(salt.login_token(), None);
1013 }
1014
1015 #[test]
1016 fn proof_bytes_bind_time_nonce_and_request() {
1017 let base = proof_bytes("{}", 1, &[0; PROOF_NONCE_LEN]);
1018 assert!(base.starts_with(b"teter-device-proof-v1 "));
1019 assert_ne!(base, proof_bytes("{} ", 1, &[0; PROOF_NONCE_LEN]));
1020 assert_ne!(base, proof_bytes("{}", 2, &[0; PROOF_NONCE_LEN]));
1021 assert_ne!(base, proof_bytes("{}", 1, &[1; PROOF_NONCE_LEN]));
1022 // The nonce's length is in it: bytes cannot move between nonce and request.
1023 assert_ne!(proof_bytes("b{}", 1, b"a"), proof_bytes("{}", 1, b"ab"));
1024 }
1025
1026 #[test]
1027 fn a_login_from_before_device_keys_reads_with_none() {
1028 let old = r#"{"Login":{"name":"n","auth_key":[1]}}"#;
1029 let request: AccountRequest = serde_json::from_str(old).unwrap_or_else(|e| panic!("{e}"));
1030 assert_eq!(
1031 request,
1032 AccountRequest::Login {
1033 name: "n".into(),
1034 auth_key: vec![1],
1035 device_key: Vec::new(),
1036 at: 0,
1037 device_proof: Vec::new(),
1038 recovery: Vec::new(),
1039 }
1040 );
1041 }
1042}