weirdnet_collab/
invite.rs1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
11pub enum Approval {
12 Auto,
14 HostApproves,
16}
17
18#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
20pub struct InviteSpec {
21 pub role: RoleId,
23 pub to: Option<UserId>,
25 pub expires_ms: i64,
27 pub max_uses: Option<u32>,
29 pub approval: Approval,
31}
32
33#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Invite {
36 pub id: RecordId,
38 pub project: ProjectId,
40 pub spec: InviteSpec,
42 pub created_by: UserId,
44 pub created_ms: i64,
46 pub key: Vec<u8>,
48 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 pub fn verify(&self) -> bool {
84 signed_by(&self.created_by, &self.key, &self.bytes(), &self.sig)
85 }
86}
87
88#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
90pub struct InviteState {
91 pub invite: Invite,
93 pub uses: u32,
95 pub revoked_ms: Option<i64>,
97}
98
99#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
101pub struct JoinRequest {
102 pub invite: RecordId,
104 pub user: UserId,
106 pub at_ms: i64,
108}
109
110#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
112pub enum InviteError {
113 #[error("unknown invite")]
115 Unknown,
116 #[error("bad signature")]
118 BadSignature,
119 #[error("expired")]
121 Expired,
122 #[error("used up")]
124 UsedUp,
125 #[error("revoked")]
127 Revoked,
128 #[error("banned")]
130 Banned,
131 #[error("not the addressee")]
133 NotAddressee,
134 #[error("already a member")]
136 AlreadyMember,
137 #[error("its creator may no longer invite")]
139 CreatorLost,
140 #[error("already waiting for approval")]
142 AlreadyPending,
143}
144
145#[derive(Clone, Debug, PartialEq, Eq)]
147pub enum Redeemed {
148 Joined(RoleId),
150 Pending,
152}