weirdnet-collab 0.1.1

Collaboration control for Weirdnet apps: project members and roles, signed allow and deny rules, owner consent grants, a decision with a reason chain, invites and a signed, mergeable audit log. App-agnostic: the app defines what a project, role and permission are.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! A project: members, roles, rules, consent, invites and the audit log, and the decision.
use crate::audit::{AuditDeletion, AuditEntry, AuditKind, AuditLog};
use crate::decision::{Decision, Explained, Step};
use crate::ids::{Permission, ProjectId, RecordId, RoleId, StreamId};
use crate::invite::{Approval, Invite, InviteError, InviteSpec, InviteState, JoinRequest, Redeemed};
use crate::records::{ConsentGrant, Duration, Effect, GrantStreams, Revocation, Rule, SignError, Subject};
use crate::roles::{Gate, RoleTable};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use weirdnet_contacts::UserId;
use weirdnet_net::Keypair;

/// The permission that manages members, roles, rules, bans and invites.
pub const MANAGE: &str = "session.manage";
/// The permission to create invites and links.
pub const INVITE: &str = "session.invite";

/// A member.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Member {
    /// Who.
    pub user: UserId,
    /// Their role.
    pub role: RoleId,
    /// When they joined.
    pub joined_ms: i64,
    /// The invite they came through (revoking it can end their session).
    pub via: Option<RecordId>,
}

/// What a caller asks about besides who and what.
#[derive(Clone, Debug, Default)]
pub struct Ctx {
    /// The time of the decision, milliseconds since the epoch.
    pub now_ms: i64,
    /// For a gated permission: whose audio it concerns.
    pub stream_owner: Option<UserId>,
    /// For a gated permission: which stream.
    pub stream: Option<StreamId>,
}

impl Ctx {
    /// A context at `now_ms`.
    pub fn at(now_ms: i64) -> Self {
        Ctx { now_ms, ..Default::default() }
    }

    /// Concerning `owner`'s audio (and one stream, if given).
    pub fn audio(mut self, owner: &UserId, stream: Option<&str>) -> Self {
        self.stream_owner = Some(owner.clone());
        self.stream = stream.map(StreamId::new);
        self
    }
}

/// Why an action was refused.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum Error {
    /// The actor may not do this; the explanation says why.
    #[error("not allowed")]
    NotAllowed(Box<Explained>),
    /// No such role in the table.
    #[error("unknown role")]
    UnknownRole,
    /// The identity is not a member.
    #[error("not a member")]
    NotMember,
    /// The project's owner cannot be removed, banned or demoted.
    #[error("that is the project's owner")]
    IsHost,
    /// A record's signature does not hold or its signer is not who it names.
    #[error("bad signature")]
    BadSignature,
    /// A record is for another project.
    #[error("wrong project")]
    WrongProject,
    /// The record already exists.
    #[error("already there")]
    Duplicate,
    /// No such record.
    #[error("no such record")]
    NoSuchRecord,
    /// Only the audio's owner can do this.
    #[error("only the owner can do this")]
    NotOwner,
    /// The permission has no owner-consent gate.
    #[error("that permission needs no consent")]
    NotGated,
    /// An invite was refused.
    #[error(transparent)]
    Invite(#[from] InviteError),
    /// The key could not sign.
    #[error(transparent)]
    Sign(#[from] SignErr),
}

/// A signing failure.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("cannot sign: {0}")]
pub struct SignErr(pub String);

impl From<SignError> for Error {
    fn from(e: SignError) -> Self {
        Error::Sign(SignErr(e.0))
    }
}

/// A project.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Project {
    id: ProjectId,
    host: UserId,
    roles: RoleTable,
    members: BTreeMap<UserId, Member>,
    bans: BTreeSet<UserId>,
    rules: Vec<Rule>,
    consents: Vec<ConsentGrant>,
    revocations: BTreeMap<RecordId, Revocation>,
    spent: BTreeMap<RecordId, i64>,
    invites: BTreeMap<RecordId, InviteState>,
    pending: Vec<JoinRequest>,
    audit: AuditLog,
    open: bool,
    seq: u64,
}

impl Project {
    /// A new project owned by `host`, who joins in the table's host role.
    pub fn new(id: &str, host: &Keypair, roles: RoleTable, now: i64) -> Result<Project, Error> {
        let role = roles.host_role().cloned().ok_or(Error::UnknownRole)?;
        let host_id = UserId::of_keypair(host);
        let mut members = BTreeMap::new();
        members.insert(host_id.clone(), Member { user: host_id.clone(), role, joined_ms: now, via: None });
        Ok(Project {
            id: ProjectId::new(id),
            host: host_id,
            roles,
            members,
            bans: BTreeSet::new(),
            rules: Vec::new(),
            consents: Vec::new(),
            revocations: BTreeMap::new(),
            spent: BTreeMap::new(),
            invites: BTreeMap::new(),
            pending: Vec::new(),
            audit: AuditLog::default(),
            open: true,
            seq: 0,
        })
    }

    /// The project id.
    pub fn id(&self) -> &ProjectId {
        &self.id
    }

    /// The owner.
    pub fn host(&self) -> &UserId {
        &self.host
    }

    /// The role table.
    pub fn roles(&self) -> &RoleTable {
        &self.roles
    }

    /// The members.
    pub fn members(&self) -> impl Iterator<Item = &Member> {
        self.members.values()
    }

    /// One member.
    pub fn member(&self, user: &UserId) -> Option<&Member> {
        self.members.get(user)
    }

    /// Whether the session is open.
    pub fn is_open(&self) -> bool {
        self.open
    }

    /// Whether `user` is banned from the project.
    pub fn is_banned(&self, user: &UserId) -> bool {
        self.bans.contains(user)
    }

    /// The rules, in the order they were added.
    pub fn rules(&self) -> &[Rule] {
        &self.rules
    }

    /// The invites and their use.
    pub fn invites(&self) -> impl Iterator<Item = &InviteState> {
        self.invites.values()
    }

    /// People waiting for the host.
    pub fn pending(&self) -> &[JoinRequest] {
        &self.pending
    }

    /// Consent grants that are live for `owner` (not revoked, not spent).
    pub fn consents_of<'a>(&'a self, owner: &'a UserId) -> impl Iterator<Item = &'a ConsentGrant> {
        self.consents.iter().filter(move |g| &g.owner == owner && self.consent_live(g))
    }

    /// The audit log.
    pub fn audit(&self) -> &AuditLog {
        &self.audit
    }

    /// What `user` sees of the audit log (a host sees all).
    pub fn audit_for(&self, user: &UserId) -> Vec<&AuditEntry> {
        self.audit.visible_to(user, self.is_host_like(user))
    }

    fn is_host_like(&self, user: &UserId) -> bool {
        self.members.get(user).is_some_and(|m| self.roles.spec(&m.role).is_some_and(|s| s.all)) && !self.bans.contains(user)
    }

    fn next_id(&mut self, who: &UserId, now: i64) -> RecordId {
        self.seq += 1;
        RecordId::new(format!("{}-{}-{}", who.short(), now, self.seq))
    }

    /// An invite id: `i` and 32 hex digits, 128 bits from the OS random source. An invite id
    /// travels in links, so it must not be guessable from the creator, the time or a counter.
    /// Panics only if the OS random source fails, which Linux and Android do not do once booted.
    fn invite_id() -> RecordId {
        let mut b = [0u8; 16];
        getrandom::fill(&mut b).expect("the OS random source failed");
        let mut s = String::with_capacity(33);
        s.push('i');
        for x in b {
            s.push_str(&format!("{x:02x}"));
        }
        RecordId::new(s)
    }

    fn consent_live(&self, g: &ConsentGrant) -> bool {
        !self.revocations.contains_key(&g.id) && !(g.duration == Duration::Once && self.spent.contains_key(&g.id))
    }

    // ---- the decision ---------------------------------------------------------------------

    /// Decide whether `who` may do `perm`, and why. The chain is built by running the rules
    /// themselves, so the same inputs always give the same chain: identity and membership, then
    /// a rule for the person, a rule for their role (a deny beats an allow at one level), the
    /// role's default, the extra gates, and default deny.
    pub fn decide(&self, who: &UserId, perm: &Permission, ctx: &Ctx) -> Explained {
        let mut chain = Vec::new();
        let decision = self.run(who, perm, ctx, &mut chain);
        Explained { who: who.clone(), permission: perm.clone(), decision, chain }
    }

    /// [`Project::decide`] with the permission as text.
    pub fn can(&self, who: &UserId, perm: &str, ctx: &Ctx) -> bool {
        self.decide(who, &Permission::new(perm), ctx).allowed()
    }

    fn rule_level(&self, subject: &Subject, perm: &Permission, now: i64, chain: &mut Vec<Step>, role: Option<&RoleId>) -> Option<Effect> {
        let mut matching: Vec<&Rule> = self.rules.iter().filter(|r| &r.subject == subject && &r.permission == perm).collect();
        matching.sort_by(|a, b| (a.set_ms, &a.id).cmp(&(b.set_ms, &b.id)));
        let mut live = Vec::new();
        for r in matching {
            if r.live(now) {
                live.push(r);
            } else {
                chain.push(Step::ExpiredRule { rule: r.id.clone() });
            }
        }
        let pick = live.iter().find(|r| r.effect == Effect::Deny).or_else(|| live.first())?;
        chain.push(match role {
            None => Step::MemberRule { rule: pick.id.clone(), effect: pick.effect, set_by: pick.set_by.clone(), set_ms: pick.set_ms },
            Some(role) => {
                Step::RoleRule { role: role.clone(), rule: pick.id.clone(), effect: pick.effect, set_by: pick.set_by.clone(), set_ms: pick.set_ms }
            }
        });
        Some(pick.effect)
    }

    fn run(&self, who: &UserId, perm: &Permission, ctx: &Ctx, chain: &mut Vec<Step>) -> Decision {
        if self.bans.contains(who) {
            chain.push(Step::Banned);
            return Decision::Denied;
        }
        let Some(m) = self.members.get(who) else {
            chain.push(Step::NotMember);
            return Decision::Denied;
        };
        if !self.open && perm.as_str() != MANAGE {
            chain.push(Step::SessionClosed);
            return Decision::Denied;
        }
        let allowed = match self.rule_level(&Subject::Member(who.clone()), perm, ctx.now_ms, chain, None) {
            Some(e) => e == Effect::Allow,
            None => match self.rule_level(&Subject::Role(m.role.clone()), perm, ctx.now_ms, chain, Some(&m.role)) {
                Some(e) => e == Effect::Allow,
                None => {
                    let granted = self.roles.grants(&m.role, perm);
                    chain.push(Step::RoleDefault { role: m.role.clone(), granted });
                    if !granted {
                        chain.push(Step::DefaultDeny);
                    }
                    granted
                }
            },
        };
        if !allowed {
            return Decision::Denied;
        }
        match self.roles.gate_of(perm) {
            None => Decision::Allowed,
            Some(Gate::Local(name)) => {
                chain.push(Step::LocalGate { name: name.clone() });
                Decision::Allowed
            }
            Some(Gate::OwnerConsent) => {
                let Some(owner) = ctx.stream_owner.clone() else {
                    chain.push(Step::NoOwnerNamed);
                    return Decision::Denied;
                };
                if &owner == who {
                    chain.push(Step::OwnAudio);
                    return Decision::Allowed;
                }
                let found = self.consents.iter().find(|g| {
                    g.owner == owner && &g.grantee == who && &g.permission == perm && g.covers(ctx.stream.as_ref()) && self.consent_live(g)
                });
                match found {
                    Some(g) => {
                        chain.push(Step::Consent { grant: g.id.clone(), owner, duration: g.duration });
                        Decision::Allowed
                    }
                    None => {
                        chain.push(Step::ConsentMissing { owner: owner.clone() });
                        Decision::NeedsConsent { owner }
                    }
                }
            }
        }
    }

    fn require(&self, who: &UserId, perm: &str, now: i64) -> Result<(), Error> {
        let e = self.decide(who, &Permission::new(perm), &Ctx::at(now));
        if e.allowed() { Ok(()) } else { Err(Error::NotAllowed(Box::new(e))) }
    }

    fn log(&mut self, actor: &Keypair, kind: AuditKind, now: i64) -> Result<(), Error> {
        let by = UserId::of_keypair(actor);
        let id = self.next_id(&by, now);
        self.audit.push(AuditEntry::sign(actor, id.as_str(), kind, now)?);
        Ok(())
    }

    // ---- members, roles, bans --------------------------------------------------------------

    /// Change a member's role. Needs `session.manage`; the owner's role cannot change.
    pub fn set_role(&mut self, actor: &Keypair, user: &UserId, role: &RoleId, now: i64) -> Result<(), Error> {
        let by = UserId::of_keypair(actor);
        self.require(&by, MANAGE, now)?;
        if !self.roles.knows(role) {
            return Err(Error::UnknownRole);
        }
        if user == &self.host {
            return Err(Error::IsHost);
        }
        let m = self.members.get_mut(user).ok_or(Error::NotMember)?;
        let from = std::mem::replace(&mut m.role, role.clone());
        self.log(actor, AuditKind::RoleChanged { user: user.clone(), from, to: role.clone() }, now)
    }

    /// Remove a member. Needs `session.manage`.
    pub fn kick(&mut self, actor: &Keypair, user: &UserId, now: i64) -> Result<(), Error> {
        self.require(&UserId::of_keypair(actor), MANAGE, now)?;
        if user == &self.host {
            return Err(Error::IsHost);
        }
        self.members.remove(user).ok_or(Error::NotMember)?;
        self.pending.retain(|p| &p.user != user);
        self.log(actor, AuditKind::MemberKicked { user: user.clone() }, now)
    }

    /// Ban an identity: it leaves the project, cannot rejoin, and cannot act. Needs
    /// `session.manage`.
    pub fn ban(&mut self, actor: &Keypair, user: &UserId, now: i64) -> Result<(), Error> {
        self.require(&UserId::of_keypair(actor), MANAGE, now)?;
        if user == &self.host {
            return Err(Error::IsHost);
        }
        self.members.remove(user);
        self.pending.retain(|p| &p.user != user);
        self.bans.insert(user.clone());
        self.log(actor, AuditKind::MemberBanned { user: user.clone() }, now)
    }

    /// Lift a ban (the identity can use an invite again). Needs `session.manage`.
    pub fn unban(&mut self, actor: &Keypair, user: &UserId, now: i64) -> Result<(), Error> {
        self.require(&UserId::of_keypair(actor), MANAGE, now)?;
        if self.bans.remove(user) {
            self.log(actor, AuditKind::MemberUnbanned { user: user.clone() }, now)?;
        }
        Ok(())
    }

    /// Close or reopen the session. Needs `session.manage`.
    pub fn set_open(&mut self, actor: &Keypair, open: bool, now: i64) -> Result<(), Error> {
        self.require(&UserId::of_keypair(actor), MANAGE, now)?;
        self.open = open;
        self.log(actor, AuditKind::SessionOpen { open }, now)
    }

    // ---- rules ----------------------------------------------------------------------------

    /// Set a rule for a member or a role. Needs `session.manage`. Returns the rule id.
    pub fn set_rule(
        &mut self,
        actor: &Keypair,
        subject: Subject,
        perm: &str,
        effect: Effect,
        expires_ms: Option<i64>,
        now: i64,
    ) -> Result<RecordId, Error> {
        let by = UserId::of_keypair(actor);
        self.require(&by, MANAGE, now)?;
        if let Subject::Role(r) = &subject
            && !self.roles.knows(r)
        {
            return Err(Error::UnknownRole);
        }
        let id = self.next_id(&by, now);
        let rule = Rule::sign(actor, id.as_str(), subject.clone(), &self.id, perm, effect, expires_ms, now)?;
        let (member, role) = match &subject {
            Subject::Member(u) => (Some(u.clone()), None),
            Subject::Role(r) => (None, Some(r.clone())),
        };
        self.rules.push(rule);
        self.log(actor, AuditKind::RuleSet { rule: id.clone(), permission: Permission::new(perm), effect, member, role }, now)?;
        Ok(id)
    }

    /// Remove a rule. Needs `session.manage`.
    pub fn remove_rule(&mut self, actor: &Keypair, rule: &RecordId, now: i64) -> Result<(), Error> {
        self.require(&UserId::of_keypair(actor), MANAGE, now)?;
        let at = self.rules.iter().position(|r| &r.id == rule).ok_or(Error::NoSuchRecord)?;
        self.rules.remove(at);
        self.log(actor, AuditKind::RuleRemoved { rule: rule.clone() }, now)
    }

    /// Take in a rule from another node. The signature must hold, the project must match and
    /// the setter must have had `session.manage` when it was set.
    pub fn accept_rule(&mut self, rule: Rule) -> Result<(), Error> {
        if !rule.verify() {
            return Err(Error::BadSignature);
        }
        if rule.project != self.id {
            return Err(Error::WrongProject);
        }
        if self.rules.iter().any(|r| r.id == rule.id) {
            return Err(Error::Duplicate);
        }
        self.require(&rule.set_by, MANAGE, rule.set_ms)?;
        self.rules.push(rule);
        Ok(())
    }

    // ---- consent --------------------------------------------------------------------------

    /// Give consent for `grantee` to use `permission` on your audio. Only you can: a host cannot
    /// grant it for you. The permission must carry an owner-consent gate.
    #[allow(clippy::too_many_arguments)]
    pub fn grant_consent(
        &mut self,
        owner: &Keypair,
        grantee: &UserId,
        permission: &str,
        streams: GrantStreams,
        duration: Duration,
        now: i64,
    ) -> Result<ConsentGrant, Error> {
        let me = UserId::of_keypair(owner);
        if !self.members.contains_key(&me) {
            return Err(Error::NotMember);
        }
        if !matches!(self.roles.gate_of(&Permission::new(permission)), Some(Gate::OwnerConsent)) {
            return Err(Error::NotGated);
        }
        let id = self.next_id(&me, now);
        let g = ConsentGrant::sign(owner, id.as_str(), grantee, &self.id, permission, streams, duration, now)?;
        self.consents.push(g.clone());
        self.log(owner, AuditKind::ConsentGranted { grant: id, owner: me, grantee: grantee.clone(), permission: Permission::new(permission) }, now)?;
        Ok(g)
    }

    /// Revoke a grant you gave. Live capture ends at the next decision.
    pub fn revoke_consent(&mut self, owner: &Keypair, grant: &RecordId, now: i64) -> Result<Revocation, Error> {
        let me = UserId::of_keypair(owner);
        let g = self.consents.iter().find(|g| &g.id == grant).ok_or(Error::NoSuchRecord)?;
        if g.owner != me {
            return Err(Error::NotOwner);
        }
        let r = Revocation::sign(owner, grant, now)?;
        self.revocations.insert(grant.clone(), r.clone());
        self.log(owner, AuditKind::ConsentRevoked { grant: grant.clone() }, now)?;
        Ok(r)
    }

    /// Take in a grant from another node (signed by the owner, for this project, gated).
    pub fn accept_consent(&mut self, g: ConsentGrant) -> Result<(), Error> {
        if !g.verify() {
            return Err(Error::BadSignature);
        }
        if g.project != self.id {
            return Err(Error::WrongProject);
        }
        if !matches!(self.roles.gate_of(&g.permission), Some(Gate::OwnerConsent)) {
            return Err(Error::NotGated);
        }
        if !self.members.contains_key(&g.owner) {
            return Err(Error::NotMember);
        }
        if self.consents.iter().any(|x| x.id == g.id) {
            return Err(Error::Duplicate);
        }
        self.consents.push(g);
        Ok(())
    }

    /// Take in a revocation from another node.
    pub fn accept_revocation(&mut self, r: Revocation) -> Result<(), Error> {
        if !r.verify() {
            return Err(Error::BadSignature);
        }
        let g = self.consents.iter().find(|g| g.id == r.grant).ok_or(Error::NoSuchRecord)?;
        if g.owner != r.owner {
            return Err(Error::NotOwner);
        }
        self.revocations.entry(r.grant.clone()).or_insert(r);
        Ok(())
    }

    /// Mark a `Once` grant as used (one take). Other grants are unaffected.
    pub fn spend_consent(&mut self, grant: &RecordId, now: i64) -> Result<(), Error> {
        let g = self.consents.iter().find(|g| &g.id == grant).ok_or(Error::NoSuchRecord)?;
        if g.duration == Duration::Once {
            self.spent.entry(grant.clone()).or_insert(now);
        }
        Ok(())
    }

    // ---- invites --------------------------------------------------------------------------

    /// Make an invite or link. Needs `session.invite`, and the creator's role must be allowed
    /// to invite as the spec's role (an editor may make viewer links only).
    /// The invite id is 128 bits from the OS random source, so a link cannot be guessed.
    pub fn create_invite(&mut self, actor: &Keypair, spec: InviteSpec, now: i64) -> Result<Invite, Error> {
        let by = UserId::of_keypair(actor);
        self.require(&by, INVITE, now)?;
        if !self.roles.knows(&spec.role) {
            return Err(Error::UnknownRole);
        }
        let creator = self.members.get(&by).ok_or(Error::NotMember)?;
        let host_like = self.roles.spec(&creator.role).is_some_and(|s| s.all);
        if !host_like && !self.roles.may_invite_as(&creator.role, &spec.role) {
            let mut e = self.decide(&by, &Permission::new(INVITE), &Ctx::at(now));
            e.decision = Decision::Denied;
            e.chain.push(Step::DefaultDeny);
            return Err(Error::NotAllowed(Box::new(e)));
        }
        let id = Self::invite_id();
        let invite = Invite::sign(actor, id.clone(), &self.id, spec.clone(), now)?;
        self.invites.insert(id.clone(), InviteState { invite: invite.clone(), uses: 0, revoked_ms: None });
        self.log(actor, AuditKind::InviteCreated { invite: id, role: spec.role, to: spec.to }, now)?;
        Ok(invite)
    }

    /// Someone opened an invite. Runs on the host's node; `host` records the outcome. The
    /// identity is the one the connection proved. Auto-approve invites make the person a
    /// member at once; others wait for [`Project::approve`].
    pub fn redeem(&mut self, host: &Keypair, invite: &RecordId, who: &UserId, now: i64) -> Result<Redeemed, Error> {
        let st = self.invites.get(invite).ok_or(InviteError::Unknown)?.clone();
        if !st.invite.verify() {
            return Err(InviteError::BadSignature.into());
        }
        if st.revoked_ms.is_some() {
            return Err(InviteError::Revoked.into());
        }
        if st.invite.spec.expires_ms <= now {
            return Err(InviteError::Expired.into());
        }
        if st.invite.spec.max_uses.is_some_and(|m| st.uses >= m) {
            return Err(InviteError::UsedUp.into());
        }
        if self.bans.contains(who) {
            return Err(InviteError::Banned.into());
        }
        if st.invite.spec.to.as_ref().is_some_and(|t| t != who) {
            return Err(InviteError::NotAddressee.into());
        }
        if self.members.contains_key(who) {
            return Err(InviteError::AlreadyMember.into());
        }
        if !self.decide(&st.invite.created_by, &Permission::new(INVITE), &Ctx::at(now)).allowed() {
            return Err(InviteError::CreatorLost.into());
        }
        match st.invite.spec.approval {
            Approval::Auto => {
                let role = st.invite.spec.role.clone();
                self.join(host, who, role.clone(), Some(invite.clone()), now)?;
                Ok(Redeemed::Joined(role))
            }
            Approval::HostApproves => {
                if self.pending.iter().any(|p| &p.user == who) {
                    return Err(InviteError::AlreadyPending.into());
                }
                self.pending.push(JoinRequest { invite: invite.clone(), user: who.clone(), at_ms: now });
                self.log(host, AuditKind::JoinRequested { user: who.clone(), invite: invite.clone() }, now)?;
                Ok(Redeemed::Pending)
            }
        }
    }

    fn join(&mut self, host: &Keypair, who: &UserId, role: RoleId, via: Option<RecordId>, now: i64) -> Result<(), Error> {
        self.members.insert(who.clone(), Member { user: who.clone(), role: role.clone(), joined_ms: now, via: via.clone() });
        if let Some(i) = via.as_ref().and_then(|v| self.invites.get_mut(v)) {
            i.uses += 1;
        }
        self.log(host, AuditKind::MemberJoined { user: who.clone(), role, invite: via }, now)
    }

    /// The host approves a waiting person. Needs `session.manage`.
    pub fn approve(&mut self, actor: &Keypair, user: &UserId, now: i64) -> Result<(), Error> {
        self.require(&UserId::of_keypair(actor), MANAGE, now)?;
        let at = self.pending.iter().position(|p| &p.user == user).ok_or(Error::NoSuchRecord)?;
        let req = self.pending.remove(at);
        let st = self.invites.get(&req.invite).ok_or(InviteError::Unknown)?.clone();
        if self.bans.contains(user) {
            return Err(InviteError::Banned.into());
        }
        self.join(actor, user, st.invite.spec.role.clone(), Some(req.invite), now)
    }

    /// The host turns a waiting person away. Needs `session.manage`.
    pub fn deny(&mut self, actor: &Keypair, user: &UserId, now: i64) -> Result<(), Error> {
        self.require(&UserId::of_keypair(actor), MANAGE, now)?;
        let at = self.pending.iter().position(|p| &p.user == user).ok_or(Error::NoSuchRecord)?;
        self.pending.remove(at);
        self.log(actor, AuditKind::JoinDenied { user: user.clone() }, now)
    }

    /// Revoke an invite. Needs `session.manage`. With `end_sessions`, members who came through
    /// it (and have no other way in) leave too. Returns who left.
    pub fn revoke_invite(&mut self, actor: &Keypair, invite: &RecordId, end_sessions: bool, now: i64) -> Result<Vec<UserId>, Error> {
        self.require(&UserId::of_keypair(actor), MANAGE, now)?;
        let st = self.invites.get_mut(invite).ok_or(InviteError::Unknown)?;
        st.revoked_ms = Some(now);
        self.pending.retain(|p| &p.invite != invite);
        let mut left = Vec::new();
        if end_sessions {
            let host = self.host.clone();
            left = self.members.values().filter(|m| m.via.as_ref() == Some(invite) && m.user != host).map(|m| m.user.clone()).collect();
            for u in &left {
                self.members.remove(u);
            }
        }
        self.log(actor, AuditKind::InviteRevoked { invite: invite.clone() }, now)?;
        Ok(left)
    }

    // ---- audit ----------------------------------------------------------------------------

    /// Delete audit entries. Needs `session.manage` (hosts only by the presets); the deletion is
    /// a signed record that [`Project::merge_audit`] carries to other nodes.
    pub fn delete_audit(&mut self, actor: &Keypair, ids: Vec<RecordId>, now: i64) -> Result<AuditDeletion, Error> {
        self.require(&UserId::of_keypair(actor), MANAGE, now)?;
        let d = AuditDeletion::sign(actor, ids, now)?;
        self.audit.delete(d.clone());
        Ok(d)
    }

    /// Set how long audit entries are kept. Needs `session.manage`.
    pub fn set_retention(&mut self, actor: &Keypair, retention_ms: Option<i64>, now: i64) -> Result<(), Error> {
        self.require(&UserId::of_keypair(actor), MANAGE, now)?;
        self.audit.retention_ms = retention_ms;
        Ok(())
    }

    /// Fold in another node's audit log: entries and deletions are checked for signature, and a
    /// deletion counts only from someone who is a host here. Returns how many entries were new.
    pub fn merge_audit(&mut self, other: &AuditLog) -> usize {
        let hosts: BTreeSet<UserId> = self.members.keys().filter(|u| self.is_host_like(u)).cloned().collect();
        self.audit.merge(other, |u| hosts.contains(u))
    }
}