weirdnet-collab 0.2.0

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
//! Invites and links: who may make one, who may redeem it, and what joining needs.
use crate::enc::{Enc, signed_by};
use crate::ids::{ProjectId, RecordId, RoleId};
use crate::records::SignError;
use serde::{Deserialize, Serialize};
use weirdnet_contacts::UserId;
use weirdnet_net::Keypair;

/// How a redeemed invite becomes membership.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Approval {
    /// The person joins at once.
    Auto,
    /// The host approves each person.
    HostApproves,
}

/// What an invite grants.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InviteSpec {
    /// The role the person joins with.
    pub role: RoleId,
    /// `Some` for a direct invite to one identity (a contact); `None` for a link.
    pub to: Option<UserId>,
    /// When it stops working, milliseconds since the epoch.
    pub expires_ms: i64,
    /// How many people may use it.
    pub max_uses: Option<u32>,
    /// Auto-approve or host approves.
    pub approval: Approval,
}

/// A signed invite. A link carries it; nobody joins without a Weirdnet identity.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Invite {
    /// Unique id.
    pub id: RecordId,
    /// The project.
    pub project: ProjectId,
    /// What it grants.
    pub spec: InviteSpec,
    /// Who made it.
    pub created_by: UserId,
    /// When.
    pub created_ms: i64,
    /// The creator's public key.
    pub key: Vec<u8>,
    /// The creator's signature.
    pub sig: Vec<u8>,
}

impl Invite {
    fn bytes(&self) -> Vec<u8> {
        Enc::new("invite")
            .s(self.id.as_str())
            .s(self.project.as_str())
            .s(self.spec.role.as_str())
            .opt_s(self.spec.to.as_ref().map(|u| u.as_str()))
            .i64(self.spec.expires_ms)
            .opt_i64(self.spec.max_uses.map(i64::from))
            .u8(matches!(self.spec.approval, Approval::Auto) as u8)
            .s(self.created_by.as_str())
            .i64(self.created_ms)
            .b(&self.key)
            .done()
    }

    pub(crate) fn sign(kp: &Keypair, id: RecordId, project: &ProjectId, spec: InviteSpec, now: i64) -> Result<Invite, SignError> {
        let mut i = Invite {
            id,
            project: project.clone(),
            spec,
            created_by: UserId::of_keypair(kp),
            created_ms: now,
            key: kp.public().encode_protobuf(),
            sig: Vec::new(),
        };
        i.sig = kp.sign(&i.bytes()).map_err(|e| SignError(e.to_string()))?;
        Ok(i)
    }

    /// Whether the signature is the creator's.
    pub fn verify(&self) -> bool {
        signed_by(&self.created_by, &self.key, &self.bytes(), &self.sig)
    }
}

/// An invite and its use.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InviteState {
    /// The invite.
    pub invite: Invite,
    /// People who joined through it.
    pub uses: u32,
    /// When it was revoked.
    pub revoked_ms: Option<i64>,
}

/// Someone waiting for the host.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct JoinRequest {
    /// The invite they used.
    pub invite: RecordId,
    /// Who they are.
    pub user: UserId,
    /// When they asked.
    pub at_ms: i64,
}

/// Why an invite was refused.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum InviteError {
    /// The project does not know this invite.
    #[error("unknown invite")]
    Unknown,
    /// The signature does not hold.
    #[error("bad signature")]
    BadSignature,
    /// Past its expiry.
    #[error("expired")]
    Expired,
    /// Every use is spent.
    #[error("used up")]
    UsedUp,
    /// Revoked.
    #[error("revoked")]
    Revoked,
    /// The identity is banned from the project.
    #[error("banned")]
    Banned,
    /// A direct invite for someone else.
    #[error("not the addressee")]
    NotAddressee,
    /// Already a member.
    #[error("already a member")]
    AlreadyMember,
    /// The person who made it can no longer make invites.
    #[error("its creator may no longer invite")]
    CreatorLost,
    /// Already waiting for the host.
    #[error("already waiting for approval")]
    AlreadyPending,
}

/// What redeeming did.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Redeemed {
    /// The person is a member now, in this role.
    Joined(RoleId),
    /// The host has to approve.
    Pending,
}