weirdnet-songnotes 0.4.0

SongNotes collaboration: the roles, permissions, links and consent requests for a SongNotes session, built on weirdnet-collab.
Documentation
//! The SongNotes collab protocol, `/songnotes/collab`: what any SongNotes app asks the host of a
//! project. The collab app serves it on the host; stage apps (drum machine, monitor, controller)
//! use [`client`] to join, read where they stand, report which app the person is in and read
//! who else is here.
//!
//! A live app re-reads its standing every [`RE_AUTH_MS`], so a role change or a kick reaches it
//! within that interval. Presence is reported every [`PRESENCE_REFRESH_MS`] and is gone
//! [`PRESENCE_TTL_MS`] after the last report.
use crate::session::ConsentRequest;
use serde::{Deserialize, Serialize};
use weirdnet_collab::{
    AuditEntry, AuditKind, ConsentGrant, Decision, Duration, Effect, Explained, GrantStreams, ProjectId, Revocation, RoleId, SignError, Step,
    StreamId,
};
use weirdnet_contacts::UserId;
use weirdnet_net::Keypair;
use weirdnet_service::ProtocolId;

/// The protocol id.
pub const PROTOCOL: &str = "/songnotes/collab";
/// The protocol version.
pub const VERSION: u32 = 1;
/// How often a live app re-reads its standing (the re-authorisation interval).
pub const RE_AUTH_MS: i64 = 5_000;
/// How often an app reports that the person is in it.
pub const PRESENCE_REFRESH_MS: i64 = 20_000;
/// How long a report counts.
pub const PRESENCE_TTL_MS: i64 = 60_000;
const _: () = assert!(RE_AUTH_MS < PRESENCE_REFRESH_MS && PRESENCE_REFRESH_MS < PRESENCE_TTL_MS);

/// The protocol id as a [`ProtocolId`].
pub fn protocol() -> ProtocolId {
    ProtocolId::new(PROTOCOL, VERSION).expect("a valid protocol id")
}

/// Where someone stands in a project.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Standing {
    /// A member with this role.
    Member(RoleId),
    /// Waiting for the host.
    Pending,
    /// Not in: never asked, turned away, kicked, or their link was revoked.
    Out,
    /// Banned.
    Banned,
}

/// Whether the person is using the app or it is in the background.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Activity {
    /// In front, in use.
    Active,
    /// Open but not in use.
    Idle,
}

/// "I am in this app": what an app reports for its person.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Here {
    /// The app, such as `collab` or `drummachine`.
    pub app: String,
    /// Active or idle.
    pub activity: Activity,
    /// When the report was made (the host's clock when it took it in).
    pub at_ms: i64,
}

/// One person as the project shows them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Person {
    /// Who.
    pub user: UserId,
    /// Their role.
    pub role: RoleId,
    /// The apps they are in now, newest report first (empty: offline).
    pub apps: Vec<Here>,
}

/// What a member sees of a project.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectView {
    /// The project.
    pub project: ProjectId,
    /// Its title.
    pub title: String,
    /// The host.
    pub host: UserId,
    /// Where the caller stands.
    pub standing: Standing,
    /// The members, the host first.
    pub people: Vec<Person>,
    /// The audit entries the caller is part of (all of them for the host), oldest first.
    pub audit: Vec<AuditEntry>,
    /// Consent questions waiting for the caller (as the audio's owner).
    #[serde(default)]
    pub consent_requests: Vec<ConsentRequest>,
    /// Live consent grants the caller gave or holds.
    #[serde(default)]
    pub grants: Vec<ConsentGrant>,
    /// The caller's own rights, one decision per permission in the catalog, with the reasons.
    #[serde(default)]
    pub rights: Vec<Explained>,
    /// The host's clock when the view was made.
    pub at_ms: i64,
}

impl ProjectView {
    /// One person.
    pub fn person(&self, user: &UserId) -> Option<&Person> {
        self.people.iter().find(|p| &p.user == user)
    }

    /// The caller's decision for `permission`, if the view has it.
    pub fn right(&self, permission: &str) -> Option<&Explained> {
        self.rights.iter().find(|e| e.permission.as_str() == permission)
    }

    /// Whether every audit entry's signature holds.
    pub fn audit_verifies(&self) -> bool {
        self.audit.iter().all(AuditEntry::verify)
    }
}

/// A request to the host.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Req {
    /// Redeem this link (its text).
    Join {
        /// The link.
        link: String,
    },
    /// Where do I stand?
    Status {
        /// The project.
        project: ProjectId,
    },
    /// The project as I may see it. Members only.
    Sync {
        /// The project.
        project: ProjectId,
    },
    /// I am in this app. Members only.
    Here {
        /// The project.
        project: ProjectId,
        /// The app.
        app: String,
        /// Active or idle.
        activity: Activity,
    },
    /// May I do `permission` (to `owner`'s audio, optionally one stream)? With `act`, the caller
    /// is about to do it, so a once-only consent is used up. A "needs consent" answer puts the
    /// question in the owner's queue. Members only.
    Can {
        /// The project.
        project: ProjectId,
        /// The permission.
        permission: String,
        /// Whose audio, for gated permissions.
        owner: Option<UserId>,
        /// Which stream.
        stream: Option<String>,
        /// About to do it now.
        act: bool,
    },
    /// A consent the caller (the owner) signed.
    Grant {
        /// The grant.
        grant: ConsentGrant,
    },
    /// The caller (the owner) takes a consent back.
    Revoke {
        /// The signed revocation.
        revocation: Revocation,
    },
    /// The caller (the owner) says no to a consent question.
    Decline {
        /// The question.
        request: ConsentRequest,
    },
}

/// The host's answer to a join or status request.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Answer {
    /// The project.
    pub project: ProjectId,
    /// Its title; told only to members and people waiting.
    pub title: Option<String>,
    /// Where the caller stands.
    pub standing: Standing,
}

/// A response.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Resp {
    /// To `Join` and `Status`.
    Answer(Answer),
    /// To `Sync`.
    View(Box<ProjectView>),
    /// To `Here`.
    Noted,
    /// To `Can`.
    Decision(Box<Explained>),
}

/// One audit entry as a line of text; `name` turns an id into how the reader knows them.
pub fn audit_line(e: &AuditEntry, name: impl Fn(&UserId) -> String) -> String {
    let by = name(&e.by);
    match &e.kind {
        AuditKind::RuleSet { permission, effect, member, role, .. } => {
            let who = member.as_ref().map(&name).or_else(|| role.as_ref().map(|r| format!("every {r}"))).unwrap_or_else(|| "everyone".into());
            let verb = if matches!(effect, weirdnet_collab::Effect::Allow) { "allowed" } else { "denied" };
            format!("{by} {verb} {permission} for {who}")
        }
        AuditKind::RuleRemoved { .. } => format!("{by} removed a rule"),
        AuditKind::RoleChanged { user, from, to } => format!("{by} changed {} from {from} to {to}", name(user)),
        AuditKind::MemberJoined { user, role, .. } => format!("{} joined as {role}", name(user)),
        AuditKind::MemberKicked { user } => format!("{by} removed {}", name(user)),
        AuditKind::MemberBanned { user } => format!("{by} banned {}", name(user)),
        AuditKind::MemberUnbanned { user } => format!("{by} lifted the ban on {}", name(user)),
        AuditKind::InviteCreated { role, to, .. } => match to {
            Some(u) => format!("{by} invited {} as {role}", name(u)),
            None => format!("{by} made a {role} link"),
        },
        AuditKind::InviteRevoked { .. } => format!("{by} revoked a link"),
        AuditKind::JoinRequested { user, .. } => format!("{} asked to join", name(user)),
        AuditKind::JoinDenied { user } => format!("{by} turned {} away", name(user)),
        AuditKind::ConsentGranted { owner, grantee, permission, .. } => format!("{} let {} {permission}", name(owner), name(grantee)),
        AuditKind::ConsentRevoked { .. } => format!("{by} took back a consent"),
        AuditKind::SessionOpen { open } => format!("{by} {} the session", if *open { "opened" } else { "closed" }),
    }
}

/// The owner answers a consent question with yes: a grant signed with `owner`, once or always,
/// for the stream the question named or (with `all_streams`, or when it named none) all of the
/// owner's streams in the project. The id is 128 bits from the OS random source.
pub fn sign_grant(owner: &Keypair, req: &ConsentRequest, how: Duration, all_streams: bool, now: i64) -> Result<ConsentGrant, SignError> {
    let mut b = [0u8; 16];
    getrandom::fill(&mut b).expect("the OS random source failed");
    let id: String = std::iter::once('g').chain(b.iter().flat_map(|x| format!("{x:02x}").chars().collect::<Vec<_>>())).collect();
    let streams = match (&req.stream, all_streams) {
        (Some(s), false) => GrantStreams::Only(vec![s.clone()]),
        _ => GrantStreams::All,
    };
    ConsentGrant::sign(owner, &id, &req.requester, &req.project, req.permission.as_str(), streams, how, now)
}

/// The owner takes a grant back.
pub fn sign_revocation(owner: &Keypair, grant: &ConsentGrant, now: i64) -> Result<Revocation, SignError> {
    Revocation::sign(owner, &grant.id, now)
}

/// A decision in a few words: "allowed", "denied" or "needs NAME's consent".
pub fn decision_word(d: &Decision, name: impl Fn(&UserId) -> String) -> String {
    match d {
        Decision::Allowed => "allowed".into(),
        Decision::Denied => "denied".into(),
        Decision::NeedsConsent { owner } => format!("needs {}'s consent", name(owner)),
    }
}

/// The reasons behind a decision, one line per step, for a "Why?" panel. The step that decided
/// names its rule, who set it and when.
pub fn why_lines(e: &Explained, name: impl Fn(&UserId) -> String) -> Vec<String> {
    let eff = |x: &Effect| if matches!(x, Effect::Allow) { "allows" } else { "denies" };
    e.chain
        .iter()
        .map(|s| match s {
            Step::Banned => "banned from the project".into(),
            Step::NotMember => "not a member".into(),
            Step::SessionClosed => "the session is closed".into(),
            Step::MemberRule { rule, effect, set_by, .. } => {
                format!("a rule for this person {} it (rule {rule}, set by {})", eff(effect), name(set_by))
            }
            Step::RoleRule { role, rule, effect, set_by, .. } => {
                format!("a rule for every {role} {} it (rule {rule}, set by {})", eff(effect), name(set_by))
            }
            Step::ExpiredRule { rule } => format!("rule {rule} has expired and was ignored"),
            Step::RoleDefault { role, granted } => format!("the {role} role {} it by default", if *granted { "has" } else { "does not have" }),
            Step::OwnAudio => "it is your own audio".into(),
            Step::Consent { owner, duration, .. } => {
                format!("{} said yes{}", name(owner), if matches!(duration, Duration::Once) { " once" } else { ", always" })
            }
            Step::ConsentMissing { owner } => format!("{} has not said yes", name(owner)),
            Step::NoOwnerNamed => "no audio owner was named".into(),
            Step::LocalGate { name: g } => format!("turned on locally ({g})"),
            Step::DefaultDeny => "nothing allows it".into(),
        })
        .collect()
}

/// The streams a grant covers, in words.
pub fn streams_word(g: &ConsentGrant) -> String {
    match &g.streams {
        GrantStreams::All => "all streams".into(),
        GrantStreams::Only(v) => v.iter().map(StreamId::to_string).collect::<Vec<_>>().join(", "),
    }
}

/// Talking to a host. Each call takes a session from
/// `weirdnet_service::Client::session::<Req, Resp>(host, &protocol())`.
pub mod client {
    use super::*;
    use weirdnet_service::{ServiceError, Session};

    fn bad(what: &str) -> ServiceError {
        ServiceError::App { code: "bad-response".into(), message: format!("not {what}") }
    }

    /// Open a session with `host`.
    pub async fn open(client: &weirdnet_service::Client, host: &UserId) -> Result<Session<Req, Resp>, ServiceError> {
        client.session::<Req, Resp>(host.as_str(), &protocol()).await
    }

    /// Ask to join with `link` (its text).
    pub async fn join(s: &Session<Req, Resp>, link: &str) -> Result<Answer, ServiceError> {
        match s.call(&Req::Join { link: link.into() }).await? {
            Resp::Answer(a) => Ok(a),
            _ => Err(bad("an answer")),
        }
    }

    /// Where you stand.
    pub async fn status(s: &Session<Req, Resp>, project: &ProjectId) -> Result<Answer, ServiceError> {
        match s.call(&Req::Status { project: project.clone() }).await? {
            Resp::Answer(a) => Ok(a),
            _ => Err(bad("an answer")),
        }
    }

    /// The project as you may see it. Call every [`RE_AUTH_MS`] while the app is live.
    pub async fn sync(s: &Session<Req, Resp>, project: &ProjectId) -> Result<ProjectView, ServiceError> {
        match s.call(&Req::Sync { project: project.clone() }).await? {
            Resp::View(v) => Ok(*v),
            _ => Err(bad("a view")),
        }
    }

    /// Report that you are in `app`. Call every [`PRESENCE_REFRESH_MS`].
    pub async fn here(s: &Session<Req, Resp>, project: &ProjectId, app: &str, activity: Activity) -> Result<(), ServiceError> {
        match s.call(&Req::Here { project: project.clone(), app: app.into(), activity }).await? {
            Resp::Noted => Ok(()),
            _ => Err(bad("noted")),
        }
    }
    /// May you do `permission` (to `owner`'s audio, one `stream`)? With `act`, you are about to,
    /// and a once-only consent is used up. Check this before acting; the answer names its reasons.
    pub async fn can(
        s: &Session<Req, Resp>,
        project: &ProjectId,
        permission: &str,
        owner: Option<&UserId>,
        stream: Option<&str>,
        act: bool,
    ) -> Result<Explained, ServiceError> {
        let req =
            Req::Can { project: project.clone(), permission: permission.into(), owner: owner.cloned(), stream: stream.map(str::to_string), act };
        match s.call(&req).await? {
            Resp::Decision(e) => Ok(*e),
            _ => Err(bad("a decision")),
        }
    }

    /// Hand the host a consent you signed (see [`sign_grant`]).
    pub async fn grant(s: &Session<Req, Resp>, grant: ConsentGrant) -> Result<(), ServiceError> {
        match s.call(&Req::Grant { grant }).await? {
            Resp::Noted => Ok(()),
            _ => Err(bad("noted")),
        }
    }

    /// Take a consent back (see [`sign_revocation`]).
    pub async fn revoke(s: &Session<Req, Resp>, revocation: Revocation) -> Result<(), ServiceError> {
        match s.call(&Req::Revoke { revocation }).await? {
            Resp::Noted => Ok(()),
            _ => Err(bad("noted")),
        }
    }

    /// Say no to a consent question.
    pub async fn decline(s: &Session<Req, Resp>, request: ConsentRequest) -> Result<(), ServiceError> {
        match s.call(&Req::Decline { request }).await? {
            Resp::Noted => Ok(()),
            _ => Err(bad("noted")),
        }
    }
}