Skip to main content

weirdnet_collab/
invite.rs

1//! Invites and links: who may make one, who may redeem it, and what joining needs.
2use crate::enc::{Enc, signed_by};
3use crate::ids::{ProjectId, RecordId, RoleId};
4use crate::records::SignError;
5use serde::{Deserialize, Serialize};
6use weirdnet_contacts::UserId;
7use weirdnet_net::Keypair;
8
9/// How a redeemed invite becomes membership.
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
11pub enum Approval {
12    /// The person joins at once.
13    Auto,
14    /// The host approves each person.
15    HostApproves,
16}
17
18/// What an invite grants.
19#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
20pub struct InviteSpec {
21    /// The role the person joins with.
22    pub role: RoleId,
23    /// `Some` for a direct invite to one identity (a contact); `None` for a link.
24    pub to: Option<UserId>,
25    /// When it stops working, milliseconds since the epoch.
26    pub expires_ms: i64,
27    /// How many people may use it.
28    pub max_uses: Option<u32>,
29    /// Auto-approve or host approves.
30    pub approval: Approval,
31}
32
33/// A signed invite. A link carries it; nobody joins without a Weirdnet identity.
34#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Invite {
36    /// Unique id.
37    pub id: RecordId,
38    /// The project.
39    pub project: ProjectId,
40    /// What it grants.
41    pub spec: InviteSpec,
42    /// Who made it.
43    pub created_by: UserId,
44    /// When.
45    pub created_ms: i64,
46    /// The creator's public key.
47    pub key: Vec<u8>,
48    /// The creator's signature.
49    pub sig: Vec<u8>,
50}
51
52impl Invite {
53    fn bytes(&self) -> Vec<u8> {
54        Enc::new("invite")
55            .s(self.id.as_str())
56            .s(self.project.as_str())
57            .s(self.spec.role.as_str())
58            .opt_s(self.spec.to.as_ref().map(|u| u.as_str()))
59            .i64(self.spec.expires_ms)
60            .opt_i64(self.spec.max_uses.map(i64::from))
61            .u8(matches!(self.spec.approval, Approval::Auto) as u8)
62            .s(self.created_by.as_str())
63            .i64(self.created_ms)
64            .b(&self.key)
65            .done()
66    }
67
68    pub(crate) fn sign(kp: &Keypair, id: RecordId, project: &ProjectId, spec: InviteSpec, now: i64) -> Result<Invite, SignError> {
69        let mut i = Invite {
70            id,
71            project: project.clone(),
72            spec,
73            created_by: UserId::of_keypair(kp),
74            created_ms: now,
75            key: kp.public().encode_protobuf(),
76            sig: Vec::new(),
77        };
78        i.sig = kp.sign(&i.bytes()).map_err(|e| SignError(e.to_string()))?;
79        Ok(i)
80    }
81
82    /// Whether the signature is the creator's.
83    pub fn verify(&self) -> bool {
84        signed_by(&self.created_by, &self.key, &self.bytes(), &self.sig)
85    }
86}
87
88/// An invite and its use.
89#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
90pub struct InviteState {
91    /// The invite.
92    pub invite: Invite,
93    /// People who joined through it.
94    pub uses: u32,
95    /// When it was revoked.
96    pub revoked_ms: Option<i64>,
97}
98
99/// Someone waiting for the host.
100#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
101pub struct JoinRequest {
102    /// The invite they used.
103    pub invite: RecordId,
104    /// Who they are.
105    pub user: UserId,
106    /// When they asked.
107    pub at_ms: i64,
108}
109
110/// Why an invite was refused.
111#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
112pub enum InviteError {
113    /// The project does not know this invite.
114    #[error("unknown invite")]
115    Unknown,
116    /// The signature does not hold.
117    #[error("bad signature")]
118    BadSignature,
119    /// Past its expiry.
120    #[error("expired")]
121    Expired,
122    /// Every use is spent.
123    #[error("used up")]
124    UsedUp,
125    /// Revoked.
126    #[error("revoked")]
127    Revoked,
128    /// The identity is banned from the project.
129    #[error("banned")]
130    Banned,
131    /// A direct invite for someone else.
132    #[error("not the addressee")]
133    NotAddressee,
134    /// Already a member.
135    #[error("already a member")]
136    AlreadyMember,
137    /// The person who made it can no longer make invites.
138    #[error("its creator may no longer invite")]
139    CreatorLost,
140    /// Already waiting for the host.
141    #[error("already waiting for approval")]
142    AlreadyPending,
143}
144
145/// What redeeming did.
146#[derive(Clone, Debug, PartialEq, Eq)]
147pub enum Redeemed {
148    /// The person is a member now, in this role.
149    Joined(RoleId),
150    /// The host has to approve.
151    Pending,
152}