Skip to main content

spoolframe_protocol/
invite_admin.rs

1//! Making and managing invites from an app: the client protocol's
2//! admin requests `CreateInvite`, `ListInvites` and `RevokeInvite`. These
3//! are the same invites, with the same limits, as the web UI makes; the
4//! web UI and the apps see each other's.
5//!
6//! Only an admin's session may ask (`AdminRequired` otherwise), and only
7//! for an account here (`NotForPortableUsers` for a portable guest).
8//! Creating and revoking also need the admin to have confirmed it is them
9//! recently, as the web UI's admin changes do: a fresh `ConfirmPassword`
10//! or passkey confirmation, else `RecentSignInRequired`. Listing does
11//! not.
12
13use std::fmt;
14
15use serde::{Deserialize, Serialize};
16use spoolframe_types::{Platform, Role};
17
18/// What redeeming an invite does.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "kebab-case")]
21pub enum InviteKind {
22    /// Makes an account here.
23    CreateUser,
24    /// Lets a portable identity watch here, with no account made.
25    PortableAccount,
26    /// Pairs another server with this one (experimental): made
27    /// only for a client that named the `federation` feature, on a
28    /// server that has it on.
29    Federation,
30    /// A kind this build does not know, from a newer server.
31    #[serde(other)]
32    Unknown,
33}
34
35/// An invite to make (`CreateInvite`). Each `None` is the server's
36/// default, as for the web UI's `inviteCreate`: one use, 7 days, the
37/// consumer role.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct CreateInvite {
40    pub kind: InviteKind,
41    /// Who it is for, for the admins' list: at most 64 characters, one
42    /// line.
43    #[serde(deserialize_with = "spoolframe_types::required::option")]
44    pub note: Option<String>,
45    /// How many times it may be redeemed: 1 to 100.
46    #[serde(deserialize_with = "spoolframe_types::required::option")]
47    pub uses: Option<u32>,
48    /// How long it lasts from now, in seconds: an hour to 30 days.
49    #[serde(deserialize_with = "spoolframe_types::required::option")]
50    pub expires_in_secs: Option<u64>,
51    /// The role the accounts it makes get; only for `create-user`. A
52    /// `portable-account` invite with any role but `consumer` is
53    /// `InvalidInput`: a portable guest has no account here to hold one.
54    #[serde(deserialize_with = "spoolframe_types::required::option")]
55    pub role: Option<Role>,
56}
57
58/// Who made an invite.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct InviteCreator {
61    /// The admin's username; `None` for one made with the server's CLI,
62    /// which signs in as no one.
63    #[serde(deserialize_with = "spoolframe_types::required::option")]
64    pub username: Option<String>,
65    /// What to show: the admin's display name (their username when they
66    /// have none, or when the account is gone), or "server CLI".
67    pub display_name: String,
68}
69
70/// Where an invite was made.
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(tag = "type", rename_all = "snake_case")]
73pub enum InviteOrigin {
74    /// The web UI's admin pages. Also any invite made before the server
75    /// recorded where invites come from, except the CLI's.
76    WebAdmin,
77    /// `spoolframe-server invite create`.
78    Cli,
79    /// An app, on the device it ran on, as its `Hello` named it.
80    Device {
81        /// The device's `EndpointId`, hex: an app compares it with its own
82        /// to say "on this device".
83        endpoint_id: String,
84        #[serde(deserialize_with = "spoolframe_types::required::option")]
85        name: Option<String>,
86        platform: Platform,
87    },
88    /// A place this build does not know, from a newer server.
89    #[serde(other)]
90    Unknown,
91}
92
93/// An invite as admins see it: never its code, which the server keeps
94/// only as a hash.
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96pub struct InviteSummary {
97    /// What `RevokeInvite` takes.
98    pub id: String,
99    pub kind: InviteKind,
100    #[serde(deserialize_with = "spoolframe_types::required::option")]
101    pub note: Option<String>,
102    /// The role its accounts get; `consumer` for a `portable-account` one.
103    pub role: Role,
104    /// How many times it may be redeemed in all, and how many it still
105    /// may.
106    pub uses: u32,
107    pub uses_left: u32,
108    /// Unix seconds.
109    pub expires_at: i64,
110    /// Unix seconds.
111    pub created_at: i64,
112    pub created_by: InviteCreator,
113    pub created_from: InviteOrigin,
114}
115
116/// A new invite (`CreateInvite`), with its code: shown this once.
117#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
118pub struct InviteCreated {
119    pub invite: InviteSummary,
120    /// As people read and type it: `QW7K-2MFP-XR4T`.
121    pub code: String,
122    /// The invite link ([`crate::invite`]), the code in it: the
123    /// `spoolframe://` form, what the QR code shows.
124    pub link: String,
125    /// The same invite as an https link on spoolframe.app
126    /// ([`crate::invite::Invite::share_link`]): what the share
127    /// sheet sends and Copy copies.
128    pub share_link: String,
129}
130
131impl fmt::Debug for InviteCreated {
132    // The code is a capability until it is used up: keep it out of logs.
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        f.debug_struct("InviteCreated")
135            .field("invite", &self.invite)
136            .field("code", &"<redacted>")
137            .field("link", &"<redacted>")
138            .field("share_link", &"<redacted>")
139            .finish()
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[test]
148    fn an_origin_from_a_newer_server_reads_as_unknown() {
149        let origin: InviteOrigin =
150            serde_json::from_str(r#"{"type":"federated_peer","server":"x"}"#).unwrap();
151        assert_eq!(origin, InviteOrigin::Unknown);
152    }
153
154    #[test]
155    fn a_kind_from_a_newer_server_reads_as_unknown() {
156        let kind: InviteKind = serde_json::from_str(r#""household""#).unwrap();
157        assert_eq!(kind, InviteKind::Unknown);
158    }
159
160    #[test]
161    fn a_device_origin_round_trips() {
162        let origin = InviteOrigin::Device {
163            endpoint_id: "ab".repeat(32),
164            name: Some("Andrey's iPhone".into()),
165            platform: Platform::Ios,
166        };
167        let json = serde_json::to_string(&origin).unwrap();
168        assert_eq!(serde_json::from_str::<InviteOrigin>(&json).unwrap(), origin);
169    }
170
171    fn created() -> InviteCreated {
172        InviteCreated {
173            invite: InviteSummary {
174                id: "id".into(),
175                kind: InviteKind::CreateUser,
176                note: None,
177                role: Role::Consumer,
178                uses: 1,
179                uses_left: 1,
180                expires_at: 1,
181                created_at: 0,
182                created_by: InviteCreator {
183                    username: Some("andrey".into()),
184                    display_name: "Andrey".into(),
185                },
186                created_from: InviteOrigin::WebAdmin,
187            },
188            code: "QW7K-2MFP-XR4T".into(),
189            link: "spoolframe://invite?server=x&cap=QW7K2MFPXR4T".into(),
190            share_link: "https://spoolframe.app/i#server=x&cap=QW7K2MFPXR4T".into(),
191        }
192    }
193
194    #[test]
195    fn the_code_and_link_stay_out_of_debug() {
196        let shown = format!("{:?}", created());
197        assert!(!shown.contains("QW7K"), "{shown}");
198    }
199
200    /// PX-45: a created invite without its share link, as a server
201    /// before the reset to revision 1 could send it, is refused.
202    #[test]
203    fn a_created_invite_without_a_share_link_is_refused() {
204        let mut sent = serde_json::to_value(created()).unwrap();
205        sent.as_object_mut().unwrap().remove("share_link").unwrap();
206        let error = serde_json::from_value::<InviteCreated>(sent).unwrap_err();
207        assert!(
208            error.to_string().contains("missing field `share_link`"),
209            "{error}"
210        );
211    }
212}