Skip to main content

nibkeep_node/library/
recovering.rs

1//! Recovering a library on a new device, after its person lost every device, or the means to
2//! unlock them: from a printed recovery code and a source, a backup or a library on this
3//! computer that no longer unlocks ([technical design: recovery codes]). The new device opens
4//! the personal space's first key from the source's recovery file, takes in what the source
5//! holds, opens the keys sealed to the code, and lists itself by the code; then it takes the
6//! person's other spaces and groups that the code is given, and lists itself in each, by the
7//! code or through a group; it revokes the lost devices, but those that the person keeps, and
8//! updates the backup. A library that no longer unlocks is read as a copy is, and never
9//! written to; one in the folder where the new replica goes is set aside there, as the
10//! recovery's last step.
11//!
12//! [technical design: recovery codes]: ../../../../docs/Technical-design.md#111-recovery-codes
13
14use std::collections::{BTreeMap, BTreeSet};
15use std::fs;
16use std::io;
17use std::path::{Path, PathBuf};
18
19use nibkeep_base::{EntityId, SpaceId};
20use nibkeep_crypto::rand_core::CryptoRng;
21use nibkeep_crypto::{DecryptionKey, Key, RecoveryCode, VerifyingKey, key_hash};
22use nibkeep_governance::{
23	Code, Listing, NewReplica, RecoveryListing, Role, SPACE_ENTRY, SpaceEntry, SpaceReplica,
24	list_by_recovery_code, list_replica, recovery_record,
25};
26use nibkeep_keys::{KeyFile, NewProtection, ReplicaKeys};
27use nibkeep_log::ChangeId;
28
29use super::holding::HeldElsewhere;
30use super::secrets::Compartment;
31use super::sync::{Joining, Replica, endpoint_of};
32use super::{Found, INFO, KEYS, Library, found, new_replica_folder_marked, replica_folders};
33use crate::info::Info;
34use crate::place::same_folder;
35use crate::recovery_file::{OpenedRecovery, RECOVERY_FILE, RecoveryFile};
36use crate::{NodeError, backup};
37
38/// The file in the folder of a replica that a recovery code brings back, until the recovery
39/// is done: the library does not open while it is there, and a recovery run again removes
40/// that replica, which nobody knows, and starts over. A recovery in place of the replica here
41/// writes that replica's folder's name in it, so that the two count as one library while the
42/// old one is in its place.
43pub(crate) const RECOVERING: &str = "recovering";
44
45/// The file that a recovery in place writes beside its [`RECOVERING`] mark once the new
46/// replica is whole: from then on it is the library, and opens. The replica it replaces stays
47/// hidden behind the mark until it is set aside, which the recovery tries then, and the
48/// library again as it opens; then the mark goes, and this file last.
49const RECOVERED: &str = "recovered";
50
51/// What starts the name under which a recovery in place sets aside the folder of the replica
52/// it replaces, beside the new one: hidden, as a dot starts it, and never taken for a replica
53/// or a copy.
54const SET_ASIDE: &str = ".replaced-";
55
56/// What a recovery did.
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub struct Recovered {
59	/// The replicas of the person's other devices that it revoked, as they were before.
60	pub revoked: Vec<Replica>,
61	/// The replicas of the person's other devices that it kept, as the person still has them.
62	pub kept: Vec<Replica>,
63	/// The spaces and groups where it also revoked replicas of the person's that the personal
64	/// space it took did not list, as a backup holds that was last updated by a computer that
65	/// learned of a device from another member alone.
66	pub revoked_elsewhere: Vec<SpaceId>,
67	/// The person's other spaces and groups that came back.
68	pub spaces: Vec<SpaceId>,
69	/// The spaces and groups given to the code that the backup holds nothing of, which did
70	/// not come back.
71	pub missing: Vec<SpaceId>,
72	/// The spaces of the person's that the devices it revoked held and that did not come
73	/// back, each with the devices it kept that hold it, which revoke them there after their
74	/// next sync with this one: one that none holds stays with the revoked devices
75	/// ([technical design](../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
76	pub out_of_reach: Vec<HeldElsewhere>,
77	/// What became of the secrets.
78	pub secrets: RecoveredSecrets,
79	/// What it recovered from.
80	pub from: RecoveredFrom,
81}
82
83/// What a recovery took the library from.
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub enum RecoveredFrom {
86	/// A backup.
87	Backup {
88		/// Its name, if the personal space still names it.
89		name: Option<String>,
90		/// Whether the recovery updated it, which then carries the new device: an update that
91		/// fails, or that another program holds off, leaves it to the next one.
92		updated: bool,
93	},
94	/// A library on this computer that no longer unlocked.
95	Library {
96		/// The folder of its replica that the recovery read, as it was then.
97		folder: PathBuf,
98		/// Its replica, as its folder names it, which the recovery revoked.
99		replica: Option<EntityId>,
100		/// Whether it was the library where the new replica went, which the new one replaces;
101		/// otherwise it is as it was.
102		replaced: bool,
103		/// Where its folder was set aside, beside the new replica's, if it was replaced:
104		/// `None` if it could not be set aside yet, as when another program has a file of it
105		/// open, which the library tries again as it opens. Its keys, and what it holds, are
106		/// of no more use: the person deletes it.
107		set_aside: Option<PathBuf>,
108	},
109}
110
111/// What became of the library's secrets in a recovery, which takes those that the code
112/// holds.
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub enum RecoveredSecrets {
115	/// The library had no secrets.
116	NoneHeld,
117	/// The library had secrets, and the code was made without them: they went with the lost
118	/// devices.
119	NotInCode,
120	/// The code held them, and this device holds them now, protected as the person chose:
121	/// this many secrets keys.
122	Taken {
123		/// How many secrets keys it took, of every space.
124		keys: usize,
125	},
126	/// The code held them, and the person left them: this device holds none.
127	Left,
128}
129
130/// A recovery under way, which [`Library::start_recovery`] began: the new replica, which
131/// nobody knows yet, holds what the backup holds of the personal space, and the keys sealed
132/// to the code there. [`Recovering::holds_secrets`] says whether the code holds the
133/// secrets, so that the person is asked how to protect them only then;
134/// [`Recovering::others`] lists the person's other devices, which [`Recovering::keep`]
135/// keeps some of; and [`Recovering::finish`] does the rest. One dropped before it finishes
136/// removes the new replica.
137pub struct Recovering<'a> {
138	/// The new replica, until the recovery finishes.
139	library: Option<Library>,
140	/// The [`RECOVERING`] mark in its folder, locked while the recovery runs.
141	mark: Option<fs::File>,
142	source: Source<'a>,
143	/// The folder of the replica here that the new one replaces, which is set aside last.
144	replacing: Option<PathBuf>,
145	code: &'a RecoveryCode,
146	new: NewRecords,
147	holds_secrets: bool,
148	/// The replicas of the person's other devices that the recovery keeps.
149	keep: BTreeSet<EntityId>,
150	/// The replicas that it revokes in any case: the one of the library that no longer
151	/// unlocks that it reads, and the one that a recovery cut short left here.
152	revoked_anyway: BTreeSet<EntityId>,
153}
154
155impl Recovering<'_> {
156	/// Whether the code holds the secrets, which [`Recovering::finish`] takes then.
157	#[must_use]
158	pub const fn holds_secrets(&self) -> bool {
159		self.holds_secrets
160	}
161
162	/// The replicas of the person's other devices, which [`Recovering::finish`] revokes as
163	/// lost, but those that [`Recovering::keep`] keeps: every replica of the person's that
164	/// is not revoked yet, but two that it revokes in any case: the one of the library that
165	/// no longer unlocks that the recovery reads, if it reads one, and the one that a
166	/// recovery cut short left in the same place, which the backup may list.
167	///
168	/// # Errors
169	///
170	/// Returns an error if the personal space cannot be read.
171	pub fn others(&self) -> Result<Vec<Replica>, NodeError> {
172		let library = self.library.as_ref().ok_or(NodeError::NoLibrary)?;
173		Ok(library
174			.replicas()?
175			.into_iter()
176			.filter(|replica| {
177				!replica.this && !replica.revoked && !self.revoked_anyway.contains(&replica.id)
178			})
179			.collect())
180	}
181
182	/// The replicas of [`Recovering::others`] that `target` names, as
183	/// [`Library::replicas_named`] finds them among them alone: those of a device, by its
184	/// name or ID, one replica by its ID, or an AI agent's by its name.
185	///
186	/// # Errors
187	///
188	/// Returns [`NodeError::WhichDevice`] if `target` names none of them, or several, as
189	/// the library that the recovery reads, or a device revoked already, and an error if the
190	/// personal space cannot be read.
191	pub fn others_named(&self, target: &str) -> Result<Vec<Replica>, NodeError> {
192		let library = self.library.as_ref().ok_or(NodeError::NoLibrary)?;
193		let error = match super::revocation::named_among(self.others()?, target) {
194			Ok(named) => return Ok(named),
195			Err(error) => error,
196		};
197		// Said apart: what the target names among the person's other replicas, if anything.
198		let Ok(named) = library.replicas_named(target) else {
199			return Err(error);
200		};
201		let why = if named
202			.iter()
203			.any(|replica| self.source.replica() == Some(replica.id))
204		{
205			"is the library that no longer unlocks, which the recovery revokes in any case"
206		} else if named
207			.iter()
208			.any(|replica| self.revoked_anyway.contains(&replica.id))
209		{
210			"was left by a recovery cut short, which this one revokes in any case"
211		} else if !named.is_empty() && named.iter().all(|replica| replica.revoked) {
212			"is revoked already"
213		} else {
214			return Err(error);
215		};
216		Err(NodeError::WhichDevice(format!("{target} {why}")))
217	}
218
219	/// Keeps `replicas`, of those that [`Recovering::others`] lists, in place of those kept
220	/// before: [`Recovering::finish`] leaves them as they are, rather than revoke them, as
221	/// the person still has their devices.
222	///
223	/// # Errors
224	///
225	/// Returns [`NodeError::WhichDevice`] if one is none of those, or if the library that
226	/// no longer unlocks, which the recovery reads, names no replica of its own, which then
227	/// may be any of them, and then keeps nothing new; and an error if the personal space
228	/// cannot be read.
229	pub fn keep(&mut self, replicas: &[EntityId]) -> Result<(), NodeError> {
230		if !replicas.is_empty() && self.source.unnamed() {
231			return Err(NodeError::WhichDevice(
232				"the library that no longer unlocks does not say which replica it is, so no device can be kept: it may be any of them".to_owned(),
233			));
234		}
235		let others: BTreeSet<EntityId> = self.others()?.iter().map(|other| other.id).collect();
236		if let Some(unknown) = replicas.iter().find(|replica| !others.contains(replica)) {
237			return Err(NodeError::WhichDevice(format!(
238				"{unknown} is no other device of yours that this recovery would revoke"
239			)));
240		}
241		self.keep = replicas.iter().copied().collect();
242		Ok(())
243	}
244
245	/// Finishes the recovery: lists the new replica by the code in the personal space; takes
246	/// the person's other spaces and groups that the code is given, with what the backup holds
247	/// of each, and lists it in each, by the code on the person's record, or through a group in
248	/// a space that the person reaches through a group alone; takes the secrets, if the code
249	/// holds them, protected as `secrets` says, unless it is `None`; then revokes every other
250	/// replica of the person's, whose devices are lost, but those that [`Recovering::keep`]
251	/// keeps, and updates the backup; in place of a library here that no longer unlocks, sets
252	/// aside that library's replica, as its last step. A recovery that fails removes the new
253	/// replica.
254	///
255	/// # Errors
256	///
257	/// Returns [`NodeError::LibraryPassphrase`] if `secrets` is the library's passphrase,
258	/// [`NodeError::BackupBusy`] if another program updates the backup, and an error if the
259	/// source cannot be read, the replica written, or the replica it replaces set aside.
260	pub fn finish(
261		mut self,
262		secrets: Option<&NewProtection<'_>>,
263		now: &dyn Fn() -> u64,
264		rng: &mut impl CryptoRng,
265	) -> Result<(Library, Recovered), NodeError> {
266		let Some(library) = self.library.as_mut() else {
267			return Err(NodeError::NoLibrary);
268		};
269		// The secrets' passphrase is never the library's, which would make the two one layer.
270		if let Some(protection) = secrets.filter(|_| self.holds_secrets)
271			&& library.opens_the_other(protection, Compartment::Replica)?
272		{
273			return Err(NodeError::LibraryPassphrase);
274		}
275		// Only what the check above covered.
276		let secrets = secrets.filter(|_| self.holds_secrets);
277		// Whatever was kept, never a replica that it revokes in any case.
278		let keep: BTreeSet<EntityId> = self
279			.keep
280			.difference(&self.revoked_anyway)
281			.copied()
282			.collect();
283		let mut recovered = library.recover_rest(
284			&self.source,
285			(self.code, &self.new, &keep),
286			secrets,
287			now,
288			rng,
289		)?;
290		let Some(library) = self.library.take() else {
291			return Err(NodeError::NoLibrary);
292		};
293		let mark = library.directory.join(RECOVERING);
294		// In place of a library here, the file that says that the new replica is whole ends
295		// the recovery; then the old replica is set aside, if it can be now, as the library
296		// does as it opens otherwise.
297		if let Some(old) = &self.replacing {
298			let done = crate::info::write_file(&library.directory.join(RECOVERED), b"");
299			drop(self.mark.take());
300			if let Err(error) = done {
301				library.remove_unsynced();
302				return Err(error);
303			}
304			tidy(&library.directory);
305			let aside = set_aside_path(old);
306			if let RecoveredFrom::Library {
307				replaced,
308				set_aside,
309				..
310			} = &mut recovered.from
311			{
312				*replaced = true;
313				*set_aside = (!old.exists() && aside.is_dir()).then_some(aside);
314			}
315			return Ok((library, recovered));
316		}
317		// The mark goes while it is locked, so that a recovery started meanwhile never takes
318		// this one for one cut short; then the lock.
319		let removed = fs::remove_file(&mark);
320		drop(self.mark.take());
321		if let Err(error) = removed {
322			library.remove_unsynced();
323			return Err(NodeError::file(&mark)(error));
324		}
325		#[cfg(unix)]
326		let _ = fs::File::open(&library.directory).and_then(|folder| folder.sync_all());
327		Ok((library, recovered))
328	}
329}
330
331impl Drop for Recovering<'_> {
332	fn drop(&mut self) {
333		// Unfinished, the new replica goes, which nobody knows.
334		drop(self.mark.take());
335		if let Some(library) = self.library.take() {
336			library.remove_unsynced();
337		}
338	}
339}
340
341impl Library {
342	/// Checks, before anything is asked or made, that `code` opens what the source in
343	/// `source` holds for it, a backup or a library that no longer unlocks: the personal
344	/// space's first key, from its recovery file.
345	///
346	/// # Errors
347	///
348	/// Returns [`NodeError::NoRecoverySource`] if `source` is neither a backup nor a library
349	/// with a recovery file, [`NodeError::CodeOpensNothing`] if the code opens nothing there,
350	/// [`NodeError::RecoveryFileChanged`] if the file's entry for the code is not what the code
351	/// signed, [`NodeError::NewerFormats`] if a later version of NibKeep changed the library,
352	/// and an error if the file cannot be read.
353	pub fn check_recovery_source(source: &Path, code: &RecoveryCode) -> Result<(), NodeError> {
354		open_source(source, code).map(|_| ())
355	}
356
357	/// Whether recovering in `directory` from the library in `source` would replace the
358	/// library here, which no longer unlocks: its replica is the one here, which a recovery
359	/// sets aside once it is done.
360	#[must_use]
361	pub fn recovery_replaces(directory: &Path, source: &Path) -> bool {
362		let Ok(here) = Self::replica_folder(directory) else {
363			return false;
364		};
365		source_replica(source).is_some_and(|folder| same_folder(&folder, &here))
366	}
367
368	/// Recovers the library of the person whose recovery code is `code` on this computer,
369	/// in `directory`, from the source in `source`, as a new replica that `joining` makes,
370	/// protected as `protection` says, and the secrets as `secrets` says, if the code holds
371	/// them: [`Library::start_recovery`], then [`Recovering::finish`].
372	///
373	/// # Errors
374	///
375	/// Returns the errors of [`Library::start_recovery`] and [`Recovering::finish`].
376	pub fn recover(
377		directory: &Path,
378		(source, code): (&Path, &RecoveryCode),
379		joining: Joining<'_>,
380		(protection, secrets): (&NewProtection<'_>, Option<&NewProtection<'_>>),
381		now: &dyn Fn() -> u64,
382		rng: &mut impl CryptoRng,
383	) -> Result<(Self, Recovered), NodeError> {
384		Self::start_recovery(directory, (source, code), joining, protection, now, rng)?
385			.finish(secrets, now, rng)
386	}
387
388	/// Starts recovering the library of the person whose recovery code is `code` on this
389	/// computer, in `directory`, from the source in `source`, as a new replica that `joining`
390	/// makes, protected as `protection` says: it opens the personal space's first key from the
391	/// source's recovery file, takes in what the source holds of the personal space, and opens
392	/// the keys sealed to the code; [`Recovering::finish`] does the rest. The code's keys are
393	/// held in memory alone. Until it is done, nobody knows the new replica, and a recovery
394	/// that fails removes it; one cut short, as by a crash, leaves it marked, and a recovery
395	/// run again removes it and starts over.
396	///
397	/// The source is a backup, or a library on this computer that no longer unlocks: its
398	/// directory, in which the replica that is here is read, or else its one copy with a
399	/// recovery file, or the folder of one of its replicas. It is read as a copy is, and never
400	/// written to. If it is the library in `directory`, the new replica goes beside its
401	/// replica, which [`Recovering::finish`] sets aside.
402	///
403	/// # Errors
404	///
405	/// Returns [`NodeError::Exists`] if another library is here,
406	/// [`NodeError::NoRecoverySource`] if `source` is neither a backup nor a library with a
407	/// recovery file, [`NodeError::CodeOpensNothing`] if the code opens nothing there,
408	/// [`NodeError::RecoveryFileChanged`] if the file's entry for the code is not what the code
409	/// signed, all before anything is written, [`NodeError::RecoveryCodeRevoked`] if the source holds the
410	/// code's revocation, [`NodeError::BackupBusy`] if another program updates the backup, and
411	/// an error if the source cannot be read or the new replica made.
412	pub fn start_recovery<'a>(
413		directory: &Path,
414		(source, code): (&'a Path, &'a RecoveryCode),
415		joining: Joining<'_>,
416		protection: &NewProtection<'_>,
417		now: &dyn Fn() -> u64,
418		rng: &mut impl CryptoRng,
419	) -> Result<Recovering<'a>, NodeError> {
420		let cut_short = remove_cut_short(directory)?;
421		let replacing = match Self::replica_folder(directory) {
422			Err(NodeError::NoLibrary | NodeError::Copied) => None,
423			Ok(here) if source_replica(source).is_some_and(|read| same_folder(&read, &here)) => {
424				Some(here)
425			}
426			_ => return Err(NodeError::Exists),
427		};
428		// What the code opens is read before anything is made: a wrong code writes nothing.
429		let (source, opened) = open_source(source, code)?;
430		Self::check_place(directory)?;
431		let (library, new) = Self::make_recovering(
432			directory,
433			(&opened, code),
434			replacing.as_deref(),
435			joining,
436			protection,
437			rng,
438		)?;
439		let mark = library.directory.join(RECOVERING);
440		let mut recovering = Recovering {
441			library: Some(library),
442			mark: None,
443			source,
444			replacing,
445			code,
446			new,
447			holds_secrets: false,
448			keep: BTreeSet::new(),
449			revoked_anyway: BTreeSet::new(),
450		};
451		recovering
452			.revoked_anyway
453			.extend(cut_short.into_iter().chain(recovering.source.replica()));
454		// Held while it runs, so that a recovery started meanwhile leaves this one alone.
455		let held = fs::File::options()
456			.write(true)
457			.open(&mark)
458			.and_then(|file| file.try_lock().map(|()| file).map_err(io::Error::other))
459			.map_err(NodeError::file(&mark))?;
460		recovering.mark = Some(held);
461		if let Some(library) = recovering.library.as_mut() {
462			recovering.holds_secrets =
463				library.recover_personal(&recovering.source, (code, &opened), now, rng)?;
464		}
465		Ok(recovering)
466	}
467
468	/// Makes the replica that a recovery brings back, in a folder of `directory` marked as
469	/// [`RECOVERING`], beside the replica in `replacing`, if given, which the mark names, with
470	/// the keys that `joining` made and the personal space's first key, which `opened` gives,
471	/// and its spaces empty; and the records that list it by `code`.
472	fn make_recovering(
473		directory: &Path,
474		(opened, code): (&OpenedRecovery, &RecoveryCode),
475		replacing: Option<&Path>,
476		joining: Joining<'_>,
477		protection: &NewProtection<'_>,
478		rng: &mut impl CryptoRng,
479	) -> Result<(Self, NewRecords), NodeError> {
480		let personal = opened.space;
481		let (signing, decryption, device, app) = joining.into_parts();
482		// The new replica's records, as pairing would make them, with its own keys, and the
483		// listing that its key signs, beside the one that the code signs.
484		let key = signing.verifying_key();
485		let replica = nibkeep_governance::replica_record(personal, &key);
486		let encryption = decryption.encryption_key();
487		let endpoint = endpoint_of(&nibkeep_governance::endpoint_secret(&signing));
488		let own = Listing::sign(&signing, &encryption, personal, (opened.member, false)).to_text();
489		let added = nibkeep_governance::add_replica(
490			&NewReplica {
491				space: personal,
492				user: opened.member,
493				signing: &key,
494				encryption: &encryption,
495				endpoint: &endpoint,
496				device: &device,
497				app: &app,
498				keys: &[],
499				ai_agent: false,
500				given: &[],
501				listing: Some(&own),
502			},
503			rng,
504		);
505		let listing =
506			RecoveryListing::sign(code, (personal, replica, opened.member), &key, &encryption);
507		let info = Info {
508			user: opened.member,
509			device: added.device,
510			replica,
511			personal,
512		};
513		let keys = ReplicaKeys {
514			signing,
515			decryption,
516			storage: Key::generate(rng),
517			spaces: BTreeMap::from([(personal, BTreeMap::from([(0, opened.key.clone())]))]),
518		};
519		let replaced = replacing
520			.and_then(Path::file_name)
521			.map_or_else(String::new, |name| name.to_string_lossy().into_owned());
522		let folder = new_replica_folder_marked(
523			directory,
524			Some((RECOVERING, replaced.as_bytes())),
525			replacing,
526			rng,
527		)?;
528		let (mut key_file, compartment) = match KeyFile::create(&keys, protection, rng) {
529			Ok(created) => created,
530			Err(error) => {
531				let _ = fs::remove_dir_all(&folder);
532				return Err(error.into());
533			}
534		};
535		let made = key_file
536			.write(&folder.join(KEYS))
537			.map_err(NodeError::from)
538			.and_then(|()| info.write(&folder.join(INFO)))
539			.and_then(|()| Self::open_spaces(&folder, key_file.clone(), compartment, true));
540		match made {
541			Ok(mut library) => {
542				// The space takes the first change that the backup's file names as its first.
543				if let Some(open) = library.spaces.get_mut(&personal) {
544					open.stored.expect_roots_too([opened.root]);
545				}
546				Ok((library, NewRecords { added, listing }))
547			}
548			Err(error) => {
549				let _ = fs::remove_dir_all(&folder);
550				key_file.discard();
551				Err(error)
552			}
553		}
554	}
555
556	/// Takes in what `source` holds of the personal space, checked as a sync is, with the
557	/// first key alone, which `opened` gives; then the keys sealed to `code`, which the space
558	/// names and has not revoked. Returns whether the code holds the secrets.
559	fn recover_personal(
560		&mut self,
561		source: &Source<'_>,
562		(code, opened): (&RecoveryCode, &OpenedRecovery),
563		now: &dyn Fn() -> u64,
564		rng: &mut impl CryptoRng,
565	) -> Result<bool, NodeError> {
566		let personal = opened.space;
567		self.take_in_source(source, &[personal], now)?;
568		self.finish_opening()?;
569		if self.space(personal)?.stored.log().root()?.is_none() {
570			return Err(NodeError::NoRecoverySource(source.path().to_owned()));
571		}
572		// The code, which the personal space names and has not revoked, and the keys sealed to
573		// it, which open the rest.
574		let recovery_key = code.signing_key().verifying_key();
575		let record = recovery_record(personal, opened.member, &recovery_key);
576		let named = self.roster(personal)?.code(record).map(Code::stands);
577		match named {
578			None => return Err(NodeError::CodeOpensNothing),
579			Some(false) => return Err(NodeError::RecoveryCodeRevoked),
580			Some(true) => {}
581		}
582		let opening = code.decryption_key();
583		loop {
584			let roster = self.roster(personal)?;
585			if self.take_keys_of_code(personal, &roster, (record, &opening), rng)? == 0 {
586				break;
587			}
588		}
589		// The secrets that the code holds are the personal space's first.
590		let rosters = BTreeMap::from([(personal, self.roster(personal)?)]);
591		Ok(!self.secrets_code_opens(&rosters, code)?.is_empty())
592	}
593
594	/// Finishes the recovery in this new replica, whose personal space
595	/// [`Library::recover_personal`] took in, from `source`, with `code`, the new replica's
596	/// records being `new`, keeping the replicas in `keep`, as [`Recovering::finish`] says, but
597	/// for setting aside the replica it replaces.
598	fn recover_rest(
599		&mut self,
600		source: &Source<'_>,
601		(code, new, keep): (&RecoveryCode, &NewRecords, &BTreeSet<EntityId>),
602		secrets: Option<&NewProtection<'_>>,
603		now: &dyn Fn() -> u64,
604		rng: &mut impl CryptoRng,
605	) -> Result<Recovered, NodeError> {
606		let personal = self.info.personal;
607		// It writes with the newest of the keys, never with the first key, which the lost
608		// devices hold.
609		self.choose_writing_keys()?;
610		// It lists itself by the code, in a change that governs the space, which the space
611		// itself commits, as nothing lists it yet; then it gives its records their names, as
612		// pairing does.
613		let mut governing = new.added.governing.clone();
614		governing.push(list_by_recovery_code(&new.listing, rng));
615		self.commit_unlisted(personal, governing, now(), rng)?;
616		self.commit(personal, new.added.operations.clone(), now(), rng)?;
617		// The person's other spaces and groups, as far as the source holds them, which it
618		// says it holds, as every device that takes a space does.
619		let (spaces, missing) = self.recover_spaces(source, code, now, rng)?;
620		self.state_holding(&spaces, now(), rng)?;
621		// The secrets, while the records still name the lost devices that held them.
622		let recovered_secrets = self.take_code_secrets(code, secrets, now(), rng)?;
623		// The person's other devices are lost, but those kept: each is revoked, with a new key,
624		// in every space where they are listed.
625		let (revoked, kept): (Vec<Replica>, Vec<Replica>) = self
626			.replicas()?
627			.into_iter()
628			.filter(|replica| !replica.this && !replica.revoked)
629			.partition(|replica| !keep.contains(&replica.id));
630		// With them, in each space and group, the devices that they added there and that the
631		// personal space taken in does not list, as a computer that learned of a new device
632		// from another member first wrote the backup: no device of the person's is left to
633		// tell of them.
634		let ids: Vec<EntityId> = revoked.iter().map(|replica| replica.id).collect();
635		// What it names only: a failure to read it leaves the recovery to go on.
636		let out_of_reach = self.out_of_reach(&ids).unwrap_or_default();
637		let revoked_elsewhere = if revoked.is_empty() {
638			self.revoke_in_spaces_telling(now(), rng).0
639		} else {
640			self.revoke(&ids, now(), rng)?
641		};
642		// Then each space that the person reaches through a group alone lists it, and learns
643		// of the revocations there, by its own anchor of the groups' changes.
644		self.anchor_where_unlisted(&spaces, now(), rng)?;
645		self.settle_keys(now(), rng)?;
646		let from = match source {
647			// The backup, which carries the new device from now on, if the space still names
648			// it. The library is whole by now: an update that fails leaves the backup to the
649			// next one, as any update does, rather than throw away what came back.
650			Source::Backup(folder, backup) => {
651				let found = self
652					.backups()?
653					.into_iter()
654					.find(|found| found.id == *backup);
655				let updated = found.as_ref().is_some_and(|found| {
656					matches!(
657						self.update_backup(found, folder, now, &|| false),
658						Ok(Some(_))
659					)
660				});
661				RecoveredFrom::Backup {
662					name: found.map(|found| found.name),
663					updated,
664				}
665			}
666			Source::Library(folder, replica) => RecoveredFrom::Library {
667				folder: folder.clone(),
668				replica: *replica,
669				replaced: false,
670				set_aside: None,
671			},
672		};
673		Ok(Recovered {
674			revoked_elsewhere,
675			revoked,
676			kept,
677			spaces,
678			missing,
679			out_of_reach,
680			secrets: recovered_secrets,
681			from,
682		})
683	}
684}
685
686impl Library {
687	/// Commits `operations` in `space` as this replica, which no counting change there may
688	/// list yet, as [`Library::commit`] would but for that check: for a replica that lists
689	/// itself by a code, or through a group by its own anchor.
690	fn commit_unlisted(
691		&mut self,
692		space: SpaceId,
693		operations: Vec<nibkeep_model::Operation>,
694		wall_millis: u64,
695		rng: &mut impl CryptoRng,
696	) -> Result<(), NodeError> {
697		let open = self
698			.spaces
699			.get_mut(&space)
700			.ok_or(NodeError::NoSpace(space))?;
701		let reloads = open.stored.reloads();
702		open.commit(
703			&self.replica.signing,
704			&self.code_types,
705			operations,
706			wall_millis,
707			rng,
708		)?;
709		if open.stored.reloads() != reloads {
710			self.read_again(space)?;
711		}
712		Ok(())
713	}
714
715	/// Takes the person's other spaces and groups that `code` is given, with what `source`
716	/// holds of each, and the keys sealed to the code there; and lists this replica by the
717	/// code in each where the code stands on the record of the person that the personal
718	/// space's entry names, which has a role there. Returns the spaces given to the code that
719	/// came back, and those that the source holds nothing of, which it takes away again; the
720	/// logs of the groups that those spaces add, which it holds to follow them, are neither.
721	///
722	/// It goes round until a round takes nothing new: a group's entries for the code open
723	/// once its keys do, and a space takes the changes of a group's members once it follows
724	/// the group, which it does once it holds the change that adds it. So each round takes in
725	/// the spaces new to it, and again those that follow groups.
726	fn recover_spaces(
727		&mut self,
728		source: &Source<'_>,
729		code: &RecoveryCode,
730		now: &dyn Fn() -> u64,
731		rng: &mut impl CryptoRng,
732	) -> Result<(Vec<SpaceId>, Vec<SpaceId>), NodeError> {
733		let personal = self.info.personal;
734		let recovery_key = code.signing_key().verifying_key();
735		let opening = code.decryption_key();
736		// The person's record in each space that the personal space gives the code, and the
737		// spaces that any entry gives it.
738		let mut members: BTreeMap<SpaceId, EntityId> = BTreeMap::new();
739		let mut given: BTreeSet<SpaceId> = BTreeSet::new();
740		let mut taken_in: BTreeSet<SpaceId> = BTreeSet::from([personal]);
741		loop {
742			let held = self.spaces.len();
743			for (entry, record, from_personal) in self.code_entries(&recovery_key)? {
744				if from_personal {
745					members.entry(entry.space).or_insert(entry.member);
746				}
747				given.insert(entry.space);
748				if self.spaces.contains_key(&entry.space) {
749					continue;
750				}
751				let Some(key) = entry
752					.open(&opening, record)
753					.filter(|key| key_hash(key) == entry.hash)
754				else {
755					continue;
756				};
757				self.add_space(entry.space, &key, rng)?;
758				if let Some(open) = self.spaces.get_mut(&entry.space) {
759					open.stored
760						.expect_roots_too([ChangeId::from_hash(entry.root)]);
761				}
762			}
763			// And the logs of the groups that those spaces add, which they follow.
764			self.take_group_keys(rng)?;
765			let _ = self.follow_all_groups();
766			let mut others = Vec::new();
767			for space in self.spaces() {
768				if !taken_in.contains(&space) || !self.inner_groups(space)?.is_empty() {
769					others.push(space);
770				}
771			}
772			others.retain(|&space| space != personal);
773			if others.is_empty() {
774				break;
775			}
776			taken_in.extend(others.iter().copied());
777			let taken = self.take_in_source(source, &others, now)?;
778			let _ = self.follow_all_groups();
779			let mut keys = 0;
780			for &space in &others {
781				keys += self.take_keys_of_codes(space, &recovery_key, &opening, rng)?;
782			}
783			if self.spaces.len() == held && taken == 0 && keys == 0 {
784				break;
785			}
786		}
787		self.choose_writing_keys()?;
788		let mut spaces = Vec::new();
789		let mut missing = Vec::new();
790		for space in given {
791			if !self.spaces.contains_key(&space) {
792				continue;
793			}
794			if self.space(space)?.stored.log().root()?.is_some() {
795				spaces.push(space);
796			} else {
797				missing.push(space);
798			}
799		}
800		// A group that a space it holds adds stays, empty, as the groups would take its log
801		// again to follow it.
802		let mut followed = BTreeSet::new();
803		for open in self.spaces.values() {
804			followed.extend(
805				open.stored
806					.log()
807					.groups(&open.keys)?
808					.into_iter()
809					.map(|found| found.group.group),
810			);
811		}
812		for &space in &missing {
813			if !followed.contains(&space) {
814				self.remove_space(space, rng);
815			}
816		}
817		for &space in &spaces {
818			if let Some(&member) = members.get(&space) {
819				self.list_by_code_in(space, member, code, now(), rng)?;
820			}
821		}
822		Ok((spaces, missing))
823	}
824
825	/// The entries that give spaces to the code whose recovery key is `recovery_key`: on each
826	/// of its records in the personal space, and in each group this replica holds, for a
827	/// space that the group agreed to join; each with the record it is on, and whether the
828	/// personal space gives it, whose entries name the person's record in the space.
829	fn code_entries(
830		&self,
831		recovery_key: &VerifyingKey,
832	) -> Result<Vec<(SpaceEntry, EntityId, bool)>, NodeError> {
833		let personal = self.info.personal;
834		let mut entries = Vec::new();
835		let records = self.code_records(personal, recovery_key)?;
836		let open = self.space(personal)?;
837		for governing in open.stored.log().governing_statements(&open.keys)? {
838			let record = governing.statement.entity;
839			if !records.contains(&record) {
840				continue;
841			}
842			if let Some(entry) = governing
843				.counting_text(&SPACE_ENTRY)
844				.and_then(SpaceEntry::from_text)
845			{
846				entries.push((entry, record, true));
847			}
848		}
849		for space in self.spaces() {
850			if space == personal || !self.is_group(space)? {
851				continue;
852			}
853			for record in self.code_records(space, recovery_key)? {
854				for (entry, _) in self.agreed_entries(space, record)? {
855					entries.push((entry, record, false));
856				}
857			}
858		}
859		Ok(entries)
860	}
861
862	/// The records in `space` of the code whose recovery key is `recovery_key`, for whichever
863	/// member each names, as the space's codes have them.
864	fn code_records(
865		&self,
866		space: SpaceId,
867		recovery_key: &VerifyingKey,
868	) -> Result<BTreeSet<EntityId>, NodeError> {
869		Ok(self
870			.roster(space)?
871			.codes()
872			.filter(|code| code.statement.key == *recovery_key)
873			.map(|code| code.record)
874			.collect())
875	}
876
877	/// Takes the keys of `space` that statements seal to the code whose recovery key is
878	/// `recovery_key`, on each of its records there, opening them with `opening`, until none
879	/// is left to take: a key may give one that it opens. Returns how many it took.
880	fn take_keys_of_codes(
881		&mut self,
882		space: SpaceId,
883		recovery_key: &VerifyingKey,
884		opening: &DecryptionKey,
885		rng: &mut impl CryptoRng,
886	) -> Result<usize, NodeError> {
887		let mut total = 0;
888		loop {
889			let roster = self.roster(space)?;
890			let records: Vec<EntityId> = roster
891				.codes()
892				.filter(|code| code.statement.key == *recovery_key)
893				.map(|code| code.record)
894				.collect();
895			let mut taken = 0;
896			for record in records {
897				taken += self.take_keys_of_code(space, &roster, (record, opening), rng)?;
898			}
899			if taken == 0 {
900				return Ok(total);
901			}
902			total += taken;
903		}
904	}
905
906	/// Lists this replica in a space with members by `code`, on the record of `member`, the
907	/// person there, as pairing would list it there, with its own listing and the code's: only
908	/// where it is not listed yet, the code stands on that member's record for it, and the
909	/// member has a role. Returns whether it did.
910	fn list_by_code_in(
911		&mut self,
912		space: SpaceId,
913		member: EntityId,
914		code: &RecoveryCode,
915		wall_millis: u64,
916		rng: &mut impl CryptoRng,
917	) -> Result<bool, NodeError> {
918		let key = self.replica.signing.verifying_key();
919		{
920			let open = self.space(space)?;
921			let log = open.stored.log();
922			if !log.has_members(&open.keys)? || log.is_listed(&key, &open.keys)? {
923				return Ok(false);
924			}
925			let has_role = log
926				.member_roles(&open.keys)?
927				.get(&member)
928				.is_some_and(|role| *role != Role::None);
929			let record = recovery_record(space, member, &code.signing_key().verifying_key());
930			if !has_role || !self.roster(space)?.code(record).is_some_and(Code::stands) {
931				return Ok(false);
932			}
933		}
934		let encryption = self.replica.decryption.encryption_key();
935		let listing = Listing::sign(&self.replica.signing, &encryption, space, (member, false));
936		let (device, app) = self.own_names()?;
937		let endpoint = endpoint_of(&nibkeep_governance::endpoint_secret(&self.replica.signing));
938		let listed = list_replica(
939			&SpaceReplica {
940				record: listing.record,
941				device_record: nibkeep_governance::device_record(space, &key),
942				member,
943				signing: &key,
944				encryption: &encryption,
945				listing: &listing.to_text(),
946				endpoint: Some(&endpoint),
947				device: &device,
948				app: &app,
949				ai_agent: false,
950			},
951			rng,
952		);
953		let by_code =
954			RecoveryListing::sign(code, (space, listing.record, member), &key, &encryption);
955		let mut governing = listed.governing;
956		governing.push(list_by_recovery_code(&by_code, rng));
957		self.commit_unlisted(space, governing, wall_millis, rng)?;
958		// A listing that does not count, as one that a change it does not know of sets aside,
959		// leaves the space to be read, as the backup held it, and the rest of the recovery
960		// goes on.
961		let open = self.space(space)?;
962		if !open.stored.log().is_listed(&key, &open.keys)? {
963			return Ok(false);
964		}
965		self.commit(space, listed.operations, wall_millis, rng)?;
966		Ok(true)
967	}
968
969	/// Anchors the groups' changes in each of `spaces` that does not list this replica yet,
970	/// and that a group which reaches it lists it in: so the space lists it through the group,
971	/// by its own anchor, and learns of what the group revoked.
972	fn anchor_where_unlisted(
973		&mut self,
974		spaces: &[SpaceId],
975		wall_millis: u64,
976		rng: &mut impl CryptoRng,
977	) -> Result<(), NodeError> {
978		let _ = self.follow_all_groups();
979		let own = self.replica.signing.verifying_key();
980		for &space in spaces {
981			let root = {
982				let open = self.space(space)?;
983				let log = open.stored.log();
984				if log.is_listed(&own, &open.keys)? {
985					continue;
986				}
987				let Some(root) = log.root()? else { continue };
988				root
989			};
990			let mut listed_by_a_group = false;
991			for (_, group) in self.reaching_groups(space, root)? {
992				let open = self.space(group.group)?;
993				let log = open.stored.log();
994				listed_by_a_group |=
995					log.is_listed(&own, &open.keys)? && !log.is_revoked(&own, &open.keys)?;
996			}
997			let operations = if listed_by_a_group {
998				self.anchoring(space, rng)?
999			} else {
1000				Vec::new()
1001			};
1002			if operations.is_empty() {
1003				continue;
1004			}
1005			self.commit_unlisted(space, operations, wall_millis, rng)?;
1006		}
1007		Ok(())
1008	}
1009}
1010
1011/// The records that list the replica that a recovery brings back: those pairing would make,
1012/// and its listing by the code.
1013struct NewRecords {
1014	added: nibkeep_governance::AddedReplica,
1015	listing: RecoveryListing,
1016}
1017
1018/// What a recovery takes the library from.
1019enum Source<'a> {
1020	/// A backup, in this folder, by its record's ID.
1021	Backup(&'a Path, EntityId),
1022	/// A library on this computer that no longer unlocks: the folder of its replica, which is
1023	/// read as a copy is, and the replica, as the folder names it, if it does.
1024	Library(PathBuf, Option<EntityId>),
1025}
1026
1027impl Source<'_> {
1028	/// The folder that holds it.
1029	fn path(&self) -> &Path {
1030		match self {
1031			Self::Backup(folder, _) => folder,
1032			Self::Library(folder, _) => folder,
1033		}
1034	}
1035
1036	/// The replica of a library that it is, as its folder names it.
1037	const fn replica(&self) -> Option<EntityId> {
1038		match self {
1039			Self::Backup(..) => None,
1040			Self::Library(_, replica) => *replica,
1041		}
1042	}
1043
1044	/// Whether it is a library whose folder names no replica, as one whose files are
1045	/// damaged.
1046	const fn unnamed(&self) -> bool {
1047		matches!(self, Self::Library(_, None))
1048	}
1049}
1050
1051impl Library {
1052	/// Takes in what `source` holds of `spaces` and this replica lacks, checked as a sync is:
1053	/// what a backup holds, or a library's replica, whose changes are taken as from their
1054	/// authors, as a backup's are. Returns how many changes, or items of a library, were new.
1055	///
1056	/// # Errors
1057	///
1058	/// Returns [`NodeError::BackupBusy`] if another program updates the backup, and an error
1059	/// if what is taken in cannot be saved.
1060	fn take_in_source(
1061		&mut self,
1062		source: &Source<'_>,
1063		spaces: &[SpaceId],
1064		now: &dyn Fn() -> u64,
1065	) -> Result<usize, NodeError> {
1066		match source {
1067			Source::Backup(folder, backup) => Ok(self
1068				.take_in_backup_at((folder, *backup), spaces, now)?
1069				.ok_or(NodeError::BackupBusy)?
1070				.changes),
1071			Source::Library(folder, _) => self.take_in_lost_replica(folder, spaces, now),
1072		}
1073	}
1074}
1075
1076/// The source in `source`, and what its recovery file gives `code`.
1077fn open_source<'a>(
1078	source: &'a Path,
1079	code: &RecoveryCode,
1080) -> Result<(Source<'a>, OpenedRecovery), NodeError> {
1081	let no_source = || NodeError::NoRecoverySource(source.to_owned());
1082	let (opened, file) = if let Some(backup) = backup::named_at(source) {
1083		(Source::Backup(source, backup), source.join(RECOVERY_FILE))
1084	} else {
1085		let folder = source_replica(source).ok_or_else(no_source)?;
1086		// A replica that a later version changed is read by none of its files.
1087		crate::engines::check(&folder)?;
1088		let file = folder.join(RECOVERY_FILE);
1089		// Read once, as the replica that the recovery revokes in any case.
1090		let replica = Info::read(&folder.join(INFO)).ok().map(|info| info.replica);
1091		(Source::Library(folder, replica), file)
1092	};
1093	// Where a folder replaces a file by deleting it first, as Android's picker does, a
1094	// backup's new recovery file waits in `tmp/` until the next update moves it in.
1095	let waiting = file
1096		.parent()
1097		.map(|folder| folder.join("tmp").join(RECOVERY_FILE));
1098	// One there that is missing or does not read gives way to one waiting that reads.
1099	let file = match (RecoveryFile::read(&file), &opened, waiting) {
1100		(Ok(Some(file)), _, _) => file,
1101		(there, Source::Backup(..), Some(waiting)) => match RecoveryFile::read(&waiting) {
1102			Ok(Some(file)) => file,
1103			_ => there?.ok_or_else(no_source)?,
1104		},
1105		(there, ..) => there?.ok_or_else(no_source)?,
1106	};
1107	let key = file.open(code)?;
1108	Ok((opened, key))
1109}
1110
1111/// The folder of the replica that a recovery from the library in `source` reads: its
1112/// replica that is here, but one that a recovery left unfinished, or that a recovery in
1113/// place replaces; or, where none is here, as in a library restored from another computer's
1114/// backup, its one copy with a recovery file; or `source` itself, if it is the folder of a
1115/// replica with a recovery file.
1116fn source_replica(source: &Path) -> Option<PathBuf> {
1117	let Some(folders) = replica_folders(source) else {
1118		let replica = source.join(crate::place::PLACE).is_file()
1119			&& source.join(RECOVERY_FILE).is_file()
1120			&& !unfinished(source);
1121		return replica.then(|| source.to_owned());
1122	};
1123	let folders: Vec<(PathBuf, bool)> = folders
1124		.into_iter()
1125		.filter(|(folder, _)| !unfinished(folder))
1126		.collect();
1127	let replaced: Vec<PathBuf> = folders
1128		.iter()
1129		.filter(|(_, here)| *here)
1130		.filter_map(|(folder, _)| replaced_by(folder))
1131		.collect();
1132	let mut here = folders
1133		.iter()
1134		.filter(|(folder, here)| *here && !replaced.contains(folder));
1135	match (here.next(), here.next()) {
1136		(Some((folder, _)), None) => return Some(folder.clone()),
1137		(Some(_), Some(_)) => return None,
1138		(None, _) => {}
1139	}
1140	let mut copies = folders
1141		.iter()
1142		.filter(|(folder, _)| folder.join(RECOVERY_FILE).is_file());
1143	match (copies.next(), copies.next()) {
1144		(Some((folder, _)), None) => Some(folder.clone()),
1145		_ => None,
1146	}
1147}
1148
1149/// Where a recovery in place sets aside the folder of the replica `old`: beside it, under a
1150/// name that [`SET_ASIDE`] starts.
1151fn set_aside_path(old: &Path) -> PathBuf {
1152	let name = old
1153		.file_name()
1154		.map_or_else(String::new, |name| name.to_string_lossy().into_owned());
1155	old.with_file_name(format!("{SET_ASIDE}{name}"))
1156}
1157
1158/// Sets aside the folder of the replica `old`, which a recovery in place replaced, at
1159/// [`set_aside_path`].
1160fn set_aside(old: &Path) -> Result<(), NodeError> {
1161	let aside = set_aside_path(old);
1162	if aside.exists() {
1163		return Err(NodeError::file(&aside)(io::ErrorKind::AlreadyExists.into()));
1164	}
1165	fs::rename(old, &aside).map_err(NodeError::file(old))?;
1166	#[cfg(unix)]
1167	if let Some(parent) = aside.parent() {
1168		let _ = fs::File::open(parent).and_then(|folder| folder.sync_all());
1169	}
1170	Ok(())
1171}
1172
1173/// The name of the replica's folder that the [`RECOVERING`] mark in `folder` names, which the
1174/// replica in `folder` replaces: `None` for a mark that names none, as a recovery from a
1175/// backup leaves, or names no folder beside it.
1176fn replaced_name(folder: &Path) -> Option<String> {
1177	let bytes = fs::read(folder.join(RECOVERING)).ok()?;
1178	let name = String::from_utf8(bytes).ok()?;
1179	let plain = !name.is_empty()
1180		&& !name.starts_with('.')
1181		&& !name.contains(['/', '\\'])
1182		&& Path::new(&name)
1183			.file_name()
1184			.is_some_and(|own| own == name.as_str());
1185	plain.then_some(name)
1186}
1187
1188/// The folder of the replica that the replica in `folder` replaces, as its [`RECOVERING`]
1189/// mark names it, while it is still in its place: a recovery in place still runs, was cut
1190/// short, or is done but could not set it aside yet.
1191pub(crate) fn replaced_by(folder: &Path) -> Option<PathBuf> {
1192	let replaced = folder.parent()?.join(replaced_name(folder)?);
1193	replaced.is_dir().then_some(replaced)
1194}
1195
1196/// Whether the replica in `folder` is one that a recovery brings back, which still runs or
1197/// was cut short, so that the library does not open: it has its [`RECOVERING`] mark, and no
1198/// [`RECOVERED`] file that says that it is whole.
1199pub(crate) fn unfinished(folder: &Path) -> bool {
1200	folder.join(RECOVERING).exists() && !folder.join(RECOVERED).exists()
1201}
1202
1203/// Finishes what a recovery in place that is done left in `folder`, its new replica's: sets
1204/// aside the replica it replaces, if that is still in its place, then removes the
1205/// [`RECOVERING`] mark, and the [`RECOVERED`] file last. Nothing, while a recovery holds the
1206/// mark, or while the old replica cannot be set aside, which then stays hidden behind the
1207/// mark.
1208pub(crate) fn tidy(folder: &Path) {
1209	let done = folder.join(RECOVERED);
1210	if !done.exists() {
1211		return;
1212	}
1213	let path = folder.join(RECOVERING);
1214	if let Ok(mark) = fs::File::options().write(true).open(&path) {
1215		if mark.try_lock().is_err() {
1216			return;
1217		}
1218		drop(mark);
1219		if let Some(old) = replaced_by(folder)
1220			&& set_aside(&old).is_err()
1221		{
1222			return;
1223		}
1224		if fs::remove_file(&path).is_err() {
1225			return;
1226		}
1227	}
1228	let _ = fs::remove_file(&done);
1229	#[cfg(unix)]
1230	let _ = fs::File::open(folder).and_then(|folder| folder.sync_all());
1231}
1232
1233/// Removes the replica of a recovery that was cut short, as by a crash, which nobody knows
1234/// but through a backup that it updated: its folder and its keystore keys. One whose
1235/// recovery still runs, which holds its mark, stays, and so does one whose recovery is
1236/// done. Returns the replica it removed, as its folder named it.
1237///
1238/// # Errors
1239///
1240/// Returns an error if the folder cannot be removed.
1241fn remove_cut_short(directory: &Path) -> Result<Option<EntityId>, NodeError> {
1242	let Found::Here { folder, .. } = found(directory) else {
1243		return Ok(None);
1244	};
1245	if !unfinished(&folder) {
1246		return Ok(None);
1247	}
1248	let Ok(mark) = fs::File::options()
1249		.write(true)
1250		.open(folder.join(RECOVERING))
1251	else {
1252		return Ok(None);
1253	};
1254	if mark.try_lock().is_err() {
1255		return Ok(None);
1256	}
1257	drop(mark);
1258	let replica = Info::read(&folder.join(INFO)).ok().map(|info| info.replica);
1259	if let Ok(key_file) = KeyFile::read(&folder.join(KEYS)) {
1260		key_file.discard();
1261	}
1262	fs::remove_dir_all(&folder).map_err(NodeError::file(&folder))?;
1263	Ok(replica)
1264}