autter-core 2.0.2

Autter authentication service for Shrimpcamp
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
use serde::{Deserialize, Serialize};
use serde_valid::Validate;
pub use tetratto_core2::model::{ApiReturn, Error, Result, id::Id};
use totp_rs::TOTP;
use tritools::{
    encoding::{hash_salted, salt},
    time::unix_epoch_timestamp,
};

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum ThemePreference {
    #[default]
    Auto,
    Light,
    Dark,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum UserPermission {
    /// Manage other users.
    ManageUsers,
    /// Verify and unverify users.
    ManageVerified,
    /// Manage audit log entries.
    ManageAuditLog,
    /// Manage reports.
    ManageReports,
    /// Manage miscellaneous app data (e.g. Askall asks).
    ManageMiscAppData,
    /// Manage user notifications.
    ManageNotifications,
    /// User is banned.
    Banned,
    /// Ban and unban users.
    ManageBans,
    /// Delete other users.
    DeleteUsers,
    /// Manage user warnings.
    ManageWarnings,
    /// User is a premium user.
    Seedling,
    /// User is a premium plus user.
    SeedlingPlus,
    /// Manage user properties.
    ManageProperties,
    /// Manage user organizations.
    ManageOrganizations,
    /// Manage organization permission lists.
    ManagePermissionsLists,
    /// Manage the permissions of other users.
    Administrator,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum UserBadge {
    /// User is a site moderator.
    Staff,
}

#[derive(Clone, Debug, Serialize, Deserialize, Validate, Default)]
pub struct UserSettings {
    #[serde(default)]
    #[validate(max_length = 32)]
    pub display_name: String,
    #[serde(default)]
    #[validate(max_length = 4096)]
    pub biography: String,
    /// External links for the user's other profiles on other websites.
    #[serde(default)]
    #[validate(max_items = 15)]
    #[validate(unique_items)]
    pub links: Vec<(String, String)>,
    /// The user's contacts.
    #[serde(default)]
    #[validate(max_items = 5)]
    #[validate(unique_items)]
    pub contacts: Vec<(String, String)>,
    /// The user's theme used on their profile.
    #[serde(default)]
    pub profile_theme: ThemePreference,
}

impl UserSettings {
    pub fn verify_values(&self) -> Result<()> {
        if let Err(e) = self.validate() {
            return Err(Error::MiscError(e.to_string()));
        }

        Ok(())
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TetrattoLinkedAccount {
    pub id: Id,
    pub username: String,
    pub added: u128,
}

#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct UserLinkedAccounts {
    #[serde(default)]
    pub tetratto_multiple: Vec<TetrattoLinkedAccount>,
}

/// `(ip, token, creation timestamp)`
pub type Token = (String, String, u128);

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct User {
    pub id: Id,
    pub created: u128,
    pub username: String,
    pub password: String,
    pub salt: String,
    pub settings: UserSettings,
    pub tokens: Vec<Token>,
    pub permissions: Vec<UserPermission>,
    pub is_verified: bool,
    pub notification_count: usize,
    /// The TOTP secret for this profile. An empty value means the user has TOTP disabled.
    #[serde(default)]
    pub totp: String,
    /// The TOTP recovery codes for this profile.
    #[serde(default)]
    pub recovery_codes: Vec<String>,
    /// The user's Stripe customer ID.
    #[serde(default)]
    pub stripe_id: String,
    /// The reason the user was banned.
    #[serde(default)]
    pub ban_reason: String,
    /// The time at which the user's ban will automatically expire.
    #[serde(default)]
    pub ban_expire: usize,
    /// If the user is deactivated. Deactivated users act almost like deleted
    /// users, but their data is not wiped.
    #[serde(default)]
    pub is_deactivated: bool,
    /// The IDs of Stripe checkout sessions that this user has successfully completed.
    ///
    /// This should be checked BEFORE applying purchases to ensure that the user hasn't
    /// already applied this purchase.
    #[serde(default)]
    pub checkouts: Vec<String>,
    /// The time in which the user last consented to the site's policies.
    #[serde(default)]
    pub last_policy_consent: u128,
    /// The other accounts in the database that are linked to this account.
    #[serde(default)]
    pub linked_accounts: UserLinkedAccounts,
    /// A list of the user's profile badges.
    #[serde(default)]
    pub badges: Vec<UserBadge>,
    /// The ID of the user's principal organization (i.e. the organization shown on their profile).
    #[serde(default)]
    pub principal_org: Id,
    /// If the user is locked into their principal organization. Their organization's
    /// owner can manage their account if this is true.
    #[serde(default)]
    pub org_as_tenant: bool,
    /// The number of organizations the user can create.
    #[serde(default)]
    pub org_creation_credits: i32,
    /// The number of users the user can register to an organization.
    #[serde(default)]
    pub org_user_register_credits: i32,
    /// Users can pay to have their account marked as fully verified. This verification
    /// confirms they are a real human (to a degree). Promoting users who are super
    /// verified is a good way to keep AI and disgraceful content down.
    #[serde(default)]
    pub is_super_verified: bool,
}

impl Default for User {
    fn default() -> Self {
        Self::new("<unknown>".to_string(), String::new())
    }
}

impl User {
    /// Create a new [`User`].
    pub fn new(username: String, password: String) -> Self {
        let salt = salt();
        let password = hash_salted(password, salt.clone());
        let created = unix_epoch_timestamp();

        Self {
            id: Id::Legacy(Id::new().as_usize()),
            created,
            username,
            password,
            salt,
            settings: UserSettings::default(),
            tokens: Vec::new(),
            permissions: Vec::new(),
            is_verified: false,
            notification_count: 0,
            totp: String::new(),
            recovery_codes: Vec::new(),
            stripe_id: String::new(),
            ban_reason: String::new(),
            is_deactivated: false,
            ban_expire: 0,
            checkouts: Vec::new(),
            last_policy_consent: created,
            linked_accounts: UserLinkedAccounts::default(),
            badges: Vec::new(),
            principal_org: Id::default(),
            org_as_tenant: false,
            org_creation_credits: 0,
            org_user_register_credits: 0,
            is_super_verified: false,
        }
    }

    /// Deleted user profile.
    pub fn deleted() -> Self {
        Self {
            username: "<deleted>".to_string(),
            id: Id::default(),
            ..Default::default()
        }
    }

    /// Banned user profile.
    pub fn banned() -> Self {
        Self {
            username: "<banned>".to_string(),
            id: Id::default(),
            permissions: vec![UserPermission::Banned],
            ..Default::default()
        }
    }

    /// Create a new token
    ///
    /// # Returns
    /// `(unhashed id, token)`
    pub fn create_token(ip: &str) -> (String, Token) {
        let unhashed = Id::new().to_string();
        (
            unhashed.clone(),
            (
                ip.to_string(),
                tritools::encoding::hash(unhashed),
                tritools::time::unix_epoch_timestamp(),
            ),
        )
    }

    /// Check if the given password is correct for the user.
    pub fn check_password(&self, against: String) -> bool {
        self.password == hash_salted(against, self.salt.clone())
    }

    /// Get a [`TOTP`] from the profile's `totp` secret value.
    pub fn totp(&self, issuer: Option<String>) -> Option<TOTP> {
        if self.totp.is_empty() {
            return None;
        }

        TOTP::new(
            totp_rs::Algorithm::SHA1,
            6,
            1,
            30,
            self.totp.as_bytes().to_owned(),
            Some(issuer.unwrap_or("tetratto!".to_string())),
            self.username.clone(),
        )
        .ok()
    }

    /// Clean the struct for public viewing.
    pub fn clean(&mut self) {
        self.password = String::new();
        self.salt = String::new();

        self.tokens = Vec::new();

        self.recovery_codes = Vec::new();
        self.totp = String::new();

        self.settings = UserSettings::default();
        self.stripe_id = String::new();
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Notification {
    pub id: Id,
    pub created: u128,
    pub title: String,
    pub content: String,
    pub owner: Id,
    pub read: bool,
    pub tag: String,
}

impl Notification {
    /// Create a new [`Notification`].
    pub fn new(title: String, content: String, owner: Id) -> Self {
        Self {
            id: Id::new(),
            created: unix_epoch_timestamp(),
            title,
            content,
            owner,
            read: false,
            tag: String::new(),
        }
    }
}

#[derive(Serialize, Deserialize)]
pub struct AuditLogEntry {
    pub id: Id,
    pub created: u128,
    pub moderator: Id,
    pub content: String,
}

impl AuditLogEntry {
    /// Create a new [`AuditLogEntry`].
    pub fn new(moderator: Id, content: String) -> Self {
        Self {
            id: Id::new(),
            created: unix_epoch_timestamp(),
            moderator,
            content,
        }
    }
}

#[derive(Serialize, Deserialize)]
pub struct IpBan {
    pub ip: String,
    pub created: u128,
    pub reason: String,
    pub moderator: Id,
}

impl IpBan {
    /// Create a new [`IpBan`].
    pub fn new(ip: String, moderator: Id, reason: String) -> Self {
        Self {
            ip,
            created: unix_epoch_timestamp(),
            reason,
            moderator,
        }
    }
}

#[derive(Serialize, Deserialize)]
pub struct UserWarning {
    pub id: Id,
    pub created: u128,
    pub receiver: Id,
    pub moderator: Id,
    pub content: String,
}

impl UserWarning {
    /// Create a new [`UserWarning`].
    pub fn new(user: Id, moderator: Id, content: String) -> Self {
        Self {
            id: Id::new(),
            created: unix_epoch_timestamp(),
            receiver: user,
            moderator,
            content,
        }
    }
}

// socket
pub mod socket {
    use serde::{Deserialize, Serialize, de::DeserializeOwned};

    #[derive(Serialize, Deserialize, PartialEq, Eq)]
    pub enum CrudMessageType {
        Create,
        Delete,
    }

    #[derive(Serialize, Deserialize, PartialEq, Eq)]
    pub enum PacketType {
        /// A regular check to ensure the connection is still alive.
        Ping,
        /// General text which can be ignored.
        Text,
        /// A CRUD operation.
        Crud(CrudMessageType),
        /// A text key which identifies the socket.
        Key,
    }

    #[derive(Serialize, Deserialize, PartialEq, Eq)]
    pub enum SocketMethod {
        /// Authentication and channel identification.
        Headers,
        /// A message was sent in the channel.
        Message,
        /// A message was deleted in the channel.
        Delete,
        /// Forward message from server to client. (Redis pubsub to ws)
        Forward(PacketType),
        /// A general packet from client to server. (ws to Redis pubsub)
        Misc(PacketType),
        /// A general packet from client to server. (ws to Redis pubsub)
        Packet(PacketType),
    }

    #[derive(Serialize, Deserialize)]
    pub struct SocketMessage {
        pub method: SocketMethod,
        pub data: String,
    }

    impl SocketMessage {
        pub fn data<T: DeserializeOwned>(&self) -> T {
            serde_json::from_str(&self.data).unwrap()
        }
    }

    /// [`PacketType::Text`]
    #[derive(Serialize, Deserialize, PartialEq, Eq)]
    pub struct TextMessage {
        pub text: String,
    }
}

// properties
pub mod properties {
    use serde::{Deserialize, Serialize};
    use tetratto_core2::model::id::Id;
    use tritools::time::unix_epoch_timestamp;

    #[derive(Serialize, Deserialize, PartialEq, Eq)]
    pub enum Product {
        /// A single Tetratto account.
        Tetratto,
        /// Ability to create a Shrimpcamp organization.
        ///
        /// $200 once.
        Organization,
        /// Ability to register a user to an organization.
        ///
        /// $4 once.
        UserReg,
        /// A seedling membership.
        ///
        /// $4 monthly.
        Seedling,
        /// A user verification payment (corresponds to [`User::is_super_verified`]).
        ///
        /// $2 once.
        UserVerification,
    }

    #[derive(Serialize, Deserialize)]
    pub struct Property {
        pub id: Id,
        pub created: u128,
        pub owner: Id,
        /// A unique name for the instance. Used in the subdomain for the CNAME
        /// record's host (aka the URL for when the instance doesn't have a custom domain).
        pub name: String,
        pub product: Product,
        pub custom_domain: String,
    }

    impl Property {
        /// Create a new [`Property`].
        pub fn new(owner: Id, name: String, product: Product) -> Self {
            Self {
                id: Id::new(),
                created: unix_epoch_timestamp(),
                owner,
                name,
                product,
                custom_domain: String::new(),
            }
        }
    }
}

// organizations
pub mod organizations {
    use serde::{Deserialize, Serialize};
    use std::collections::HashMap;
    use tetratto_core2::model::id::Id;
    use tritools::time::unix_epoch_timestamp;

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
    pub enum OrganizationRole {
        Owner,
        Custom(usize),
        #[default]
        Member,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct Organization {
        pub id: Id,
        pub created: u128,
        pub owner: Id,
        pub name: String,
        pub members: i32,
        pub roles: HashMap<usize, String>,
    }

    impl Organization {
        /// Create a new [`Organization`].
        pub fn new(name: String, owner: Id) -> Self {
            Self {
                id: Id::new(),
                created: unix_epoch_timestamp(),
                owner,
                name,
                members: 0,
                roles: HashMap::new(),
            }
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct OrganizationMembership {
        pub id: Id,
        pub created: u128,
        pub organization: Id,
        pub owner: Id,
        pub role: OrganizationRole,
    }

    impl OrganizationMembership {
        /// Create a new [`OrganizationMembership`].
        pub fn new(organization: Id, owner: Id) -> Self {
            Self {
                id: Id::new(),
                created: unix_epoch_timestamp(),
                organization,
                owner,
                role: OrganizationRole::Member,
            }
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct PermissionsList {
        pub id: Id,
        pub created: u128,
        pub owner_org: Id,
        pub name: String,
        pub roles: Vec<usize>,
    }

    impl PermissionsList {
        /// Create a new [`PermissionsList`].
        pub fn new(owner_org: Id, name: String) -> Self {
            Self {
                id: Id::new(),
                created: unix_epoch_timestamp(),
                owner_org,
                name,
                roles: Vec::new(),
            }
        }
    }
}