Skip to main content

nibkeep_governance/
pairing.rs

1//! Pairing a new replica, the joiner, with one that holds the library, the sponsor: the code
2//! that the person types, the key that SPAKE2 agrees on from it, the joiner's request and
3//! the sponsor's grant ([Sync](../../../docs/spec/sync.md#2-pairing)).
4
5use std::collections::BTreeMap;
6use std::fmt;
7use std::str::FromStr;
8
9use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value};
10use nibkeep_base::{EntityId, SpaceId};
11use nibkeep_crypto::rand_core::CryptoRng;
12use nibkeep_crypto::{
13	CryptoError, DecryptionKey, EncryptionKey, Key, Pake, PakeSide, SealedMessage, VerifyingKey,
14};
15
16/// What a sponsor adds to what it announces on the network while it pairs, followed by the
17/// first two digits of the code.
18pub const PAIRING_PREFIX: &str = "nibkeep-pair-";
19
20/// What an admin adds to what it announces on the network while it invites someone to a
21/// space, followed by the first two digits of the code: apart from pairing's, so that a
22/// joiner never reaches a sponsor, nor a new replica an admin.
23pub const INVITATION_PREFIX: &str = "nibkeep-invite-";
24
25/// The context of the space keys sealed to the joiner.
26pub(crate) const SPACE_KEYS: &str = "nibkeep 2026-10 space keys";
27
28/// How long the name of a device or an app in a request may be, in bytes.
29pub const MAX_NAME_LEN: usize = 200;
30
31/// A code that pairs two replicas once: eight decimal digits, the first two from 10 to 99,
32/// which find the sponsor on the network, and six more that are secret. It is shown as
33/// `37-482-177`, and never printed in full by `Debug`.
34#[derive(Clone, PartialEq, Eq)]
35pub struct PairingCode([u8; 8]);
36
37impl PairingCode {
38	/// A new random code.
39	pub fn generate(rng: &mut impl CryptoRng) -> Self {
40		let mut digits = [0; 8];
41		digits[0] = random_below(rng, 9) + 1;
42		for digit in &mut digits[1..] {
43			*digit = random_below(rng, 10);
44		}
45		Self(digits)
46	}
47
48	/// The code's first two digits, from 10 to 99, which find the sponsor.
49	#[must_use]
50	pub fn nameplate(&self) -> u8 {
51		self.0[0] * 10 + self.0[1]
52	}
53
54	/// What the sponsor announces on the network while it pairs with this code.
55	#[must_use]
56	pub fn announcement(&self) -> String {
57		format!("{PAIRING_PREFIX}{}", self.nameplate())
58	}
59
60	/// What an admin announces on the network while it invites someone with this code.
61	#[must_use]
62	pub fn invitation_announcement(&self) -> String {
63		format!("{INVITATION_PREFIX}{}", self.nameplate())
64	}
65
66	/// SPAKE2's password: the eight digits in ASCII.
67	fn password(&self) -> [u8; 8] {
68		self.0.map(|digit| b'0' + digit)
69	}
70}
71
72/// A random number below `bound`, which is at most 10, without bias.
73fn random_below(rng: &mut impl CryptoRng, bound: u8) -> u8 {
74	// The largest multiple of `bound` that a byte holds: bytes at or above it are drawn again.
75	let limit = 256 - 256 % u16::from(bound);
76	loop {
77		let mut byte = [0];
78		rng.fill_bytes(&mut byte);
79		if u16::from(byte[0]) < limit {
80			return byte[0] % bound;
81		}
82	}
83}
84
85impl fmt::Display for PairingCode {
86	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87		for (place, digit) in self.0.iter().enumerate() {
88			if place == 2 || place == 5 {
89				f.write_str("-")?;
90			}
91			write!(f, "{digit}")?;
92		}
93		Ok(())
94	}
95}
96
97impl fmt::Debug for PairingCode {
98	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99		write!(f, "PairingCode({}-…)", self.nameplate())
100	}
101}
102
103/// Why text is not a pairing code.
104#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
105#[error("a pairing code is eight digits, such as 37-482-177")]
106pub struct NotACode;
107
108impl FromStr for PairingCode {
109	type Err = NotACode;
110
111	/// Reads a code as it is shown, or with spaces or no separators: eight digits, the first
112	/// not 0.
113	fn from_str(text: &str) -> Result<Self, NotACode> {
114		let mut digits = Vec::new();
115		for character in text.trim().chars() {
116			match character {
117				'0'..='9' => digits.push(character as u8 - b'0'),
118				'-' | ' ' => {}
119				_ => return Err(NotACode),
120			}
121		}
122		let digits: [u8; 8] = digits.try_into().map_err(|_| NotACode)?;
123		if digits[0] == 0 {
124			return Err(NotACode);
125		}
126		Ok(Self(digits))
127	}
128}
129
130/// Which side of pairing a replica takes.
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132pub enum Side {
133	/// The replica that holds the library, and shows the code.
134	Sponsor,
135	/// The new replica, on whose device the code is typed.
136	Joiner,
137}
138
139impl Side {
140	/// The side's name in tags.
141	const fn name(self) -> &'static str {
142		match self {
143			Self::Sponsor => "sponsor",
144			Self::Joiner => "joiner",
145		}
146	}
147}
148
149/// One side of SPAKE2 for pairing, between its own message and the other side's.
150#[derive(Debug)]
151pub struct Pairing(Pake);
152
153impl Pairing {
154	/// Starts pairing with `code` as `side`, and returns the message to send.
155	pub fn start(side: Side, code: &PairingCode, rng: &mut impl CryptoRng) -> (Self, Vec<u8>) {
156		let pake_side = match side {
157			Side::Sponsor => PakeSide::A,
158			Side::Joiner => PakeSide::B,
159		};
160		let (pake, message) = Pake::start(
161			pake_side,
162			&code.password(),
163			b"nibkeep sponsor",
164			b"nibkeep joiner",
165			rng,
166		);
167		(Self(pake), message)
168	}
169
170	/// Finishes SPAKE2 with the other side's message, and derives the pairing key, bound to
171	/// the connection by `binding`.
172	///
173	/// # Errors
174	///
175	/// Returns [`CryptoError::Pake`] if the message is not one of the other side's.
176	pub fn finish(self, message: &[u8], binding: &[u8; 32]) -> Result<PairingKey, CryptoError> {
177		self.finish_with("nibkeep 2026-10 pairing", message, binding)
178	}
179
180	/// Finishes SPAKE2 as [`Pairing::finish`] does, for an invitation to a space: the key is
181	/// derived with a context of its own, so that a code shown to pair never works as an
182	/// invitation, nor one shown to invite as a pairing.
183	///
184	/// # Errors
185	///
186	/// Returns [`CryptoError::Pake`] if the message is not one of the other side's.
187	pub fn finish_invitation(
188		self,
189		message: &[u8],
190		binding: &[u8; 32],
191	) -> Result<PairingKey, CryptoError> {
192		self.finish_with("nibkeep 2026-11 invitations", message, binding)
193	}
194
195	fn finish_with(
196		self,
197		context: &str,
198		message: &[u8],
199		binding: &[u8; 32],
200	) -> Result<PairingKey, CryptoError> {
201		let agreed = self.0.finish(message)?;
202		let mut material = Vec::with_capacity(64);
203		material.extend_from_slice(agreed.expose_bytes());
204		material.extend_from_slice(binding);
205		Ok(PairingKey(Key::from_bytes(blake3::derive_key(
206			context, &material,
207		))))
208	}
209}
210
211/// The key that pairing agrees on, which tags what each side sends. Both sides have the same
212/// key only if they typed the same code, over the same connection.
213pub struct PairingKey(Key);
214
215impl PairingKey {
216	/// The tag of a message that `side` sends.
217	#[must_use]
218	pub fn tag(&self, side: Side, message: &Value) -> [u8; 32] {
219		let tagged = Value::Array(vec![Value::Text(side.name().to_owned()), message.clone()]);
220		self.0.tag(&cbor::encode(&tagged))
221	}
222
223	/// Whether `tag` is the tag of a message that `side` sent, compared in constant time.
224	#[must_use]
225	pub fn checks(&self, side: Side, message: &Value, tag: &[u8]) -> bool {
226		let tagged = Value::Array(vec![Value::Text(side.name().to_owned()), message.clone()]);
227		self.0.verify_tag(&cbor::encode(&tagged), tag)
228	}
229}
230
231impl fmt::Debug for PairingKey {
232	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233		f.write_str("PairingKey(..)")
234	}
235}
236
237/// What a joiner asks for: to be a replica with these keys, on a device and in an app with
238/// these names, and, with a secrets encryption key, the secrets too. In CBOR,
239/// `[signing key, encryption key, device, app]`, or
240/// `[signing key, encryption key, device, app, secrets encryption key]`.
241#[derive(Clone, Debug, PartialEq, Eq)]
242pub struct JoinRequest {
243	/// The new replica's verifying key.
244	pub signing: VerifyingKey,
245	/// The new replica's encryption key, which the space keys are sealed to.
246	pub encryption: EncryptionKey,
247	/// The name of its device.
248	pub device: String,
249	/// The name of its app.
250	pub app: String,
251	/// The new replica's secrets encryption key, which secrets keys are sealed to, if it
252	/// asks for the secrets from the sponsor.
253	pub secrets: Option<EncryptionKey>,
254}
255
256impl ToCbor for JoinRequest {
257	fn to_cbor(&self) -> Value {
258		let mut items = vec![
259			self.signing.to_cbor(),
260			self.encryption.to_cbor(),
261			self.device.to_cbor(),
262			self.app.to_cbor(),
263		];
264		items.extend(self.secrets.as_ref().map(ToCbor::to_cbor));
265		Value::Array(items)
266	}
267}
268
269impl FromCbor for JoinRequest {
270	fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
271		const EXPECTED: &str =
272			"a request: [signing key, encryption key, device, app, secrets encryption key?]";
273		let Value::Array(items) = value else {
274			return Err(cbor::Error::Expected(EXPECTED));
275		};
276		let (signing, encryption, device, app, secrets) = match items.as_slice() {
277			[signing, encryption, device, app] => (signing, encryption, device, app, None),
278			[signing, encryption, device, app, secrets] => {
279				(signing, encryption, device, app, Some(secrets))
280			}
281			_ => return Err(cbor::Error::Expected(EXPECTED)),
282		};
283		let name = |value: &Value| -> Result<String, cbor::Error> {
284			let name = String::from_cbor(value)?;
285			if name.is_empty() || name.len() > MAX_NAME_LEN {
286				return Err(cbor::Error::Expected(EXPECTED));
287			}
288			Ok(name)
289		};
290		Ok(Self {
291			signing: VerifyingKey::from_cbor(signing)?,
292			encryption: EncryptionKey::from_cbor(encryption)?,
293			device: name(device)?,
294			app: name(app)?,
295			secrets: secrets.map(EncryptionKey::from_cbor).transpose()?,
296		})
297	}
298}
299
300/// The space keys of one space, each sealed to the joiner. In CBOR,
301/// `[space, [[epoch, sealed key], …]]`.
302#[derive(Clone, Debug, PartialEq, Eq)]
303pub struct SealedSpaceKeys {
304	/// The space.
305	pub space: SpaceId,
306	/// Its keys by epoch, each sealed.
307	pub keys: Vec<(u64, SealedMessage)>,
308}
309
310/// What a sponsor grants a joiner: who it is now, and the space keys; for a replica of the
311/// user's, whether it asks before it takes a space given to it later, as a phone does, or
312/// takes it, as a computer does; and, for an AI agent's replica, that it is one, and the
313/// other spaces chosen for it, in which it signs its listings as it joins, as it signs its
314/// listing in the personal space. In CBOR, `[user, device, replica, space, sponsor, keys,
315/// asks]` for a replica of the user's, where `asks` is a boolean, and `[user, device,
316/// replica, space, sponsor, keys, [[space, member], …]]` for an AI agent's, with no space
317/// chosen or some.
318#[derive(Clone, Debug, PartialEq, Eq)]
319pub struct Grant {
320	/// The user.
321	pub user: EntityId,
322	/// The joiner's device.
323	pub device: EntityId,
324	/// The joiner's replica.
325	pub replica: EntityId,
326	/// The user's personal space.
327	pub space: SpaceId,
328	/// The sponsor's verifying key, which the joiner trusts for its first sync.
329	pub sponsor: VerifyingKey,
330	/// The space keys, sorted by space.
331	pub keys: Vec<SealedSpaceKeys>,
332	/// Whether the joiner is an AI agent's replica, as its listings say.
333	pub ai_agent: bool,
334	/// For an AI agent's replica, the spaces besides the personal one chosen for it, each with
335	/// the user's member record there, sorted by space: empty for a replica of the user's.
336	pub chosen: Vec<(SpaceId, EntityId)>,
337	/// For a replica of the user's, whether it asks before it takes a space given to it
338	/// later, as the person chose by pairing it as a phone: it states so itself, after its
339	/// first sync ([technical design](../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
340	/// `false` for an AI agent's.
341	pub asks_first: bool,
342}
343
344impl ToCbor for Grant {
345	fn to_cbor(&self) -> Value {
346		let keys = self
347			.keys
348			.iter()
349			.map(|space| {
350				Value::Array(vec![
351					space.space.to_cbor(),
352					Value::Array(
353						space
354							.keys
355							.iter()
356							.map(|(epoch, sealed)| {
357								Value::Array(vec![epoch.to_cbor(), sealed.to_cbor()])
358							})
359							.collect(),
360					),
361				])
362			})
363			.collect();
364		let mut items = vec![
365			self.user.to_cbor(),
366			self.device.to_cbor(),
367			self.replica.to_cbor(),
368			self.space.to_cbor(),
369			self.sponsor.to_cbor(),
370			Value::Array(keys),
371		];
372		if self.ai_agent {
373			items.push(Value::Array(
374				self.chosen
375					.iter()
376					.map(|(space, member)| Value::Array(vec![space.to_cbor(), member.to_cbor()]))
377					.collect(),
378			));
379		} else {
380			items.push(Value::Bool(self.asks_first));
381		}
382		Value::Array(items)
383	}
384}
385
386impl FromCbor for Grant {
387	fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
388		const EXPECTED: &str =
389			"a grant: [user, device, replica, space, sponsor, keys, asks or chosen]";
390		let error = || cbor::Error::Expected(EXPECTED);
391		let Value::Array(items) = value else {
392			return Err(error());
393		};
394		let [user, device, replica, space, sponsor, keys, last] = items.as_slice() else {
395			return Err(error());
396		};
397		// A boolean for a replica of the user's, the spaces chosen for an AI agent's.
398		let (asks_first, chosen) = match last {
399			Value::Bool(asks) => (*asks, None),
400			chosen => (false, Some(chosen)),
401		};
402		let mut chosen_spaces = Vec::new();
403		if let Some(chosen) = chosen {
404			let Value::Array(chosen) = chosen else {
405				return Err(error());
406			};
407			for each in chosen {
408				let Value::Array(each) = each else {
409					return Err(error());
410				};
411				let [space, member] = each.as_slice() else {
412					return Err(error());
413				};
414				chosen_spaces.push((SpaceId::from_cbor(space)?, EntityId::from_cbor(member)?));
415			}
416			if !chosen_spaces.windows(2).all(|pair| pair[0].0 < pair[1].0) {
417				return Err(error());
418			}
419		}
420		let Value::Array(spaces) = keys else {
421			return Err(error());
422		};
423		let mut sealed = Vec::new();
424		for entry in spaces {
425			let Value::Array(entry) = entry else {
426				return Err(error());
427			};
428			let [space, keys] = entry.as_slice() else {
429				return Err(error());
430			};
431			let Value::Array(keys) = keys else {
432				return Err(error());
433			};
434			let mut by_epoch = Vec::new();
435			for key in keys {
436				let Value::Array(key) = key else {
437					return Err(error());
438				};
439				let [epoch, key] = key.as_slice() else {
440					return Err(error());
441				};
442				by_epoch.push((u64::from_cbor(epoch)?, SealedMessage::from_cbor(key)?));
443			}
444			if by_epoch.is_empty() || !by_epoch.windows(2).all(|pair| pair[0].0 < pair[1].0) {
445				return Err(error());
446			}
447			sealed.push(SealedSpaceKeys {
448				space: SpaceId::from_cbor(space)?,
449				keys: by_epoch,
450			});
451		}
452		if !sealed
453			.windows(2)
454			.all(|pair| pair[0].space.as_bytes() < pair[1].space.as_bytes())
455		{
456			return Err(error());
457		}
458		Ok(Self {
459			user: EntityId::from_cbor(user)?,
460			device: EntityId::from_cbor(device)?,
461			replica: EntityId::from_cbor(replica)?,
462			space: SpaceId::from_cbor(space)?,
463			sponsor: VerifyingKey::from_cbor(sponsor)?,
464			keys: sealed,
465			ai_agent: chosen.is_some(),
466			chosen: chosen_spaces,
467			asks_first,
468		})
469	}
470}
471
472/// The associated data of a sealed space key: `[space, epoch, replica]`.
473pub(crate) fn space_key_data(space: SpaceId, epoch: u64, replica: EntityId) -> Vec<u8> {
474	cbor::encode(&Value::Array(vec![
475		space.to_cbor(),
476		epoch.to_cbor(),
477		replica.to_cbor(),
478	]))
479}
480
481/// Seals every key of every space to the joiner's encryption key, for its replica.
482pub fn seal_space_keys(
483	recipient: &EncryptionKey,
484	replica: EntityId,
485	spaces: &BTreeMap<SpaceId, BTreeMap<u64, Key>>,
486	rng: &mut impl CryptoRng,
487) -> Vec<SealedSpaceKeys> {
488	let mut sealed: Vec<SealedSpaceKeys> = spaces
489		.iter()
490		.map(|(&space, keys)| SealedSpaceKeys {
491			space,
492			keys: keys
493				.iter()
494				.map(|(&epoch, key)| {
495					let data = space_key_data(space, epoch, replica);
496					(
497						epoch,
498						SealedMessage::seal_key(recipient, key, SPACE_KEYS, &data, rng),
499					)
500				})
501				.collect(),
502		})
503		.collect();
504	sealed.sort_by(|a, b| a.space.as_bytes().cmp(b.space.as_bytes()));
505	sealed
506}
507
508/// Opens the space keys that a grant seals to this replica.
509///
510/// # Errors
511///
512/// Returns [`CryptoError::Decryption`] if a key does not open: it was sealed to another key,
513/// for another replica, space or epoch, or changed.
514pub fn open_space_keys(
515	decryption: &DecryptionKey,
516	replica: EntityId,
517	sealed: &[SealedSpaceKeys],
518) -> Result<BTreeMap<SpaceId, BTreeMap<u64, Key>>, CryptoError> {
519	let mut spaces = BTreeMap::new();
520	for space in sealed {
521		let mut keys = BTreeMap::new();
522		for (epoch, key) in &space.keys {
523			let data = space_key_data(space.space, *epoch, replica);
524			keys.insert(*epoch, key.open_key(decryption, SPACE_KEYS, &data)?);
525		}
526		spaces.insert(space.space, keys);
527	}
528	Ok(spaces)
529}