spoolframe-protocol 0.16.4-beta.2

The spoolframe/client/1 wire protocol.
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
//! Passkeys in the apps, each server through a relying party of
//! its own under `spoolframe.app`: [`ServerId::rp_id`].
//!
//! A platform's passkey API works only for a domain the app is associated
//! with when it is built; a self-hosted server's own domain is not known
//! then. So the apps make and use their passkeys for
//! `<server id>.spoolframe.app`, which one association file at
//! `spoolframe.app` covers, with a wildcard. Sign-in runs between the app
//! and the server over this protocol; the server never contacts
//! `spoolframe.app`.
//!
//! Because each server has its own relying party, a security key with
//! passkeys for two servers offers only the right server's at a sign-in.
//! A passkey made for `spoolframe.app` itself ([`LEGACY_APP_RP_ID`]) signs
//! in nowhere: its user adds it again.
//!
//! Every server keeps its own passkeys, so a passkey made on one is
//! refused by another. Each user has a random user handle per server, so
//! one server's says nothing about the same person on another.
//!
//! The relying party comes from the server id the server names in
//! `ServerInfo`, and a server may name another's. So the challenge still
//! names the server by its key: a server sends a random
//! nonce, never a challenge, and the challenge is [`app_passkey_challenge`]
//! of the server's endpoint id and that nonce. The server computes it with
//! its own id; the client with the id it pinned and dialled, never one the
//! server names. A server that claims another's server id and hands on
//! its nonce, to relay a sign-in, has the app sign a challenge for itself,
//! which the other refuses.
//!
//! The bytes are WebAuthn's own, as the platform API gives and takes them;
//! the app maps them to and from it and changes nothing.

use std::fmt;

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::server_id::{APP_RP_DOMAIN, ServerId};

/// The relying party shared by all servers, with no server id. A passkey
/// stored with it signs in nowhere: its user adds it again.
pub const LEGACY_APP_RP_ID: &str = APP_RP_DOMAIN;

/// Whether a passkey made for `rp_id` was made in an app: for a server's
/// relying party ([`ServerId::rp_id`]), or the one all shared before.
pub fn is_app_rp_id(rp_id: &str) -> bool {
    rp_id == LEGACY_APP_RP_ID
        || rp_id
            .strip_suffix(APP_RP_DOMAIN)
            .and_then(|id| id.strip_suffix('.'))
            .is_some_and(|id| ServerId::parse(id).is_ok())
}

/// Bytes of a nonce a server sends.
pub const NONCE_LEN: usize = 32;

/// What [`app_passkey_challenge`] hashes first, so its digest is of use
/// for nothing else.
const CHALLENGE_TAG: &[u8] = b"spoolframe/app-passkey-challenge/1";

/// The WebAuthn challenge for an app passkey ceremony with the server
/// whose endpoint id is `server`, from the `nonce` it sent: SHA-256 of
/// `CHALLENGE_TAG`, the 32 bytes of the id, then the nonce. The tag and
/// the id are of fixed length, so nothing else hashes the same.
pub fn app_passkey_challenge(server: &[u8; 32], nonce: &[u8]) -> Vec<u8> {
    Sha256::new()
        .chain_update(CHALLENGE_TAG)
        .chain_update(server)
        .chain_update(nonce)
        .finalize()
        .to_vec()
}

/// A server's answer to `BeginPasskeyRegistration`, on the wire: a nonce,
/// not a challenge. [`PasskeyRegistrationBegun::for_server`] makes the
/// [`PasskeyCreation`] the platform is given.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PasskeyRegistrationBegun {
    /// Of use once, for 5 minutes, from this device.
    #[serde(with = "serde_bytes")]
    pub nonce: Vec<u8>,
    /// The user handle: random, this server's for this user.
    #[serde(with = "serde_bytes")]
    pub user_id: Vec<u8>,
    /// As [`PasskeyCreation::user_name`].
    pub user_name: String,
    /// As [`PasskeyCreation::display_name`].
    pub display_name: String,
    /// As [`PasskeyCreation::exclude_credential_ids`].
    #[serde(with = "byte_strings")]
    pub exclude_credential_ids: Vec<Vec<u8>>,
}

impl PasskeyRegistrationBegun {
    /// What the platform makes the passkey with, for the server whose
    /// endpoint id is `server`, the one the client dialled, and whose
    /// server id is `server_id`, the one it pinned with it.
    pub fn for_server(self, server: &[u8; 32], server_id: &ServerId) -> PasskeyCreation {
        PasskeyCreation {
            rp_id: server_id.rp_id(),
            origin: server_id.origin(),
            challenge: app_passkey_challenge(server, &self.nonce),
            user_id: self.user_id,
            user_name: self.user_name,
            display_name: self.display_name,
            exclude_credential_ids: self.exclude_credential_ids,
        }
    }
}

/// A server's answer to `BeginPasskeySignIn` and `BeginConfirmPasskey`,
/// on the wire: a nonce, not a challenge.
/// [`PasskeySignInBegun::for_server`] makes the [`PasskeyRequest`] the
/// platform is given.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PasskeySignInBegun {
    /// Of use once, for 5 minutes, from this device.
    #[serde(with = "serde_bytes")]
    pub nonce: Vec<u8>,
    /// As [`PasskeyRequest::allow_credential_ids`]. Always empty for
    /// `BeginPasskeySignIn`: anyone can begin one.
    #[serde(with = "byte_strings")]
    pub allow_credential_ids: Vec<Vec<u8>>,
}

impl PasskeySignInBegun {
    /// What the platform signs, for the server whose endpoint id is
    /// `server`, the one the client dialled, and whose server id is
    /// `server_id`, the one it pinned with it.
    pub fn for_server(self, server: &[u8; 32], server_id: &ServerId) -> PasskeyRequest {
        PasskeyRequest {
            rp_id: server_id.rp_id(),
            origin: server_id.origin(),
            challenge: app_passkey_challenge(server, &self.nonce),
            allow_credential_ids: self.allow_credential_ids,
        }
    }
}

/// What making a passkey needs: the platform's options. User verification
/// is required. Not on the wire: the client makes it from a
/// [`PasskeyRegistrationBegun`].
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct PasskeyCreation {
    /// The relying party to make it for: the server's,
    /// `<server id>.spoolframe.app`. Never `spoolframe.app` itself.
    pub rp_id: String,
    /// The origin a platform that takes one writes into `clientDataJSON`:
    /// `https://<server id>.spoolframe.app`. The server accepts no other.
    pub origin: String,
    /// To sign: [`app_passkey_challenge`] of the server and its nonce.
    #[serde(with = "serde_bytes")]
    pub challenge: Vec<u8>,
    /// The user handle: random, this server's for this user.
    #[serde(with = "serde_bytes")]
    pub user_id: Vec<u8>,
    /// The account's name in the platform's passkey list,
    /// `<username> @ <server name>`: the relying party is an opaque id, so
    /// the server's name says which server it is.
    pub user_name: String,
    /// The user's display name, or their username without one.
    pub display_name: String,
    /// The user's app passkeys on this server: an authenticator holding
    /// one of these is not to make another.
    #[serde(with = "byte_strings")]
    pub exclude_credential_ids: Vec<Vec<u8>>,
}

/// A passkey made for a [`PasskeyCreation`], to keep
/// (`FinishPasskeyRegistration`).
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct FinishPasskeyRegistration {
    #[serde(with = "serde_bytes")]
    pub credential_id: Vec<u8>,
    /// The attestation object (CBOR), as the platform gave it.
    #[serde(with = "serde_bytes")]
    pub attestation_object: Vec<u8>,
    /// `clientDataJSON`, as the platform gave it.
    #[serde(with = "serde_bytes")]
    pub client_data_json: Vec<u8>,
    /// What the device calls itself; the user's profile shows the passkey
    /// as "Spoolframe app · \<name\>". 1 to 64 characters.
    pub name: String,
}

/// The most characters a name a user types for a device may have: a
/// passkey's, an identity's, a pairing's label.
pub const MAX_NAME_CHARS: usize = 64;

/// `name` as a server takes it: trimmed and cut to [`MAX_NAME_CHARS`]
/// characters, as the apps cut what is typed; `None` when nothing is left.
pub fn fit_name(name: &str) -> Option<String> {
    let name: String = name.trim().chars().take(MAX_NAME_CHARS).collect();
    let name = name.trim_end();
    (!name.is_empty()).then(|| name.to_owned())
}

/// What signing in with a passkey needs: the platform's options. Not on
/// the wire: the client makes it from a [`PasskeySignInBegun`].
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct PasskeyRequest {
    /// The relying party to sign for, as [`PasskeyCreation::rp_id`].
    pub rp_id: String,
    /// The origin, as [`PasskeyCreation::origin`].
    pub origin: String,
    /// To sign: [`app_passkey_challenge`] of the server and its nonce.
    #[serde(with = "serde_bytes")]
    pub challenge: Vec<u8>,
    /// The passkeys that may answer; empty: any the platform finds for
    /// `rp_id` (a discoverable sign-in), so only this server's.
    #[serde(with = "byte_strings")]
    pub allow_credential_ids: Vec<Vec<u8>>,
}

/// A passkey's answer to a [`PasskeyRequest`] (`FinishPasskeySignIn`).
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct FinishPasskeySignIn {
    #[serde(with = "serde_bytes")]
    pub credential_id: Vec<u8>,
    #[serde(with = "serde_bytes")]
    pub authenticator_data: Vec<u8>,
    #[serde(with = "serde_bytes")]
    pub client_data_json: Vec<u8>,
    #[serde(with = "serde_bytes")]
    pub signature: Vec<u8>,
    /// The user handle the authenticator keeps with the passkey, or
    /// `None` when the platform gave none (webauthn-authenticator-rs, for
    /// a phone over caBLE). Never `Some` of no bytes: the server refuses
    /// that as `InvalidInput`. The client SDK sends an empty handle as
    /// `None`. On the wire a CBOR byte string, or null for `None`; the key
    /// is always there.
    #[serde(with = "optional_bytes")]
    pub user_handle: Option<Vec<u8>>,
}

/// One of the session user's passkeys (`ListPasskeys`), the web UI's as
/// well as the apps': the user sees every way they sign in, and the web
/// UI's `me.passkeys` lists the same ones.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct PasskeyInfo {
    /// Its credential id, base64url with no padding, as the web UI names
    /// it: what `RenamePasskey` and `RemovePasskey` take. For an app
    /// passkey, that of the `credential_id` bytes the platform gave.
    pub id: String,
    /// What its user called it; an app passkey's is the device's (the web
    /// UI shows it as "Spoolframe app · \<name\>").
    pub name: String,
    /// Unix seconds.
    pub created_at: i64,
    /// `None` if it has never signed them in.
    pub last_used_at: Option<i64>,
    /// The relying party it was made for: the server's app relying party
    /// ([`ServerId::rp_id`]), [`LEGACY_APP_RP_ID`], or the host of the
    /// server's web UI.
    pub rp_id: String,
    /// Made in a Spoolframe app ([`is_app_rp_id`]).
    pub app: bool,
    /// An app can sign in with it: only an app passkey made for this
    /// server's relying party. One made for [`LEGACY_APP_RP_ID`] is an
    /// app passkey that cannot: list it as old, to add again. A web UI's
    /// is listed so the user sees it, and can rename or remove it.
    pub usable_here: bool,
}

// Byte fields are shown by length: they are not secrets, but a log of
// them says nothing and takes a screen.

impl fmt::Debug for PasskeyCreation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PasskeyCreation")
            .field("rp_id", &self.rp_id)
            .field("user_name", &self.user_name)
            .field("display_name", &self.display_name)
            .field("exclude", &self.exclude_credential_ids.len())
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for PasskeyRegistrationBegun {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PasskeyRegistrationBegun")
            .field("user_name", &self.user_name)
            .field("display_name", &self.display_name)
            .field("exclude", &self.exclude_credential_ids.len())
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for PasskeySignInBegun {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PasskeySignInBegun")
            .field("allow", &self.allow_credential_ids.len())
            .finish_non_exhaustive()
    }
}

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

impl fmt::Debug for PasskeyRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PasskeyRequest")
            .field("rp_id", &self.rp_id)
            .field("allow", &self.allow_credential_ids.len())
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for FinishPasskeySignIn {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FinishPasskeySignIn")
            .field("user_handle", &self.user_handle.as_ref().map(Vec::len))
            .finish_non_exhaustive()
    }
}

/// A list of byte strings, each a CBOR byte string as `serde_bytes` makes
/// one (it has no impl for a list of them).
mod byte_strings {
    use serde::{Deserialize, Deserializer, Serializer};
    use serde_bytes::{ByteBuf, Bytes};

    pub fn serialize<S: Serializer>(list: &[Vec<u8>], serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_seq(list.iter().map(|bytes| Bytes::new(bytes)))
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Vec<Vec<u8>>, D::Error> {
        let list = Vec::<ByteBuf>::deserialize(deserializer)?;
        Ok(list.into_iter().map(ByteBuf::into_vec).collect())
    }
}

/// An optional byte string: CBOR bytes, or null. Its field is required:
/// `with` makes serde ask for it, as it does not for a plain `Option`.
mod optional_bytes {
    use serde::{Deserialize, Deserializer, Serializer};
    use serde_bytes::{ByteBuf, Bytes};

    pub fn serialize<S: Serializer>(
        bytes: &Option<Vec<u8>>,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        match bytes {
            Some(bytes) => serializer.serialize_some(Bytes::new(bytes)),
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Option<Vec<u8>>, D::Error> {
        Ok(Option::<ByteBuf>::deserialize(deserializer)?.map(ByteBuf::into_vec))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_name_is_trimmed_and_cut_to_64_characters() {
        assert_eq!(
            fit_name("  Living room TV \n").as_deref(),
            Some("Living room TV")
        );
        assert_eq!(fit_name(" \t"), None);
        let long = "é".repeat(70);
        assert_eq!(fit_name(&long).unwrap().chars().count(), 64);
        let spaced = format!("{} b", "a".repeat(63));
        assert_eq!(fit_name(&spaced), Some("a".repeat(63)));
    }

    const NONCE: [u8; NONCE_LEN] = [7; NONCE_LEN];

    #[test]
    fn the_challenge_differs_for_another_server_with_the_same_nonce() {
        assert_ne!(
            app_passkey_challenge(&[1; 32], &NONCE),
            app_passkey_challenge(&[2; 32], &NONCE)
        );
    }

    #[test]
    fn the_challenge_is_the_tagged_sha256_of_the_server_and_nonce() {
        let mut bytes = b"spoolframe/app-passkey-challenge/1".to_vec();
        bytes.extend([1; 32]);
        bytes.extend(NONCE);
        assert_eq!(
            app_passkey_challenge(&[1; 32], &NONCE),
            Sha256::digest(&bytes).to_vec()
        );
    }

    fn server_id() -> ServerId {
        ServerId::parse("mzxw6ytbojtg633c").unwrap()
    }

    #[test]
    fn a_request_for_a_server_signs_its_challenge_for_its_relying_party() {
        let begun = PasskeySignInBegun {
            nonce: NONCE.to_vec(),
            allow_credential_ids: vec![vec![4]],
        };
        assert_eq!(
            begun.for_server(&[1; 32], &server_id()),
            PasskeyRequest {
                rp_id: "mzxw6ytbojtg633c.spoolframe.app".into(),
                origin: "https://mzxw6ytbojtg633c.spoolframe.app".into(),
                challenge: app_passkey_challenge(&[1; 32], &NONCE),
                allow_credential_ids: vec![vec![4]],
            }
        );
    }

    #[test]
    fn a_creation_for_a_server_is_for_its_relying_party() {
        let begun = PasskeyRegistrationBegun {
            nonce: NONCE.to_vec(),
            user_id: vec![9],
            user_name: "alice @ Nimble".into(),
            display_name: "Alice".into(),
            exclude_credential_ids: Vec::new(),
        };
        let creation = begun.for_server(&[1; 32], &server_id());
        assert_eq!(
            (creation.rp_id.as_str(), creation.origin.as_str()),
            (
                "mzxw6ytbojtg633c.spoolframe.app",
                "https://mzxw6ytbojtg633c.spoolframe.app"
            )
        );
        assert_eq!(creation.challenge, app_passkey_challenge(&[1; 32], &NONCE));
    }

    #[test]
    fn app_passkeys_are_known_by_their_relying_party() {
        for app in ["spoolframe.app", "mzxw6ytbojtg633c.spoolframe.app"] {
            assert!(is_app_rp_id(app), "{app}");
        }
        for not in [
            "media.example.org",
            "localhost",
            "evil.spoolframe.app",
            "mzxw6ytbojtg633c.spoolframe.app.example.org",
            "mzxw6ytbojtg633cspoolframe.app",
        ] {
            assert!(!is_app_rp_id(not), "{not}");
        }
    }
}