Skip to main content

nibkeep_node/library/
members.rs

1//! The members of a shared space and their roles, as its counting governing changes say,
2//! and the two sides of an invitation to it: the admin's, which confirms who asks and adds
3//! the member, and the joiner's, which signs its listing and takes the space
4//! ([Identity](../../../../docs/spec/identity.md#9-members-and-invitations),
5//! [technical design](../../../../docs/Technical-design.md#13-sharing)).
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use nibkeep_base::{EntityId, SpaceId, StatementId};
10use nibkeep_crypto::rand_core::CryptoRng;
11use nibkeep_crypto::{VerifyingKey, key_hash};
12use nibkeep_governance::{
13	InvitationGrant, InvitationRequest, Listing, NewMember, Offer, Role as MemberRole, SpaceEntry,
14	SpaceReplica, add_member, encryption_hash, replica_record,
15};
16use nibkeep_model::storage::Statements;
17use nibkeep_model::{Operation, Statement, Value, fields};
18use nibkeep_sync::{Accepting, Inviting};
19
20use super::Library;
21use super::entities::display_name;
22use crate::NodeError;
23
24/// A member of a shared space, as its counting governing changes say: a user, with a role,
25/// and the replicas listed for them there.
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct SpaceMember {
28	/// The member's record in the space.
29	pub record: EntityId,
30	/// The ID of the user whom the member is, as the record states it.
31	pub user: Option<EntityId>,
32	/// The member's name in the space.
33	pub name: Option<String>,
34	/// The member's role now: [`MemberRole::None`] for one who left or was removed.
35	pub role: MemberRole,
36	/// Whether the member is the one this replica is listed for.
37	pub this_user: bool,
38	/// The member's replicas there, by record.
39	pub replicas: Vec<MemberReplica>,
40	/// The member's link to a person in the space.
41	pub person: PersonLink,
42}
43
44/// A member's link to a person in a shared space: it holds when an admin's statement and the
45/// member's own name the same person; an admin's own statement counts for both while they are an
46/// admin
47/// ([users and people](../../../../docs/Design.md#610-users-people-and-devices)).
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
49pub struct PersonLink {
50	/// The person the member is linked to, if the two agree, and the person is not deleted.
51	pub holds: Option<EntityId>,
52	/// The person that an admin's latest statement names, if one states it.
53	pub by_admin: Option<EntityId>,
54	/// The person that the member's own latest statement names, if they state it.
55	pub by_member: Option<EntityId>,
56	/// Whether the two agree on a person who is deleted, which holds no link.
57	pub deleted: bool,
58}
59
60/// A replica that a shared space lists for a member.
61#[derive(Clone, Debug, PartialEq, Eq)]
62#[expect(
63	clippy::struct_excessive_bools,
64	reason = "each says something apart of the replica, which lists show apart"
65)]
66pub struct MemberReplica {
67	/// Its record in the space.
68	pub record: EntityId,
69	/// The name of its app.
70	pub app: Option<String>,
71	/// The name of its device.
72	pub device: Option<String>,
73	/// Its endpoint ID, which the others connect to, if its record has one.
74	pub endpoint: Option<[u8; 32]>,
75	/// Its verifying key.
76	pub signing: VerifyingKey,
77	/// Whether the space revoked it.
78	pub revoked: bool,
79	/// Whether it dropped the space: its choice that stands there does not hold it
80	/// ([technical design](../../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces)).
81	pub dropped: bool,
82	/// Whether it is an AI agent's, which every member sees.
83	pub ai_agent: bool,
84	/// Whether it is this replica.
85	pub this: bool,
86	/// Whether it holds the space's secrets, as given to it by the replica it asked, or as
87	/// it set them up.
88	pub holds_secrets: bool,
89	/// Whether it asks another replica for the space's secrets, which has not given them.
90	pub asks_for_secrets: bool,
91	/// The replica that it asked for the space's secrets, if it asked one.
92	pub secrets_from: Option<EntityId>,
93}
94
95/// Who asks to join a space, as the admin's device shows them before the person confirms:
96/// the user, by ID and name, the names of the device and app that ask, the members whose
97/// records name the same user ID, and whether the user was a member before.
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct Invitee {
100	/// The user's ID.
101	pub user: EntityId,
102	/// The user's name, as their library has it.
103	pub user_name: String,
104	/// The name of the device that asks.
105	pub device: String,
106	/// The name of its app.
107	pub app: String,
108	/// The members, with a role, whose records name the same user ID: a new member is
109	/// another all the same.
110	pub same_user: Vec<SpaceMember>,
111	/// Whether a member record of the same user has the role none: the user was a member,
112	/// left or was removed, and comes back as a new member.
113	pub was_member: bool,
114}
115
116impl Library {
117	/// The members of a shared space, as its counting governing changes say, with their
118	/// roles now and their replicas, sorted by name and record.
119	///
120	/// # Errors
121	///
122	/// Returns [`NodeError::NeverShared`] for the personal space, and an error if the space
123	/// cannot be read.
124	pub fn members(&self, space: SpaceId) -> Result<Vec<SpaceMember>, NodeError> {
125		self.check_shared(space)?;
126		let own = self.replica.signing.verifying_key();
127		let this_member = self.member_in(space)?;
128		let open = self.space(space)?;
129		let log = open.stored.log();
130		let state = log.state();
131		let roles = log.member_roles(&open.keys)?;
132		let (users, owners) = self.users_and_owners(space)?;
133		let roster = self.roster(space)?;
134		let holders = roster.secrets_holders();
135		let mut replicas: BTreeMap<EntityId, Vec<MemberReplica>> = BTreeMap::new();
136		for record in roster.replicas() {
137			let Some(key) = roster.keys_of(record).first().copied() else {
138				continue;
139			};
140			let Some(owner) = owners.get(key.as_bytes()) else {
141				continue;
142			};
143			let found = nibkeep_governance::replica(state, record)?;
144			let device = found.as_ref().and_then(|found| found.device);
145			replicas.entry(*owner).or_default().push(MemberReplica {
146				record,
147				app: display_name(state, &open.types, &self.languages, record)?,
148				device: match device {
149					Some(device) => display_name(state, &open.types, &self.languages, device)?,
150					None => None,
151				},
152				endpoint: found.and_then(|found| found.endpoint),
153				signing: key,
154				revoked: log.is_revoked(&key, &open.keys)?,
155				dropped: !log.holds_space(&key, &open.keys)?,
156				ai_agent: log.is_ai_agent(&key, &open.keys)?,
157				this: key == own,
158				holds_secrets: holders.contains(&record),
159				asks_for_secrets: roster.secrets_encryption_of(record).is_some()
160					&& roster
161						.secrets_from(record)
162						.is_some_and(|from| from != record)
163					&& !holders.contains(&record),
164				secrets_from: roster.secrets_from(record).filter(|from| *from != record),
165			});
166		}
167		// The groups in it have records of their own there, which no user is.
168		let groups: BTreeSet<EntityId> = log
169			.groups(&open.keys)?
170			.iter()
171			.map(|found| found.record)
172			.collect();
173		let mut members = Vec::new();
174		for (&record, &role) in &roles {
175			if groups.contains(&record) {
176				continue;
177			}
178			members.push(SpaceMember {
179				record,
180				user: users.get(&record).copied(),
181				name: display_name(state, &open.types, &self.languages, record)?,
182				role,
183				this_user: this_member == Some(record),
184				replicas: replicas.remove(&record).unwrap_or_default(),
185				person: person_link((&open.stored, state), (&owners, &roles), record)?,
186			});
187		}
188		members.sort_by(|a, b| (&a.name, a.record).cmp(&(&b.name, b.record)));
189		Ok(members)
190	}
191
192	/// The member of a shared space that `reference` names: by name, whatever the case, or
193	/// by the start of the record's ID, at least four characters long; of several, the one
194	/// with a role, if one alone has one.
195	///
196	/// # Errors
197	///
198	/// Returns [`NodeError::NoMember`] if none matches, [`NodeError::Ambiguous`] if several
199	/// do, and the errors of [`Library::members`].
200	pub fn find_member(&self, space: SpaceId, reference: &str) -> Result<EntityId, NodeError> {
201		let found = self.find_members(space, reference)?;
202		if let [member] = found.as_slice() {
203			return Ok(*member);
204		}
205		// One who came back has a record of the past too: the one with a role is meant.
206		let roles = {
207			let open = self.space(space)?;
208			open.stored.log().member_roles(&open.keys)?
209		};
210		let current: Vec<EntityId> = found
211			.iter()
212			.copied()
213			.filter(|member| {
214				roles
215					.get(member)
216					.is_some_and(|role| *role != MemberRole::None)
217			})
218			.collect();
219		match current.as_slice() {
220			[member] => Ok(*member),
221			_ => Err(NodeError::Ambiguous {
222				reference: reference.to_owned(),
223				candidates: found,
224			}),
225		}
226	}
227
228	/// Every member of a shared space that `reference` names, as [`Library::find_member`]
229	/// finds them, those who left or were removed included: one who came back has a record
230	/// of the past too.
231	///
232	/// # Errors
233	///
234	/// Returns [`NodeError::NoMember`] if none matches, and the errors of
235	/// [`Library::members`].
236	pub fn find_members(
237		&self,
238		space: SpaceId,
239		reference: &str,
240	) -> Result<Vec<EntityId>, NodeError> {
241		let lowered = reference.to_lowercase();
242		let members = self.members(space)?;
243		let by_name: Vec<EntityId> = members
244			.iter()
245			.filter(|member| {
246				member
247					.name
248					.as_ref()
249					.is_some_and(|name| name.to_lowercase() == lowered)
250			})
251			.map(|member| member.record)
252			.collect();
253		let found = if by_name.is_empty() && lowered.len() >= 4 {
254			members
255				.iter()
256				.filter(|member| member.record.to_string().starts_with(&lowered))
257				.map(|member| member.record)
258				.collect()
259		} else {
260			by_name
261		};
262		if found.is_empty() {
263			return Err(NodeError::NoMember(reference.to_owned()));
264		}
265		Ok(found)
266	}
267
268	/// Gives a member of a shared space a role, as an admin of it: viewer, editor or admin;
269	/// the role none removes them, as [`Library::remove_member`] does.
270	///
271	/// # Errors
272	///
273	/// Returns [`NodeError::NeverShared`] for the personal space, [`NodeError::AdminsOnly`]
274	/// if this replica's member is no admin, [`NodeError::NoMember`] if the space has no such
275	/// member, [`NodeError::LastAdmin`] if the space would have no admin left, and an error if
276	/// the change cannot be saved.
277	pub fn give_role(
278		&mut self,
279		space: SpaceId,
280		member: EntityId,
281		role: MemberRole,
282		wall_millis: u64,
283		rng: &mut impl CryptoRng,
284	) -> Result<(), NodeError> {
285		self.observe_wall(wall_millis);
286		self.check_shared(space)?;
287		if role == MemberRole::None {
288			return self.remove_member(space, member, wall_millis, rng);
289		}
290		self.check_admin(space, "give roles")?;
291		let roles = {
292			let open = self.space(space)?;
293			open.stored.log().member_roles(&open.keys)?
294		};
295		// Making an admin, or lowering one, needs an admin for good.
296		if role == MemberRole::Admin || roles.get(&member) == Some(&MemberRole::Admin) {
297			self.check_settled_admin(space, "make or lower admins")?;
298		}
299		match roles.get(&member) {
300			None | Some(MemberRole::None) => return Err(NodeError::NoMember(member.to_string())),
301			Some(now) if *now == role => return Ok(()),
302			Some(_) => {}
303		}
304		// A group's record in the space is never an admin's.
305		if role == MemberRole::Admin {
306			let open = self.space(space)?;
307			let group = open
308				.stored
309				.log()
310				.groups(&open.keys)?
311				.iter()
312				.any(|found| found.record == member);
313			if group {
314				return Err(NodeError::GroupAsAdmin);
315			}
316		}
317		let admins = roles
318			.iter()
319			.filter(|(other, given)| **given == MemberRole::Admin && **other != member)
320			.count();
321		if role != MemberRole::Admin && admins == 0 {
322			return Err(NodeError::LastAdmin);
323		}
324		self.set_role(space, member, role, wall_millis, rng)
325	}
326
327	/// Removes a member of a shared space, as an admin of it, or, for this replica's own
328	/// member, leaves, as [`Library::leave`] does: gives them the role none, which ends every
329	/// replica of theirs there, and gives the space a new key, sealed to the replicas that
330	/// remain, so that they read nothing added after. What they did without knowing of it is
331	/// set aside on every device, for an admin to review.
332	///
333	/// # Errors
334	///
335	/// Returns [`NodeError::NeverShared`] for the personal space, [`NodeError::AdminsOnly`]
336	/// if this replica's member is no admin, [`NodeError::NoMember`] if the space has no such
337	/// member, or they left already, [`NodeError::LastAdmin`] if the space would have no admin
338	/// left, and an error if the changes cannot be saved.
339	pub fn remove_member(
340		&mut self,
341		space: SpaceId,
342		member: EntityId,
343		wall_millis: u64,
344		rng: &mut impl CryptoRng,
345	) -> Result<(), NodeError> {
346		self.observe_wall(wall_millis);
347		if self.check_remove(space, member)? {
348			return self.leave(space, wall_millis, rng).map(|_| ());
349		}
350		// A member who is in the space through a group too is kept out of it, in the same
351		// change.
352		let through = self.keys_through_groups(space, member)?;
353		let mut operations = vec![self.role_operation(space, member, MemberRole::None, rng)?];
354		operations.extend(self.kept_out_operations(space, &through, true, rng)?);
355		self.commit(space, operations, wall_millis, rng)?;
356		// The removal is saved: if the new key fails, the next sync makes one, as this
357		// replica's newest key is not safe; and a new secrets key, if the secrets are unlocked
358		// here, or else the first replica that unlocks them makes one.
359		self.after_departure(space, wall_millis, rng);
360		Ok(())
361	}
362
363	/// Leaves a shared space: gives this replica's own member the role none, which ends every
364	/// replica of the user there, and keeps the user out of it through groups, where they are
365	/// in it through one, staying in the group. They keep what they hold, read only, and get
366	/// nothing added after; the members who remain give the space a new key as they learn of
367	/// it. Returns whether it closed the space, as the last member there.
368	///
369	/// # Errors
370	///
371	/// Returns [`NodeError::NeverShared`] for the personal space, [`NodeError::Removed`] if
372	/// the member left or was removed already, [`NodeError::NotListed`] if this replica is no
373	/// member's there, [`NodeError::AiAgentMayNot`] for an AI agent's replica,
374	/// [`NodeError::LastAdmin`] if the member is the only admin while others remain, who
375	/// makes another an admin first, and an error if the change cannot be saved.
376	pub fn leave(
377		&mut self,
378		space: SpaceId,
379		wall_millis: u64,
380		rng: &mut impl CryptoRng,
381	) -> Result<bool, NodeError> {
382		let closes = self.check_leave(space)?;
383		// The role none and keeping out go in one change, as this replica changes nothing
384		// there after either.
385		let key = self.replica.signing.verifying_key();
386		let mut operations = Vec::new();
387		let mut through = Vec::new();
388		if let Some(own) = self.user_member(space)? {
389			operations.push(self.role_operation(space, own, MemberRole::None, rng)?);
390			through = self.keys_through_groups(space, own)?;
391		}
392		// A member through a group keeps themselves out, by this replica's key too.
393		if !through.contains(&key) && self.is_listed_through_groups(space, &key)? {
394			through.push(key);
395		}
396		operations.extend(self.kept_out_operations(space, &through, true, rng)?);
397		self.commit(space, operations, wall_millis, rng)?;
398		Ok(closes)
399	}
400
401	/// Whether groups in a space list a key, at any level.
402	fn is_listed_through_groups(
403		&self,
404		space: SpaceId,
405		key: &nibkeep_crypto::VerifyingKey,
406	) -> Result<bool, NodeError> {
407		let open = self.space(space)?;
408		Ok(open
409			.stored
410			.log()
411			.listed_through_groups(&open.keys)?
412			.contains(key))
413	}
414
415	/// Checks that this replica's member may leave a shared space now, as before saying what
416	/// leaving would do, and returns whether leaving would close it, as its last member.
417	///
418	/// # Errors
419	///
420	/// Returns the errors of [`Library::leave`] but those of saving.
421	pub fn check_leave(&self, space: SpaceId) -> Result<bool, NodeError> {
422		self.check_shared(space)?;
423		self.check_not_revoked(space)?;
424		self.check_not_ai_agent("leave spaces")?;
425		let Some(own) = self.user_member(space)? else {
426			// A member through a group alone leaves the space and stays in the group.
427			let key = self.replica.signing.verifying_key();
428			if self.is_listed_through_groups(space, &key)? {
429				return Ok(false);
430			}
431			return Err(NodeError::NotListed);
432		};
433		let roles = {
434			let open = self.space(space)?;
435			open.stored.log().member_roles(&open.keys)?
436		};
437		let others: Vec<MemberRole> = roles
438			.iter()
439			.filter(|(member, role)| **member != own && **role != MemberRole::None)
440			.map(|(_, role)| *role)
441			.collect();
442		if roles.get(&own) == Some(&MemberRole::Admin)
443			&& !others.is_empty()
444			&& !others.contains(&MemberRole::Admin)
445		{
446			return Err(NodeError::LastAdmin);
447		}
448		Ok(others.is_empty())
449	}
450
451	/// Checks that this replica's member may remove `member` from a shared space now, as
452	/// before saying what removing would do; returns whether `member` is this replica's own,
453	/// whose removal is leaving, as [`Library::check_leave`] checks.
454	///
455	/// # Errors
456	///
457	/// Returns the errors of [`Library::remove_member`] but those of saving.
458	pub fn check_remove(&self, space: SpaceId, member: EntityId) -> Result<bool, NodeError> {
459		self.check_shared(space)?;
460		if self.member_in(space)? == Some(member) {
461			self.check_leave(space)?;
462			return Ok(true);
463		}
464		self.check_admin(space, "remove members")?;
465		let roles = {
466			let open = self.space(space)?;
467			open.stored.log().member_roles(&open.keys)?
468		};
469		if roles.get(&member) == Some(&MemberRole::Admin) {
470			self.check_settled_admin(space, "remove admins")?;
471		}
472		// The admin who removes stays: the space keeps an admin.
473		match roles.get(&member) {
474			None | Some(MemberRole::None) => Err(NodeError::NoMember(member.to_string())),
475			Some(_) => Ok(false),
476		}
477	}
478
479	/// Commits a member's role, replacing the statements of it now, in a change that
480	/// governs the space.
481	pub(crate) fn set_role(
482		&mut self,
483		space: SpaceId,
484		member: EntityId,
485		role: MemberRole,
486		wall_millis: u64,
487		rng: &mut impl CryptoRng,
488	) -> Result<(), NodeError> {
489		let operation = self.role_operation(space, member, role, rng)?;
490		self.commit(space, vec![operation], wall_millis, rng)
491	}
492
493	/// The operation that states a member's role, replacing the statements of it now.
494	pub(crate) fn role_operation(
495		&self,
496		space: SpaceId,
497		member: EntityId,
498		role: MemberRole,
499		rng: &mut impl CryptoRng,
500	) -> Result<Operation, NodeError> {
501		let current: Vec<StatementId> = self
502			.space(space)?
503			.stored
504			.log()
505			.state()
506			.current(member, &fields::ROLE)?
507			.iter()
508			.map(|statement| statement.id)
509			.collect();
510		Ok(Operation::replace(
511			Statement::new(
512				StatementId::random(rng),
513				member,
514				fields::ROLE,
515				Value::Text(role.as_text().to_owned()),
516			),
517			current,
518		))
519	}
520
521	/// Whether inviting someone to a space should suggest making them a second admin: a
522	/// shared space with a single admin does, and the personal space never.
523	///
524	/// # Errors
525	///
526	/// Returns an error if the space cannot be read.
527	pub fn suggests_second_admin(&self, space: SpaceId) -> Result<bool, NodeError> {
528		if space == self.info.personal || !self.has_members(space)? {
529			return Ok(false);
530		}
531		let open = self.space(space)?;
532		let roles = open.stored.log().member_roles(&open.keys)?;
533		Ok(roles
534			.values()
535			.filter(|role| **role == MemberRole::Admin)
536			.count()
537			== 1)
538	}
539
540	/// What this replica asks with when it joins a space by an invitation: its user, by ID
541	/// and name, its keys, and the names of its device and app.
542	pub(crate) fn invitation_request(&self) -> Result<InvitationRequest, NodeError> {
543		let (device, app) = self.own_names()?;
544		let user_name = self.own_name(self.info.user)?.unwrap_or_default();
545		for name in [&user_name, &device, &app] {
546			if name.len() > nibkeep_governance::MAX_NAME_LEN {
547				return Err(NodeError::LongName(nibkeep_governance::MAX_NAME_LEN));
548			}
549			if name.trim().is_empty() {
550				return Err(NodeError::EmptyName);
551			}
552		}
553		Ok(InvitationRequest {
554			user: self.info.user,
555			user_name,
556			signing: self.replica.signing.verifying_key(),
557			encryption: self.replica.decryption.encryption_key(),
558			device,
559			app,
560		})
561	}
562
563	/// Whether a space allows AI agents now: the personal space does, and a shared space where
564	/// its admins said so last ([technical design](../../../../docs/Technical-design.md#13-sharing)).
565	///
566	/// # Errors
567	///
568	/// Returns an error if the space cannot be read.
569	pub fn ai_agents_allowed(&self, space: SpaceId) -> Result<bool, NodeError> {
570		if space == self.info.personal || !self.has_members(space)? {
571			return Ok(true);
572		}
573		let open = self.space(space)?;
574		Ok(open.stored.log().allows_ai_agents(&open.keys)?)
575	}
576
577	/// Says, as an admin of a shared space, whether it allows AI agents: an AI agent's replica
578	/// is listed there only while it does, and what it writes counts only then. Stopping them
579	/// ends the AI agents' replicas listed there, as a removal does, and gives the space a new
580	/// key that they do not get; allowing them again brings those back.
581	///
582	/// # Errors
583	///
584	/// Returns [`NodeError::NeverShared`] for the personal space, [`NodeError::AdminsOnly`]
585	/// if this replica's member is no admin there, and an error if the change cannot be
586	/// saved.
587	pub fn allow_ai_agents(
588		&mut self,
589		space: SpaceId,
590		allow: bool,
591		wall_millis: u64,
592		rng: &mut impl CryptoRng,
593	) -> Result<(), NodeError> {
594		self.check_admin(space, "allow AI agents")?;
595		let allowed = self.ai_agents_allowed(space)?;
596		let open = self.space(space)?;
597		let entity = open
598			.own_entity()?
599			.ok_or_else(|| NodeError::Damaged(format!("the space {space} has no record")))?;
600		let current: Vec<StatementId> = open
601			.stored
602			.log()
603			.state()
604			.current(entity, &fields::AI_AGENTS)?
605			.iter()
606			.map(|statement| statement.id)
607			.collect();
608		let operation = Operation::replace(
609			Statement::new(
610				StatementId::random(rng),
611				entity,
612				fields::AI_AGENTS,
613				Value::Boolean(allow),
614			),
615			current,
616		);
617		self.commit(space, vec![operation], wall_millis, rng)?;
618		if allow || !allowed {
619			return Ok(());
620		}
621		// What is written next is sealed with a key that the AI agents it ended do not hold;
622		// if making it fails, the next sync makes one.
623		let roster = self.roster(space)?;
624		let open = self.space(space)?;
625		let mut ended = false;
626		for replica in roster.replicas() {
627			for key in roster.keys_of(replica) {
628				ended |= open.stored.log().is_ai_agent(key, &open.keys)?
629					&& open.stored.log().is_listed(key, &open.keys)?;
630			}
631		}
632		if ended {
633			let _ = self.rotate(space, &[], &roster, wall_millis, rng);
634		}
635		Ok(())
636	}
637
638	/// Checks, before an AI agent's replica is paired, that each of `spaces` can list it: a
639	/// shared space that this replica is listed in, which allows AI agents, or where this
640	/// replica's member is an admin, who allows them once the AI agent has joined.
641	pub(crate) fn check_ai_spaces(&self, spaces: &[SpaceId]) -> Result<(), NodeError> {
642		for &space in spaces {
643			self.check_shared(space)?;
644			self.check_not_revoked(space)?;
645			self.member_in(space)?.ok_or(NodeError::NotListed)?;
646			if self.ai_agents_allowed(space)? {
647				continue;
648			}
649			match self.check_admin(space, "allow AI agents") {
650				Ok(_) => {}
651				Err(NodeError::AdminsOnly(_)) => {
652					let name = self.space_name(space)?.unwrap_or_else(|| space.to_string());
653					return Err(NodeError::AiAgentsNotAllowed(name));
654				}
655				Err(error) => return Err(error),
656			}
657		}
658		Ok(())
659	}
660
661	/// The listings that this replica's key signs as it pairs: in the personal space, for the
662	/// record and the user that a grant names, as an AI agent's if the grant says so; then, as
663	/// an AI agent's, in the spaces that the grant chose for it, in their order.
664	pub(crate) fn pairing_listings(&self, grant: &nibkeep_governance::Grant) -> Vec<String> {
665		let encryption = self.replica.decryption.encryption_key();
666		let own = Listing::sign(
667			&self.replica.signing,
668			&encryption,
669			grant.space,
670			(grant.user, grant.ai_agent),
671		);
672		std::iter::once(own.to_text())
673			.chain(grant.chosen.iter().map(|&(space, member)| {
674				Listing::sign(&self.replica.signing, &encryption, space, (member, true)).to_text()
675			}))
676			.collect()
677	}
678
679	/// What listing an AI agent's replica that pairing added in the spaces chosen for it
680	/// takes, once the listings that its key signed check, before anything is committed: the
681	/// personal space's entries that give it each space's first key, and the operations that
682	/// list it in each space, owned by the user's member, marked as an AI agent's.
683	pub(crate) fn ai_agent_listings(
684		&self,
685		(request, endpoint, grant, name): (
686			&nibkeep_governance::JoinRequest,
687			&[u8; 32],
688			&nibkeep_governance::Grant,
689			&str,
690		),
691		listings: &[String],
692		rng: &mut impl CryptoRng,
693	) -> Result<AiAgentListings, NodeError> {
694		let chosen: Vec<SpaceId> = grant.chosen.iter().map(|(space, _)| *space).collect();
695		self.check_ai_spaces(&chosen)?;
696		let encryption = encryption_hash(&request.encryption.to_bytes());
697		let mut prepared = AiAgentListings::default();
698		for (&(space, member), text) in grant.chosen.iter().zip(listings) {
699			let listing = Listing::from_text(text)
700				.filter(|listing| {
701					listing.space == space
702						&& listing.owner == member
703						&& listing.ai_agent
704						&& listing.key == request.signing
705						&& listing.encryption == encryption
706						&& listing.verifies()
707				})
708				.ok_or_else(|| {
709					NodeError::Damaged("the AI agent's listing is not the one asked for".to_owned())
710				})?;
711			let open = self.space(space)?;
712			let first = open
713				.keys
714				.space_keys()
715				.find(|(epoch, _)| *epoch == 0)
716				.map(|(_, key)| key.clone())
717				.ok_or(NodeError::NoSpace(space))?;
718			let root = open.stored.log().root()?.ok_or(NodeError::NoSpace(space))?;
719			prepared.entries.push(nibkeep_governance::give_space_entry(
720				grant.replica,
721				&SpaceEntry::seal(
722					&request.encryption,
723					(space, member, *root.hash()),
724					grant.replica,
725					(&first, key_hash(&first)),
726					rng,
727				),
728				rng,
729			));
730			let listed = nibkeep_governance::list_replica(
731				&SpaceReplica {
732					record: listing.record,
733					device_record: nibkeep_governance::device_record(space, &listing.key),
734					member,
735					signing: &listing.key,
736					encryption: &request.encryption,
737					listing: text,
738					endpoint: Some(endpoint),
739					device: &request.device,
740					app: name,
741					ai_agent: true,
742				},
743				rng,
744			);
745			let mut operations = listed.governing;
746			operations.extend(listed.operations);
747			prepared.spaces.push((space, operations));
748		}
749		Ok(prepared)
750	}
751
752	/// Lists an AI agent's replica in the spaces chosen for it, as
753	/// [`Library::ai_agent_listings`] prepared: allows AI agents first where a space does not
754	/// yet, as an admin there, then lists it, and gives it the space's keys.
755	pub(crate) fn list_ai_agent(
756		&mut self,
757		spaces: Vec<(SpaceId, Vec<Operation>)>,
758		wall_millis: u64,
759		rng: &mut impl CryptoRng,
760	) -> Result<(), NodeError> {
761		for (space, operations) in spaces {
762			if !self.ai_agents_allowed(space)? {
763				self.allow_ai_agents(space, true, wall_millis, rng)?;
764			}
765			self.commit(space, operations, wall_millis, rng)?;
766			self.give_keys(space, wall_millis, rng)?;
767		}
768		Ok(())
769	}
770
771	/// Checks that a shared space holds a person to name a member by: an entity there, not
772	/// deleted.
773	pub(crate) fn check_person(&self, space: SpaceId, person: EntityId) -> Result<(), NodeError> {
774		let state = self.space(space)?.stored.log().state();
775		if !state.types(person)?.contains(&nibkeep_governance::PERSON)
776			|| state.is_deleted(person)?
777		{
778			return Err(NodeError::NoEntity(person.to_string()));
779		}
780		Ok(())
781	}
782
783	/// The person in a shared space that `reference` names, as [`Library::find_entity`]
784	/// finds entities, but of the type `std.person` alone: so that neither a member's
785	/// record, which has the user's name, nor another entity is taken for a person.
786	///
787	/// # Errors
788	///
789	/// Returns [`NodeError::NoEntity`] if no person matches, [`NodeError::Ambiguous`] if
790	/// several do, and an error if the space cannot be read.
791	pub fn find_person(&self, space: SpaceId, reference: &str) -> Result<EntityId, NodeError> {
792		let is_person = |entity: EntityId| -> Result<bool, NodeError> {
793			let state = self.space(space)?.stored.log().state();
794			Ok(state.types(entity)?.contains(&nibkeep_governance::PERSON)
795				&& !state.is_deleted(entity)?)
796		};
797		let candidates = match self.find_entity(space, reference) {
798			Ok(entity) => vec![entity],
799			Err(NodeError::Ambiguous { candidates, .. }) => candidates,
800			Err(error) => return Err(error),
801		};
802		let mut persons = Vec::new();
803		for candidate in candidates {
804			if is_person(candidate)? {
805				persons.push(candidate);
806			}
807		}
808		match persons.as_slice() {
809			[] => Err(NodeError::NoEntity(reference.to_owned())),
810			[person] => Ok(*person),
811			_ => Err(NodeError::Ambiguous {
812				reference: reference.to_owned(),
813				candidates: persons,
814			}),
815		}
816	}
817
818	/// Checks that a space is a shared one, with members.
819	pub(super) fn check_shared(&self, space: SpaceId) -> Result<(), NodeError> {
820		if space == self.info.personal || !self.has_members(space)? {
821			return Err(NodeError::NeverShared);
822		}
823		Ok(())
824	}
825
826	/// Checks that this replica's member is an admin of a shared space now, as before
827	/// showing a code that could not be used, and returns the member.
828	///
829	/// # Errors
830	///
831	/// Returns [`NodeError::NeverShared`] for the personal space, [`NodeError::Revoked`] if
832	/// this replica is revoked there, [`NodeError::AiAgentMayNot`] for an AI agent's replica,
833	/// [`NodeError::AdminsOnly`] if its member is no admin, and an error if the space cannot
834	/// be read.
835	pub fn check_admin(&self, space: SpaceId, what: &'static str) -> Result<EntityId, NodeError> {
836		self.check_shared(space)?;
837		self.check_not_revoked(space)?;
838		if self.is_ai_agent()? {
839			return Err(NodeError::AiAgentMayNot(what));
840		}
841		let member = self.member_in(space)?.ok_or(NodeError::AdminsOnly(what))?;
842		let open = self.space(space)?;
843		let roles = open.stored.log().member_roles(&open.keys)?;
844		// A claim that took effect makes its claimant an admin too.
845		if roles.get(&member) != Some(&MemberRole::Admin)
846			&& self.claim_now(space, member)?.is_none()
847		{
848			return Err(NodeError::AdminsOnly(what));
849		}
850		Ok(member)
851	}
852
853	/// Checks, as [`Library::check_admin`] does, that this replica's member is an admin of a
854	/// shared space now, other than one whose claim to the role took effect less than 30 days
855	/// ago, who can only undo: no purge, acceptance, rejection of claims, new admin, or
856	/// lowering an admin.
857	///
858	/// # Errors
859	///
860	/// The errors of [`Library::check_admin`].
861	pub(crate) fn check_settled_admin(
862		&self,
863		space: SpaceId,
864		what: &'static str,
865	) -> Result<EntityId, NodeError> {
866		let member = self.check_admin(space, what)?;
867		if self.claim_now(space, member)? == Some(super::claims::ClaimNow::Undoing) {
868			let open = self.space(space)?;
869			let roles = open.stored.log().member_roles(&open.keys)?;
870			if roles.get(&member) != Some(&MemberRole::Admin) {
871				return Err(NodeError::AdminsOnly(what));
872			}
873		}
874		Ok(member)
875	}
876
877	/// The member that a key's counting listing in a shared space names, if one lists it.
878	fn listed_member(
879		&self,
880		space: SpaceId,
881		key: &VerifyingKey,
882	) -> Result<Option<EntityId>, NodeError> {
883		Ok(self.users_and_owners(space)?.1.get(key.as_bytes()).copied())
884	}
885
886	/// What the counting governing changes of a shared space say of who is who, as
887	/// [`users_and_owners`] says.
888	pub(crate) fn users_and_owners(&self, space: SpaceId) -> Result<UsersAndOwners, NodeError> {
889		let open = self.space(space)?;
890		users_and_owners(&open.stored, &open.keys)
891	}
892
893	/// Links a member of a shared space to a person in it, or, without one, unlinks them: as
894	/// the member, for themselves, or as an admin, for another member. The link holds once an
895	/// admin's statement and the member's own agree; an admin's own statement counts for both
896	/// while they are an admin.
897	///
898	/// # Errors
899	///
900	/// Returns [`NodeError::NeverShared`] for the personal space, [`NodeError::NotListed`]
901	/// if this replica is no member's there, [`NodeError::AdminsOnly`] for another member if
902	/// this replica's member is no admin, [`NodeError::NoMember`] if the space has no such
903	/// member, [`NodeError::NoEntity`] if it holds no such person, and an error if the change
904	/// cannot be saved.
905	pub fn link_member(
906		&mut self,
907		space: SpaceId,
908		member: EntityId,
909		person: Option<EntityId>,
910		wall_millis: u64,
911		rng: &mut impl CryptoRng,
912	) -> Result<(), NodeError> {
913		self.check_shared(space)?;
914		self.check_not_revoked(space)?;
915		let own = self.member_in(space)?.ok_or(NodeError::NotListed)?;
916		if member != own {
917			self.check_admin(space, "link another member to a person")?;
918		}
919		let open = self.space(space)?;
920		let log = open.stored.log();
921		let roles = log.member_roles(&open.keys)?;
922		if roles
923			.get(&member)
924			.is_none_or(|role| *role == MemberRole::None)
925		{
926			return Err(NodeError::NoMember(member.to_string()));
927		}
928		if let Some(person) = person {
929			self.check_person(space, person)?;
930		}
931		let open = self.space(space)?;
932		// Each side replaces only its own statements, so that the other's stays to agree with.
933		let (_, owners) = users_and_owners(&open.stored, &open.keys)?;
934		let by_member = member == own;
935		let ours: Vec<StatementId> =
936			link_statements((&open.stored, open.stored.log().state()), &owners, member)?
937				.into_iter()
938				.filter(|stated| stated.by_member == by_member)
939				.map(|stated| stated.id)
940				.collect();
941		let operation = match person {
942			Some(person) => Operation::replace(
943				Statement::new(
944					StatementId::random(rng),
945					member,
946					nibkeep_governance::LINKED_PERSON,
947					Value::Reference(person),
948				),
949				ours,
950			),
951			None if ours.is_empty() => return Ok(()),
952			None => Operation::retract(member, ours),
953		};
954		self.commit(space, vec![operation], wall_millis, rng)
955	}
956
957	/// The replicas of other members of the shared spaces that this replica is listed in,
958	/// which it syncs those spaces with: listed there, not revoked, and with an endpoint on
959	/// their records, each once, with the first such space.
960	pub(crate) fn other_members_replicas(&self) -> Vec<super::sync::Replica> {
961		let own = self.replica.signing.verifying_key();
962		let mut found: BTreeMap<[u8; 32], super::sync::Replica> = BTreeMap::new();
963		for space in self.spaces() {
964			// A space that cannot be read keeps nobody from syncing the others.
965			if space == self.info.personal
966				|| !self.has_members(space).unwrap_or(false)
967				|| self.check_not_revoked(space).is_err()
968			{
969				continue;
970			}
971			let Ok(members) = self.members(space) else {
972				continue;
973			};
974			let member = self.member_in(space).ok().flatten();
975			// The members of the groups in it too, at every level, whose logs it holds.
976			let mut others = members;
977			for group in self.inner_groups(space).unwrap_or_default() {
978				if self.spaces.contains_key(&group)
979					&& let Ok(members) = self.members(group)
980				{
981					others.extend(members);
982				}
983			}
984			for other in others {
985				if Some(other.record) == member {
986					continue;
987				}
988				for replica in other.replicas {
989					if replica.revoked
990						|| replica.signing == own
991						|| replica.endpoint.is_none()
992						|| found.contains_key(replica.signing.as_bytes())
993					{
994						continue;
995					}
996					found.insert(
997						*replica.signing.as_bytes(),
998						super::sync::Replica::of_member((space, other.name.as_deref()), &replica),
999					);
1000				}
1001			}
1002		}
1003		found.into_values().collect()
1004	}
1005}
1006
1007/// What listing an AI agent's replica in the spaces chosen for it takes: the personal
1008/// space's entries, and the operations of each space.
1009#[derive(Default)]
1010pub(crate) struct AiAgentListings {
1011	pub(crate) entries: Vec<Operation>,
1012	pub(crate) spaces: Vec<(SpaceId, Vec<Operation>)>,
1013}
1014
1015/// Each member record's user ID, and each listed key's owner.
1016type UsersAndOwners = (BTreeMap<EntityId, EntityId>, BTreeMap<[u8; 32], EntityId>);
1017
1018/// What the counting governing changes of a shared space say of who is who: each member
1019/// record's user ID, the first stated, and each listed key's owner, by the listings that its
1020/// key signed.
1021pub(crate) fn users_and_owners(
1022	stored: &nibkeep_store::StoredLog,
1023	keys: &nibkeep_log::SpaceKeys,
1024) -> Result<UsersAndOwners, NodeError> {
1025	let mut users = BTreeMap::new();
1026	let mut owners = BTreeMap::new();
1027	for governing in stored.log().governing_statements(keys)? {
1028		let entity = governing.statement.entity;
1029		if let Some(text) = governing.counting_text(&fields::USER_ID) {
1030			if let Ok(user) = text.parse::<EntityId>() {
1031				users.entry(entity).or_insert(user);
1032			}
1033		} else if let Some(listing) = governing
1034			.counting_text(&fields::LISTING)
1035			.and_then(Listing::from_text)
1036			&& listing.record == entity
1037			&& listing.verifies()
1038		{
1039			owners.insert(*listing.key.as_bytes(), listing.owner);
1040		}
1041	}
1042	Ok((users, owners))
1043}
1044
1045/// A current statement of a member's link to a person: the person, when it was recorded,
1046/// and whether one of the member's own replicas signed it, or else an admin's, as only those
1047/// count on a member's record.
1048struct LinkStated {
1049	id: StatementId,
1050	person: EntityId,
1051	at: nibkeep_time::Timestamp,
1052	by_member: bool,
1053}
1054
1055/// The statements of a member's link to a person that `state` holds now, with who signed
1056/// each, as the log has their changes.
1057fn link_statements<S: Statements>(
1058	(stored, state): (&nibkeep_store::StoredLog, &nibkeep_model::State<S>),
1059	owners: &BTreeMap<[u8; 32], EntityId>,
1060	member: EntityId,
1061) -> Result<Vec<LinkStated>, NodeError>
1062where
1063	NodeError: From<S::Error>,
1064{
1065	let log = stored.log();
1066	let mut stated = Vec::new();
1067	for statement in state.current(member, &nibkeep_governance::LINKED_PERSON)? {
1068		let Some(person) = statement.value.as_reference() else {
1069			continue;
1070		};
1071		let Some(recorded) = state.storage().get(statement.id)? else {
1072			continue;
1073		};
1074		let Some(change) = recorded.change else {
1075			continue;
1076		};
1077		let Some(change) = log.change(nibkeep_log::ChangeId::from_hash(change))? else {
1078			continue;
1079		};
1080		stated.push(LinkStated {
1081			id: statement.id,
1082			person,
1083			at: recorded.at,
1084			by_member: owners.get(change.author().as_bytes()) == Some(&member),
1085		});
1086	}
1087	Ok(stated)
1088}
1089
1090/// A member's link to a person in a shared space, as `state` has it, with each listed key's
1091/// owner and each member's role now.
1092pub(crate) fn person_link<S: Statements>(
1093	(stored, state): (&nibkeep_store::StoredLog, &nibkeep_model::State<S>),
1094	(owners, roles): (
1095		&BTreeMap<[u8; 32], EntityId>,
1096		&BTreeMap<EntityId, MemberRole>,
1097	),
1098	member: EntityId,
1099) -> Result<PersonLink, NodeError>
1100where
1101	NodeError: From<S::Error>,
1102{
1103	let stated = link_statements((stored, state), owners, member)?;
1104	let latest = |by_member: bool| {
1105		stated
1106			.iter()
1107			.filter(|stated| stated.by_member == by_member)
1108			.max_by_key(|stated| (stated.at, stated.id))
1109			.map(|stated| stated.person)
1110	};
1111	let (by_member, by_admin) = (latest(true), latest(false));
1112	let is_admin = roles.get(&member) == Some(&MemberRole::Admin);
1113	let agreed = by_member.filter(|person| is_admin || by_admin == Some(*person));
1114	let deleted = match agreed {
1115		Some(person) => state.is_deleted(person)?,
1116		None => false,
1117	};
1118	Ok(PersonLink {
1119		holds: agreed.filter(|_| !deleted),
1120		by_admin,
1121		by_member,
1122		deleted,
1123	})
1124}
1125
1126/// What an admin's replica asks and offers as it invites someone to a space.
1127pub(crate) struct Inviter<'a> {
1128	library: &'a mut Library,
1129	space: SpaceId,
1130	role: MemberRole,
1131	person: Option<EntityId>,
1132	confirm: &'a mut dyn FnMut(&Invitee) -> bool,
1133	now: &'a dyn Fn() -> u64,
1134	/// Who asked, from where, and what was offered.
1135	asked: Option<(InvitationRequest, [u8; 32], Offer)>,
1136	/// The joiner's listing, once it checked.
1137	listing: Option<(Listing, String)>,
1138	/// Whether the code matched: the joiner's request came with the tag of the code's key.
1139	matched: bool,
1140}
1141
1142impl<'a> Inviter<'a> {
1143	pub(crate) fn new(
1144		library: &'a mut Library,
1145		invitation: &crate::Invitation,
1146		confirm: &'a mut dyn FnMut(&Invitee) -> bool,
1147		now: &'a dyn Fn() -> u64,
1148	) -> Self {
1149		Self {
1150			library,
1151			space: invitation.space,
1152			role: invitation.role,
1153			person: invitation.person,
1154			confirm,
1155			now,
1156			asked: None,
1157			listing: None,
1158			matched: false,
1159		}
1160	}
1161
1162	/// Whether the code matched: the person was asked about the joiner, or would have been,
1163	/// had reading the members not failed. An invitation that failed before then leaves the
1164	/// code for another try.
1165	pub(crate) const fn matched(&self) -> bool {
1166		self.matched
1167	}
1168}
1169
1170impl Inviting for Inviter<'_> {
1171	type Error = NodeError;
1172
1173	fn offer<R: CryptoRng>(
1174		&mut self,
1175		request: &InvitationRequest,
1176		endpoint: &[u8; 32],
1177		rng: &mut R,
1178	) -> Result<Option<Offer>, NodeError> {
1179		// An invitation asks for an offer only once the code matched.
1180		self.matched = true;
1181		let members = self.library.members(self.space)?;
1182		let of_user = |member: &&SpaceMember| member.user == Some(request.user);
1183		let invitee = Invitee {
1184			user: request.user,
1185			user_name: request.user_name.clone(),
1186			device: request.device.clone(),
1187			app: request.app.clone(),
1188			same_user: members
1189				.iter()
1190				.filter(of_user)
1191				.filter(|member| member.role != MemberRole::None)
1192				.cloned()
1193				.collect(),
1194			was_member: members
1195				.iter()
1196				.filter(of_user)
1197				.any(|member| member.role == MemberRole::None),
1198		};
1199		if !(self.confirm)(&invitee) {
1200			return Ok(None);
1201		}
1202		// A device invited before, whose first sync failed, is still listed, for the member
1203		// that invitation made: it comes back as that member. One whose member left or was
1204		// removed comes back as a new member, as anyone who comes back does.
1205		let listed = self.library.listed_member(self.space, &request.signing)?;
1206		let of_listed =
1207			listed.and_then(|listed| members.iter().find(|member| member.record == listed));
1208		let member = match of_listed {
1209			Some(listed) if listed.role == MemberRole::None => EntityId::random(rng),
1210			Some(listed) if listed.user == Some(request.user) => listed.record,
1211			Some(_) => {
1212				return Err(NodeError::Damaged(
1213					"the device that asks is listed in the space for another user".to_owned(),
1214				));
1215			}
1216			None if listed.is_some() => {
1217				return Err(NodeError::Damaged(
1218					"the device that asks is listed in the space for no member".to_owned(),
1219				));
1220			}
1221			None => EntityId::random(rng),
1222		};
1223		let name = self
1224			.library
1225			.space_name(self.space)?
1226			.unwrap_or_else(|| self.space.to_string());
1227		let person = match self.person {
1228			Some(person) => {
1229				let name = self
1230					.library
1231					.name(self.space, person)?
1232					.unwrap_or_else(|| person.to_string());
1233				Some((person, truncated(&name, nibkeep_governance::MAX_NAME_LEN)))
1234			}
1235			None => None,
1236		};
1237		let offer = Offer {
1238			space: self.space,
1239			space_name: truncated(&name, nibkeep_governance::MAX_NAME_LEN),
1240			member,
1241			role: self.role.as_text().to_owned(),
1242			person,
1243		};
1244		self.asked = Some((request.clone(), *endpoint, offer.clone()));
1245		Ok(Some(offer))
1246	}
1247
1248	fn grant<R: CryptoRng>(
1249		&mut self,
1250		text: &str,
1251		rng: &mut R,
1252	) -> Result<InvitationGrant, NodeError> {
1253		let (request, _, offer) = self
1254			.asked
1255			.as_ref()
1256			.ok_or_else(|| NodeError::Damaged("a listing came before the offer".to_owned()))?;
1257		let space = self.space;
1258		let listing = Listing::from_text(text)
1259			.filter(|listing| {
1260				listing.space == space
1261					&& listing.owner == offer.member
1262					&& !listing.ai_agent
1263					&& listing.key == request.signing
1264					&& listing.encryption == encryption_hash(&request.encryption.to_bytes())
1265					&& listing.verifies()
1266			})
1267			.ok_or_else(|| {
1268				NodeError::Damaged("the joiner's listing is not the one offered".to_owned())
1269			})?;
1270		let open = self.library.space(space)?;
1271		let log = open.stored.log();
1272		// A key that the space revoked is never listed anew.
1273		if log.is_revoked(&listing.key, &open.keys)? {
1274			return Err(NodeError::Damaged(
1275				"the joiner's key is revoked in the space".to_owned(),
1276			));
1277		}
1278		let first = open
1279			.keys
1280			.space_keys()
1281			.find(|(epoch, _)| *epoch == 0)
1282			.map(|(_, key)| key.clone())
1283			.ok_or(NodeError::NoSpace(space))?;
1284		let root = log.root()?.ok_or(NodeError::NoSpace(space))?;
1285		let entry = SpaceEntry::seal(
1286			&request.encryption,
1287			(space, offer.member, *root.hash()),
1288			listing.record,
1289			(&first, key_hash(&first)),
1290			rng,
1291		);
1292		self.listing = Some((listing, text.to_owned()));
1293		Ok(InvitationGrant {
1294			entry,
1295			admin: self.library.replica.signing.verifying_key(),
1296		})
1297	}
1298
1299	fn record<R: CryptoRng>(&mut self, rng: &mut R) -> Result<(), NodeError> {
1300		let (Some((request, endpoint, offer)), Some((listing, text))) =
1301			(&self.asked, &self.listing)
1302		else {
1303			return Err(NodeError::Damaged(
1304				"the joiner joined before it was granted the space".to_owned(),
1305			));
1306		};
1307		// A device invited before is listed already, for this member: it gets the role anew.
1308		if self.library.listed_member(self.space, &listing.key)? == Some(offer.member) {
1309			let wall_millis = (self.now)();
1310			let roles = {
1311				let open = self.library.space(self.space)?;
1312				open.stored.log().member_roles(&open.keys)?
1313			};
1314			if roles.get(&offer.member) != Some(&self.role) {
1315				self.library
1316					.set_role(self.space, offer.member, self.role, wall_millis, rng)?;
1317			}
1318			let _ = self.library.give_keys(self.space, wall_millis, rng);
1319			// The joiner holds the space now: a person deleted meanwhile keeps nobody out.
1320			if let Some(person) = self.person {
1321				let _ = self.library.link_member(
1322					self.space,
1323					offer.member,
1324					Some(person),
1325					wall_millis,
1326					rng,
1327				);
1328			}
1329			return Ok(());
1330		}
1331		let added = add_member(
1332			&NewMember {
1333				user: request.user,
1334				user_name: &request.user_name,
1335				member: offer.member,
1336				role: self.role.as_text(),
1337				replica: SpaceReplica {
1338					record: listing.record,
1339					device_record: nibkeep_governance::device_record(self.space, &listing.key),
1340					member: offer.member,
1341					signing: &listing.key,
1342					encryption: &request.encryption,
1343					listing: text,
1344					endpoint: Some(endpoint),
1345					device: &request.device,
1346					app: &request.app,
1347					ai_agent: false,
1348				},
1349			},
1350			rng,
1351		);
1352		let mut operations = added.governing;
1353		operations.extend(added.operations);
1354		// The admin's side of the member's link to the person named, which the member's own
1355		// statement completes.
1356		if let Some(person) = self.person {
1357			operations.push(Operation::assert(Statement::new(
1358				StatementId::random(rng),
1359				offer.member,
1360				nibkeep_governance::LINKED_PERSON,
1361				Value::Reference(person),
1362			)));
1363		}
1364		let wall_millis = (self.now)();
1365		self.library
1366			.commit(self.space, operations, wall_millis, rng)?;
1367		// The space's later keys reach the new replica through the records; if giving them
1368		// fails, the next sync gives them.
1369		let _ = self.library.give_keys(self.space, wall_millis, rng);
1370		Ok(())
1371	}
1372}
1373
1374/// The longest start of `text` that is at most `max` bytes long, cut between characters.
1375fn truncated(text: &str, max: usize) -> String {
1376	let mut end = text.len().min(max);
1377	while !text.is_char_boundary(end) {
1378		end -= 1;
1379	}
1380	text[..end].to_owned()
1381}
1382
1383/// What a joiner's replica signs and takes as it joins a space by an invitation.
1384pub(crate) struct Acceptor<'a> {
1385	library: &'a mut Library,
1386	/// The space it holds already, if the offer named one.
1387	pub(crate) held: Option<SpaceId>,
1388	/// The space it took.
1389	pub(crate) taken: Option<SpaceId>,
1390	/// The space it holds already, which its member left or was removed from, that it comes
1391	/// back to as a new member.
1392	pub(crate) back: Option<SpaceId>,
1393	/// Whether the code matched: the admin's offer came with the tag of the code's key.
1394	pub(crate) matched: bool,
1395}
1396
1397impl<'a> Acceptor<'a> {
1398	pub(crate) const fn new(library: &'a mut Library) -> Self {
1399		Self {
1400			library,
1401			held: None,
1402			taken: None,
1403			back: None,
1404			matched: false,
1405		}
1406	}
1407}
1408
1409impl Accepting for Acceptor<'_> {
1410	type Error = NodeError;
1411
1412	fn listing(&mut self, offer: &Offer) -> Result<Option<String>, NodeError> {
1413		// An invitation asks for the listing only once the code matched.
1414		self.matched = true;
1415		if MemberRole::from_text(&offer.role).is_none_or(|role| role == MemberRole::None) {
1416			return Err(NodeError::Damaged(format!(
1417				"the invitation offers a role that is none: {}",
1418				offer.role
1419			)));
1420		}
1421		if self.library.spaces.contains_key(&offer.space) {
1422			// A replica whose member left or was removed comes back as a new member, keeping
1423			// what it holds.
1424			if !self.library.has_left(offer.space)? {
1425				self.held = Some(offer.space);
1426				return Ok(None);
1427			}
1428			// An admin's device that has not learned of the leaving yet offers the member who
1429			// left, which would leave this replica removed.
1430			if self.library.member_in(offer.space)? == Some(offer.member) {
1431				return Err(NodeError::InviterBehind);
1432			}
1433			self.back = Some(offer.space);
1434		}
1435		Ok(Some(
1436			Listing::sign(
1437				&self.library.replica.signing,
1438				&self.library.replica.decryption.encryption_key(),
1439				offer.space,
1440				(offer.member, false),
1441			)
1442			.to_text(),
1443		))
1444	}
1445
1446	fn take<R: CryptoRng>(
1447		&mut self,
1448		offer: &Offer,
1449		grant: &InvitationGrant,
1450		rng: &mut R,
1451	) -> Result<(), NodeError> {
1452		let entry = &grant.entry;
1453		if entry.space != offer.space || entry.member != offer.member {
1454			return Err(NodeError::Damaged(
1455				"the grant is of another space than the offer".to_owned(),
1456			));
1457		}
1458		let record = replica_record(offer.space, &self.library.replica.signing.verifying_key());
1459		let key = entry
1460			.open(&self.library.replica.decryption, record)
1461			.filter(|key| key_hash(key) == entry.hash)
1462			.ok_or_else(|| NodeError::Damaged("the space's first key does not open".to_owned()))?;
1463		if self.back == Some(offer.space) {
1464			// It holds the space and its first key already.
1465			return Ok(());
1466		}
1467		self.library.add_space(offer.space, &key, rng)?;
1468		self.taken = Some(offer.space);
1469		if let Some(open) = self.library.spaces.get_mut(&offer.space) {
1470			open.stored
1471				.expect_roots([nibkeep_log::ChangeId::from_hash(entry.root)]);
1472		}
1473		Ok(())
1474	}
1475}