Skip to main content

nibkeep_node/library/
recovery.rs

1//! Recovery codes: a person's printed code, which works as one more device that lives on
2//! paper. It is named in the personal space, and given the keys of the space as a replica
3//! is, until it is revoked ([technical design: recovery codes]).
4//!
5//! [technical design: recovery codes]: ../../../../docs/Technical-design.md#111-recovery-codes
6
7use std::collections::BTreeSet;
8
9use getrandom::SysRng;
10use getrandom::rand_core::UnwrapErr;
11use nibkeep_base::{EntityId, Hash, SpaceId};
12use nibkeep_crypto::rand_core::CryptoRng;
13use nibkeep_crypto::{DecryptionKey, RecoveryCode, VerifyingKey, key_hash};
14use nibkeep_governance::{
15	RECOVERY_CODE, RecoveryEntry, RecoveryStatement, Roster, SPACE_ENTRY, SpaceEntry,
16	recovery_record, state_recovery_code, state_recovery_entry,
17};
18use nibkeep_keys::SpaceKeyMap;
19use nibkeep_model::{Name, Value, fields};
20
21use super::Library;
22use super::policies::assert;
23use super::revocation::Makers;
24use crate::NodeError;
25use crate::recovery_file::{RECOVERY_FILE, RecoveryFile};
26
27/// A recovery code of the person's, as their personal space names it.
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub struct RecoveryCodeInfo {
30	/// The code's record in the personal space.
31	pub record: EntityId,
32	/// Its short name, printed beside the code, which tells one sheet of paper from another.
33	pub name: String,
34	/// Its recovery key.
35	pub key: VerifyingKey,
36	/// When it was made, in milliseconds since 1970, as the device that made it says.
37	pub made_at: u64,
38	/// The replica that made it: the one whose key signed its statement.
39	pub made_by: Option<EntityId>,
40	/// The name of the device that made it.
41	pub made_on: Option<String>,
42	/// Whether it was revoked: it is given no key made since, and brings no device back.
43	pub revoked: bool,
44	/// Whether the replica that made it gave it a secrets key of the personal space that a
45	/// replica which holds the secrets was given too, sealed to the secrets encryption key
46	/// that it signed: whether it opens the secrets, as a recovery with it takes them.
47	pub holds_secrets: bool,
48	/// For a code that stands, the names of the person's backups that carry it: whose last
49	/// update, as its account in the personal space tells, wrote the personal space with the
50	/// code named, and so the recovery file with the code's entry.
51	pub carried_by: Vec<String>,
52	/// For a code that stands, the names of the person's backups still to update before they
53	/// carry it, with which the code brings nothing back yet.
54	pub to_update: Vec<String>,
55	/// For a code that stands and that a newer one replaces, the newer one's name: it is
56	/// revoked once every backup carries the newer one, as a backup not updated since opens
57	/// with this one alone; until then its paper is to be kept.
58	pub replaced_by: Option<String>,
59}
60
61/// What the person's codes call for of a recovery file, in a replica's folder or a backup's.
62pub(crate) enum RecoveryFileNeed {
63	/// To keep it as it is, as it holds the personal space's first key for the codes that
64	/// stand and no other, or as there is none and no code stands.
65	Kept,
66	/// To write this one, sealed anew.
67	Written(RecoveryFile),
68	/// To remove it, as no code stands.
69	Removed,
70}
71
72/// What a check of a recovery code on a device that works found.
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub struct RecoveryCheck {
75	/// The code, if the personal space names it: one of the person's own.
76	pub code: Option<RecoveryCodeInfo>,
77	/// For each space that names it, the personal one or another, for whichever member, the
78	/// keys that it opens and those it lacks.
79	pub spaces: Vec<RecoveryKeys>,
80}
81
82/// The keys of a space that a recovery code opens, of those that this replica holds and that
83/// were given out. The first key is never given out: it reaches a code another way.
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct RecoveryKeys {
86	/// The space.
87	pub space: SpaceId,
88	/// The numbers of the keys that the records seal to the code, and that open with it to
89	/// the keys that this replica holds: on any of this replica's member's records for the
90	/// code there, as a member made direct, or one through a group, may have more than one,
91	/// or else on one member's.
92	pub opens: Vec<u64>,
93	/// The numbers of the keys that the code was not given, as those made after it was
94	/// revoked, or that do not open with it.
95	pub lacks: Vec<u64>,
96	/// For a space other than the personal one, whether the code is given that space: an
97	/// entry on the code's record, in the personal space or in a group that the space is
98	/// reached through, whose first key opens with the code to the one that this replica
99	/// holds. `None` for the personal space, whose first key reaches a code another way, and
100	/// where the personal space does not name the code.
101	pub entry: Option<bool>,
102	/// While this replica's secrets of the space are unlocked, the numbers of the secrets
103	/// keys that it holds and that the code opens, and of those that the code lacks; `None`
104	/// while they are locked, or the replica holds none.
105	pub secrets: Option<(Vec<u64>, Vec<u64>)>,
106}
107
108impl Library {
109	/// The person's recovery codes, as their personal space names them, the oldest first,
110	/// revoked ones too: every code that the space names, whichever member its statement
111	/// names, as every replica there is the user's, and each is given the space's keys.
112	///
113	/// # Errors
114	///
115	/// Returns an error if the personal space cannot be read.
116	pub fn recovery_codes(&self) -> Result<Vec<RecoveryCodeInfo>, NodeError> {
117		let roster = self.roster(self.info.personal)?;
118		let mut codes: Vec<_> = roster.codes().collect();
119		codes.sort_by_key(|code| (code.at, code.change));
120		if codes.is_empty() {
121			return Ok(Vec::new());
122		}
123		// The newest code of the person's own that stands replaces those before it: one named
124		// for another member, as by a device that copied the code's statement, replaces none.
125		let newest = codes
126			.iter()
127			.rfind(|code| code.stands() && code.statement.member == self.info.user)
128			.map(|code| (code.record, RecoveryCode::name_of(&code.statement.key)));
129		let replicas = self.replicas()?;
130		// Each backup of the person's, with the heads of the personal space's changes that its
131		// latest account says it holds: it carries a code whose naming one of them is or builds
132		// on, as walked down to that change alone.
133		let accounts = self.backup_accounts(self.info.personal)?;
134		let mut backups: Vec<(String, Vec<nibkeep_log::ChangeId>)> = Vec::new();
135		for backup in self.backups()? {
136			let heads = accounts
137				.get(&backup.id)
138				.map_or_default(|account| account.head.heads.clone());
139			backups.push((backup.name, heads));
140		}
141		let personal_log = self.space(self.info.personal)?.stored.log();
142		let holds = |heads: &[nibkeep_log::ChangeId], change: nibkeep_log::ChangeId| {
143			let mut found = false;
144			for &head in heads {
145				found |= personal_log.builds_on_all(head, &[change])?;
146			}
147			Ok::<_, NodeError>(found)
148		};
149		let mut carried: Vec<Vec<bool>> = Vec::new();
150		for code in &codes {
151			let mut of_code = Vec::new();
152			for (_, heads) in &backups {
153				of_code.push(code.stands() && holds(heads, code.change)?);
154			}
155			carried.push(of_code);
156		}
157		// The secrets keys that the replicas which hold the secrets were given: a key of
158		// someone's own making, given to a code, opens nothing of theirs.
159		let held: std::collections::BTreeSet<(u64, nibkeep_base::Hash)> = roster
160			.secrets_holders()
161			.into_iter()
162			.flat_map(|holder| roster.secrets_given_to(holder))
163			.map(|sealed| (sealed.epoch, sealed.hash))
164			.collect();
165		Ok(codes
166			.into_iter()
167			.zip(carried)
168			.map(|(code, carried)| {
169				let made_by = roster.replica_of(&code.author);
170				let made_on = replicas
171					.iter()
172					.find(|replica| Some(replica.id) == made_by)
173					.and_then(|replica| replica.device_name.clone());
174				RecoveryCodeInfo {
175					record: code.record,
176					name: RecoveryCode::name_of(&code.statement.key),
177					key: code.statement.key,
178					made_at: code.at.millis(),
179					made_by,
180					made_on,
181					revoked: !code.stands(),
182					holds_secrets: {
183						let recipient = nibkeep_governance::secrets_recipient(
184							&code.statement.secrets_encryption,
185						);
186						// Given by the replica that made it, as a recovery takes them.
187						let by_maker = made_by
188							.is_some_and(|maker| roster.own_key_of(maker) == Some(&code.author));
189						by_maker
190							&& roster.secrets_gifts(code.record).iter().any(|gift| {
191								gift.counts
192									&& gift.author == code.author
193									&& gift.sealed.recipient == recipient
194									&& held.contains(&(gift.sealed.epoch, gift.sealed.hash))
195							})
196					},
197					carried_by: backups
198						.iter()
199						.zip(&carried)
200						.filter(|(_, carries)| **carries)
201						.map(|((name, _), _)| name.clone())
202						.collect(),
203					to_update: backups
204						.iter()
205						.zip(&carried)
206						.filter(|(_, carries)| code.stands() && !**carries)
207						.map(|((name, _), _)| name.clone())
208						.collect(),
209					replaced_by: newest
210						.as_ref()
211						.filter(|(record, _)| code.stands() && *record != code.record)
212						.map(|(_, name)| name.clone()),
213				}
214			})
215			.collect())
216	}
217
218	/// What the person's codes call for of a recovery file, as `existing` stands, as
219	/// [`RecoveryFileNeed`] says: an entry for each code of the person's own that stands,
220	/// with the personal space's ID, first change and first key's hash, and the person, and
221	/// the code's signature of these, which the personal space states on the code's record.
222	/// A code without one, which a version before it named, gets no entry.
223	///
224	/// # Errors
225	///
226	/// Returns an error if the personal space cannot be read.
227	pub(crate) fn recovery_file_anew(
228		&self,
229		existing: Option<&RecoveryFile>,
230	) -> Result<RecoveryFileNeed, NodeError> {
231		let personal = self.info.personal;
232		let roster = self.roster(personal)?;
233		let Some((first, hash, root)) = self.what_codes_sign()? else {
234			return Ok(RecoveryFileNeed::Kept);
235		};
236		// The person's own codes alone: a recovery takes the person from the entry that its
237		// code opens, and a code's statement copied onto a record for another member, as its
238		// signature allows, opens with the same code. Each with the entry that it signed for
239		// the space, which the roster takes only for this space and the code's record, and so
240		// its member.
241		let standing: Vec<(&nibkeep_governance::Code, &RecoveryEntry)> = roster
242			.codes()
243			.filter(|code| code.stands() && code.statement.member == self.info.user)
244			.filter_map(|code| {
245				code.entries
246					.iter()
247					.find(|entry| entry.root == root && entry.hash == hash)
248					.map(|entry| (code, entry))
249			})
250			.collect();
251		if standing.is_empty() {
252			return Ok(if existing.is_some() {
253				RecoveryFileNeed::Removed
254			} else {
255				RecoveryFileNeed::Kept
256			});
257		}
258		// Kept where it holds an entry for each code that stands, as it should be, and no
259		// other.
260		let kept = existing.is_some_and(|file| {
261			let entries = file.entries();
262			entries.len() == standing.len()
263				&& standing.iter().all(|(code, signed)| {
264					entries.iter().any(|(record, entry, signature)| {
265						*record == code.record
266							&& entry.space == personal
267							&& entry.member == code.statement.member
268							&& entry.root == root
269							&& entry.hash == hash
270							&& *signature == signed.signature
271					})
272				})
273		});
274		if kept {
275			return Ok(RecoveryFileNeed::Kept);
276		}
277		let mut rng = UnwrapErr(SysRng);
278		let entries: Vec<(EntityId, SpaceEntry, nibkeep_crypto::Signature)> = standing
279			.iter()
280			.map(|(code, signed)| {
281				let entry = SpaceEntry::seal(
282					&code.statement.encryption,
283					(personal, code.statement.member, root),
284					code.record,
285					(&first, hash),
286					&mut rng,
287				);
288				(code.record, entry, signed.signature)
289			})
290			.collect();
291		Ok(RecoveryFileNeed::Written(RecoveryFile::new(entries)))
292	}
293
294	/// What a code signs of the personal space, as its entry names it, and the first key that
295	/// the entry seals: the first key, its hash, and the space's first change; `None` before
296	/// the replica holds them.
297	///
298	/// # Errors
299	///
300	/// Returns an error if the personal space cannot be read.
301	fn what_codes_sign(&self) -> Result<Option<(nibkeep_crypto::Key, Hash, Hash)>, NodeError> {
302		let open = self.space(self.info.personal)?;
303		let first = open.keys.space_keys().find(|(epoch, _)| *epoch == 0);
304		Ok(match (first, open.stored.log().root()?) {
305			(Some((_, first)), Some(root)) => Some((first.clone(), key_hash(first), *root.hash())),
306			_ => None,
307		})
308	}
309
310	/// Keeps the recovery file in the replica's folder as the person's codes call for, as
311	/// [`Library::recovery_file_anew`] says: done as a code is named or revoked, and after
312	/// each sync. An AI agent's replica keeps none, as it names no code.
313	///
314	/// # Errors
315	///
316	/// Returns an error if the personal space cannot be read, or the file written.
317	pub(crate) fn save_recovery_file(&self) -> Result<(), NodeError> {
318		if self.is_ai_agent()? {
319			return Ok(());
320		}
321		let path = self.directory.join(RECOVERY_FILE);
322		// One that does not read is written anew.
323		let existing = RecoveryFile::read(&path).ok().flatten();
324		match self.recovery_file_anew(existing.as_ref())? {
325			RecoveryFileNeed::Kept => Ok(()),
326			RecoveryFileNeed::Written(file) => crate::info::write_file(&path, &file.to_bytes()),
327			RecoveryFileNeed::Removed => match std::fs::remove_file(&path) {
328				Ok(()) => Ok(()),
329				Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
330				Err(error) => Err(NodeError::file(&path)(error)),
331			},
332		}
333	}
334
335	/// Revokes the person's codes that a newer one replaces, as their records say: once every
336	/// backup carries the newest code that stands, or at once with `at_once`, as the person
337	/// says. Done after each sync and each update of a backup, and as a new code stands.
338	/// Returns those it revoked; none on an AI agent's replica, which revokes no code.
339	///
340	/// # Errors
341	///
342	/// Returns an error if the personal space cannot be read, or a revocation saved.
343	pub fn revoke_replaced_recovery_codes(
344		&mut self,
345		at_once: bool,
346		wall_millis: u64,
347		rng: &mut impl CryptoRng,
348	) -> Result<Vec<RecoveryCodeInfo>, NodeError> {
349		if self.is_ai_agent()? {
350			return Ok(Vec::new());
351		}
352		// Nothing to replace with one code or none, as is usual: the backups are not read.
353		let standing = self
354			.roster(self.info.personal)?
355			.codes()
356			.filter(|code| code.stands())
357			.count();
358		if standing < 2 {
359			return Ok(Vec::new());
360		}
361		let codes = self.recovery_codes()?;
362		// The code that replaces the others, as each names it.
363		let Some(newest) = codes.iter().find_map(|code| code.replaced_by.as_ref()) else {
364			return Ok(Vec::new());
365		};
366		let carried = codes
367			.iter()
368			.find(|code| !code.revoked && code.replaced_by.is_none() && code.name == *newest)
369			.is_some_and(|newest| newest.to_update.is_empty());
370		if !at_once && !carried {
371			return Ok(Vec::new());
372		}
373		let mut revoked = Vec::new();
374		for code in codes.iter().filter(|code| code.replaced_by.is_some()) {
375			revoked.push(self.revoke_recovery_code(&code.record.to_string(), wall_millis, rng)?);
376		}
377		Ok(revoked)
378	}
379
380	/// The person's codes that stand and that one of `replicas` made, as the key that signed
381	/// each one's statement says: those that revoking a device names.
382	///
383	/// # Errors
384	///
385	/// Returns an error if the personal space cannot be read.
386	pub fn recovery_codes_made_by(
387		&self,
388		replicas: &[EntityId],
389	) -> Result<Vec<RecoveryCodeInfo>, NodeError> {
390		Ok(self
391			.recovery_codes()?
392			.into_iter()
393			.filter(|code| {
394				!code.revoked
395					&& code
396						.made_by
397						.is_some_and(|replica| replicas.contains(&replica))
398			})
399			.collect())
400	}
401
402	/// The recovery code that `reference` names, by its short name, in either case, or by
403	/// its record's ID, of those that stand.
404	///
405	/// # Errors
406	///
407	/// Returns [`NodeError::WhichRecoveryCode`] if it names none that stands, or several.
408	pub fn find_recovery_code(&self, reference: &str) -> Result<RecoveryCodeInfo, NodeError> {
409		let reference = reference.trim();
410		let named: Vec<RecoveryCodeInfo> = self
411			.recovery_codes()?
412			.into_iter()
413			.filter(|code| {
414				code.name.eq_ignore_ascii_case(reference) || code.record.to_string() == reference
415			})
416			.collect();
417		let mut standing = named.iter().filter(|code| !code.revoked);
418		match (standing.next(), standing.next()) {
419			(Some(code), None) => Ok(code.clone()),
420			(Some(_), Some(_)) => Err(NodeError::WhichRecoveryCode(format!(
421				"several recovery codes are named {reference}; name one by its ID, which nib recovery list shows"
422			))),
423			(None, _) if named.is_empty() => Err(NodeError::WhichRecoveryCode(format!(
424				"no recovery code is named {reference}; nib recovery list shows them"
425			))),
426			(None, _) => Err(NodeError::WhichRecoveryCode(format!(
427				"the recovery code {reference} is revoked already"
428			))),
429		}
430	}
431
432	/// Names a recovery code in the personal space, once the person wrote it down and typed
433	/// it back, and gives it the keys of the space that were given out, as a replica that
434	/// lacks them is given them. With `secrets`, as the person chose, it also gives the code
435	/// the secrets, which must be unlocked: the code then opens them too. Naming a code that
436	/// is named already changes nothing, but gives it the secrets if asked, on the device that
437	/// made it alone.
438	///
439	/// # Errors
440	///
441	/// Returns [`NodeError::AiAgentMayNot`] on an AI agent's replica,
442	/// [`NodeError::WhichRecoveryCode`] if the code was revoked, as a revocation is final,
443	/// [`NodeError::SecretsLocked`] if `secrets` is asked while they are locked, before
444	/// anything is named, [`NodeError::RecoveryCodeMadeElsewhere`] if they are asked for a
445	/// code that another device made, and an error if the changes cannot be saved.
446	pub fn add_recovery_code(
447		&mut self,
448		code: &RecoveryCode,
449		secrets: bool,
450		wall_millis: u64,
451		rng: &mut impl CryptoRng,
452	) -> Result<RecoveryCodeInfo, NodeError> {
453		if self.is_ai_agent()? {
454			return Err(NodeError::AiAgentMayNot("make a recovery code"));
455		}
456		if secrets && !self.secrets_unlocked(self.info.personal) {
457			return Err(NodeError::SecretsLocked);
458		}
459		let personal = self.info.personal;
460		let stated = RecoveryStatement::sign(code, self.info.user);
461		let record = stated.record(personal);
462		match self.roster(personal)?.code(record) {
463			Some(named) if !named.stands() => {
464				return Err(NodeError::WhichRecoveryCode(
465					"this recovery code was revoked, which is final; make a new one".to_owned(),
466				));
467			}
468			// What another device gave it, a device that recovers with it could not tell from
469			// a key of someone's own making.
470			Some(named) if secrets && named.author != self.replica.signing.verifying_key() => {
471				return Err(NodeError::RecoveryCodeMadeElsewhere);
472			}
473			Some(_) => {}
474			None => {
475				let name = RecoveryCode::name_of(&stated.key);
476				// The code signs, once, what the personal space's entry for it names, which
477				// each recovery file then carries: no device can write another for it.
478				let Some((_, hash, root)) = self.what_codes_sign()? else {
479					return Err(NodeError::Damaged(
480						"the personal space has no first key or first change".to_owned(),
481					));
482				};
483				let entry = RecoveryEntry::sign(code, (personal, self.info.user, root), hash);
484				let operations = vec![
485					state_recovery_code(personal, &stated, rng),
486					state_recovery_entry(&entry, rng),
487					assert(
488						record,
489						fields::TYPE,
490						Value::Text(RECOVERY_CODE.to_string()),
491						rng,
492					),
493					assert(record, fields::NAME, Value::Name(Name::new(&name)), rng),
494				];
495				self.commit(personal, operations, wall_millis, rng)?;
496			}
497		}
498		// The keys given out so far: a code is given them as a replica that lacks them is.
499		self.give_keys(personal, wall_millis, rng)?;
500		// And the person's other spaces: each is given to the code, and names it. The code
501		// stands in the personal space already; a space where this fails gets it after the
502		// next sync.
503		let _ = self.give_space_entries(wall_millis, rng);
504		let _ = self.carry_codes(wall_millis, rng);
505		// And the recovery file, which the next sync writes if this fails.
506		let _ = self.save_recovery_file();
507		if secrets {
508			self.give_code_secrets(record, wall_millis, rng)?;
509			// And the secrets of the person's other spaces, which their holders give to those
510			// known to hold the personal space's.
511			let _ = self.settle_secrets(wall_millis, rng);
512		}
513		self.recovery_codes()?
514			.into_iter()
515			.find(|named| named.record == record)
516			.ok_or_else(|| NodeError::NoEntity(record.to_string()))
517	}
518
519	/// Checks a recovery code on this device, which works: whether the personal space names
520	/// it, whether it stands, and, in each space that names it, which of the keys that this
521	/// replica holds it opens.
522	///
523	/// # Errors
524	///
525	/// Returns an error if a space cannot be read.
526	pub fn check_recovery_code(&self, code: &RecoveryCode) -> Result<RecoveryCheck, NodeError> {
527		let key = code.signing_key().verifying_key();
528		let personal = self.info.personal;
529		// The record derived for the user first, as this version names a code.
530		let own = recovery_record(personal, self.info.user, &key);
531		let mut named: Vec<RecoveryCodeInfo> = self
532			.recovery_codes()?
533			.into_iter()
534			.filter(|named| named.key == key)
535			.collect();
536		named.sort_by_key(|named| (named.record != own, named.revoked));
537		let named = named.into_iter().next();
538		let decryption = code.decryption_key();
539		// The secrets keys that a recovery with the code takes, where the secrets are unlocked.
540		let secrets_opened = if self
541			.spaces()
542			.into_iter()
543			.any(|space| self.secrets_unlocked(space))
544		{
545			self.secrets_code_opens(&self.rosters()?, code)?
546		} else {
547			SpaceKeyMap::new()
548		};
549		let mut spaces = Vec::new();
550		for space in self.spaces() {
551			let roster = self.roster(space)?;
552			let mut records: Vec<_> = roster
553				.codes()
554				.filter(|named| named.statement.key == key)
555				.map(|named| named.record)
556				.collect();
557			if records.is_empty() {
558				continue;
559			}
560			// Every record of this replica's member for the code in each space; or else one
561			// member's, the user's own first.
562			let own_members = if space == personal {
563				Vec::new()
564			} else {
565				self.own_code_members(space)?
566			};
567			let own_records: Vec<EntityId> = records
568				.iter()
569				.copied()
570				.filter(|record| {
571					own_members
572						.iter()
573						.any(|member| recovery_record(space, *member, &key) == *record)
574				})
575				.collect();
576			records.sort_by_key(|record| *record != own);
577			records.truncate(1);
578			let records = if own_records.is_empty() {
579				records
580			} else {
581				own_records
582			};
583			let mut keys = RecoveryKeys {
584				space,
585				opens: Vec::new(),
586				lacks: Vec::new(),
587				entry: None,
588				secrets: None,
589			};
590			for &record in &records {
591				let found = self.code_keys(space, &roster, record, &decryption)?;
592				keys.opens.extend(found.opens);
593				keys.lacks.extend(found.lacks);
594			}
595			keys.opens = merged(keys.opens, &[]);
596			keys.lacks = merged(keys.lacks, &keys.opens);
597			if self.secrets_unlocked(space) {
598				keys.secrets = Some(self.code_secrets(space, &roster, &secrets_opened)?);
599			}
600			if space != personal {
601				keys.entry = self.code_entry(space, named.as_ref(), &decryption)?;
602			}
603			spaces.push(keys);
604		}
605		Ok(RecoveryCheck {
606			code: named,
607			spaces,
608		})
609	}
610
611	/// The keys of `space` that this replica holds and that were given out, by whether the
612	/// statements on a code's record there seal them to the code, so that they open with its
613	/// decryption key to the keys held.
614	fn code_keys(
615		&self,
616		space: SpaceId,
617		roster: &Roster,
618		record: EntityId,
619		decryption: &DecryptionKey,
620	) -> Result<RecoveryKeys, NodeError> {
621		let open = self.space(space)?;
622		let mut makers = Makers::of(open);
623		let mut keys = RecoveryKeys {
624			space,
625			opens: Vec::new(),
626			lacks: Vec::new(),
627			entry: None,
628			secrets: None,
629		};
630		for (epoch, held) in open.keys.space_keys() {
631			let hash = key_hash(held);
632			// Only a key whose rotation a member's replica made is given out; the first key
633			// never is.
634			let Some(rotation) = roster.rotation(epoch, &hash).filter(|_| epoch != 0) else {
635				continue;
636			};
637			if !makers.made(rotation.change)? {
638				continue;
639			}
640			let opens = roster.given_to(record).iter().any(|gift| {
641				gift.sealed.epoch == epoch
642					&& gift.sealed.hash == hash
643					&& gift
644						.sealed
645						.open(decryption, space, record)
646						.is_some_and(|opened| opened.same_as(held))
647			});
648			if opens {
649				keys.opens.push(epoch);
650			} else {
651				keys.lacks.push(epoch);
652			}
653		}
654		Ok(keys)
655	}
656
657	/// The secrets keys of `space` that this replica holds, unlocked, and that were given out,
658	/// by whether a recovery with the code takes them, as `opened` has them: those it opens,
659	/// and those it lacks.
660	fn code_secrets(
661		&self,
662		space: SpaceId,
663		roster: &Roster,
664		opened: &SpaceKeyMap,
665	) -> Result<(Vec<u64>, Vec<u64>), NodeError> {
666		let open = self.space(space)?;
667		let mut makers = Makers::of(open);
668		let (mut opens, mut lacks) = (Vec::new(), Vec::new());
669		for (epoch, held) in open.keys.secrets_keys() {
670			let hash = key_hash(held);
671			let Some(rotation) = roster.secrets_rotation(epoch, &hash) else {
672				continue;
673			};
674			if !makers.made(rotation.change)? {
675				continue;
676			}
677			let taken = opened
678				.get(&space)
679				.and_then(|keys| keys.get(&epoch))
680				.is_some_and(|key| key.same_as(held));
681			if taken {
682				opens.push(epoch);
683			} else {
684				lacks.push(epoch);
685			}
686		}
687		Ok((opens, lacks))
688	}
689
690	/// Whether a code of the person's is given the space `space`: whether an entry on the
691	/// code's record, in the personal space or in a group that this replica holds, names the
692	/// space, and opens with the code to the first key that this replica holds. `None` where
693	/// the personal space does not name the code.
694	fn code_entry(
695		&self,
696		space: SpaceId,
697		named: Option<&RecoveryCodeInfo>,
698		decryption: &DecryptionKey,
699	) -> Result<Option<bool>, NodeError> {
700		let Some(named) = named else {
701			return Ok(None);
702		};
703		let Some(first) = self
704			.space(space)?
705			.keys
706			.space_keys()
707			.find(|(epoch, _)| *epoch == 0)
708			.map(|(_, key)| key.clone())
709		else {
710			return Ok(Some(false));
711		};
712		// Whether a counting statement of a log, on one of `records`, gives the space.
713		let gives = |open: &super::Space, records: &BTreeSet<EntityId>| {
714			let statements = open.stored.log().governing_statements(&open.keys)?;
715			Ok::<_, NodeError>(statements.iter().any(|governing| {
716				let record = governing.statement.entity;
717				records.contains(&record)
718					&& governing
719						.counting_text(&SPACE_ENTRY)
720						.and_then(SpaceEntry::from_text)
721						.is_some_and(|entry| {
722							entry.space == space
723								&& entry
724									.open(decryption, record)
725									.is_some_and(|opened| opened.same_as(&first))
726						})
727			}))
728		};
729		// The personal space's entry, on the code's record there.
730		if gives(
731			self.space(self.info.personal)?,
732			&BTreeSet::from([named.record]),
733		)? {
734			return Ok(Some(true));
735		}
736		// Or a group's, on the person's own record for the code there, for a space that the
737		// group is in.
738		for (&group, open) in &self.spaces {
739			if group == space || group == self.info.personal || !open.is_group()? {
740				continue;
741			}
742			let records: BTreeSet<EntityId> = self
743				.own_code_members(group)?
744				.into_iter()
745				.map(|member| recovery_record(group, member, &named.key))
746				.collect();
747			if !records.is_empty() && gives(open, &records)? {
748				return Ok(Some(true));
749			}
750		}
751		Ok(Some(false))
752	}
753
754	/// Revokes the recovery code that `reference` names, as [`Library::find_recovery_code`]
755	/// finds it, and gives the personal space a new key in the same change, which the code is
756	/// not given: so it opens nothing added later, and brings no device back.
757	///
758	/// # Errors
759	///
760	/// Returns [`NodeError::AiAgentMayNot`] on an AI agent's replica,
761	/// [`NodeError::WhichRecoveryCode`] if `reference` names no code that stands, or several,
762	/// and an error if the change cannot be saved.
763	pub fn revoke_recovery_code(
764		&mut self,
765		reference: &str,
766		wall_millis: u64,
767		rng: &mut impl CryptoRng,
768	) -> Result<RecoveryCodeInfo, NodeError> {
769		if self.is_ai_agent()? {
770			return Err(NodeError::AiAgentMayNot("revoke a recovery code"));
771		}
772		let code = self.find_recovery_code(reference)?;
773		let personal = self.info.personal;
774		self.check_not_revoked(personal)?;
775		// The new key is sealed to this replica too, which needs its encryption key on its
776		// record: a library's first replica states it only now, or as it first syncs.
777		self.record_own_endpoint(wall_millis, rng)?;
778		let roster = self.roster(personal)?;
779		self.rotate_revoking(
780			personal,
781			&[],
782			&[(code.record, code.key)],
783			&roster,
784			wall_millis,
785			rng,
786		)?;
787		// And in every other space that names it, each with a new key. The personal space's
788		// revocation is made: a space where this fails revokes after the next sync.
789		let _ = self.carry_codes(wall_millis, rng);
790		// The recovery file without the code, which the next sync writes if this fails.
791		let _ = self.save_recovery_file();
792		// A new secrets key, if the secrets are unlocked here and the code held them; or else
793		// the first replica that unlocks them makes one.
794		let _ = self.settle_secrets(wall_millis, rng);
795		Ok(RecoveryCodeInfo {
796			revoked: true,
797			..code
798		})
799	}
800}
801
802/// The key numbers of `numbers`, each once and in order, but those of `but`.
803fn merged(numbers: Vec<u64>, but: &[u64]) -> Vec<u64> {
804	let numbers: BTreeSet<u64> = numbers.into_iter().collect();
805	numbers
806		.into_iter()
807		.filter(|number| !but.contains(number))
808		.collect()
809}