allowthem-core 0.0.5

Core types, database, and auth logic for allowthem
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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;

macro_rules! id_newtype {
    ($name:ident) => {
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, sqlx::Type)]
        #[sqlx(transparent)]
        pub struct $name(Uuid);

        impl $name {
            pub fn new() -> Self {
                Self(Uuid::now_v7())
            }

            pub fn from_uuid(id: Uuid) -> Self {
                Self(id)
            }

            pub fn as_uuid(&self) -> &Uuid {
                &self.0
            }
        }

        impl Default for $name {
            fn default() -> Self {
                Self::new()
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                self.0.fmt(f)
            }
        }

        impl std::str::FromStr for $name {
            type Err = uuid::Error;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                s.parse::<Uuid>().map(Self)
            }
        }
    };
}

id_newtype!(UserId);
id_newtype!(SessionId);
id_newtype!(RoleId);
id_newtype!(PermissionId);
id_newtype!(ResetTokenId);
id_newtype!(AuditEntryId);
id_newtype!(ApiTokenId);
id_newtype!(OAuthAccountId);
id_newtype!(OAuthStateId);
id_newtype!(MfaSecretId);
id_newtype!(MfaRecoveryCodeId);
id_newtype!(MfaChallengeId);
id_newtype!(InvitationId);
id_newtype!(ApplicationId);
id_newtype!(AuthorizationCodeId);
id_newtype!(RefreshTokenId);
id_newtype!(ConsentId);
id_newtype!(SigningKeyId);
id_newtype!(VerificationTokenId);

/// Email address. Validated at construction.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, sqlx::Type)]
#[sqlx(transparent)]
pub struct Email(String);

impl Email {
    /// Create an `Email` after basic format validation.
    ///
    /// Checks: exactly one `@`, non-empty local part, non-empty domain
    /// with at least one `.`. Not RFC 5322 compliant — intentionally simple.
    pub fn new(s: String) -> Result<Self, crate::error::AuthError> {
        let trimmed = s.trim().to_string();
        let parts: Vec<&str> = trimmed.splitn(3, '@').collect();
        if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() {
            return Err(crate::error::AuthError::InvalidEmail);
        }
        Ok(Self(trimmed))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[allow(dead_code)]
    pub(crate) fn new_unchecked(s: String) -> Self {
        Self(s)
    }
}

/// Optional display/login alias.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, sqlx::Type)]
#[sqlx(transparent)]
pub struct Username(String);

impl Username {
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[allow(dead_code)]
    pub(crate) fn new_unchecked(s: String) -> Self {
        Self(s)
    }
}

/// Argon2id hash output stored as PHC string.
/// Not Serialize — password hashes must never appear in API responses.
/// Not PartialEq/Eq — forces callers to use constant-time comparison via Argon2 verify.
#[derive(Debug, Clone, sqlx::Type)]
#[sqlx(transparent)]
pub struct PasswordHash(String);

impl PasswordHash {
    pub fn new_unchecked(s: String) -> Self {
        Self(s)
    }

    pub(crate) fn as_str(&self) -> &str {
        &self.0
    }
}

/// SHA-256 hash of the raw session token, stored in the DB.
/// The raw token is only held in memory or in the cookie — never persisted.
/// Not PartialEq/Eq — forces callers to use constant-time comparison.
#[derive(Debug, Clone, sqlx::Type)]
#[sqlx(transparent)]
pub struct TokenHash(String);

impl TokenHash {
    #[allow(dead_code)]
    pub(crate) fn new_unchecked(s: String) -> Self {
        Self(s)
    }
}

/// A raw session token — 32 random bytes encoded as base64url (no padding).
/// This is what is placed in the session cookie. Never persisted to the database.
/// The SHA-256 hash of this value is stored as `TokenHash`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionToken(String);

impl SessionToken {
    pub fn from_encoded(s: String) -> Self {
        Self(s)
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Public-facing OAuth client identifier.
///
/// Format: `ath_` prefix + 24 random bytes base64url-encoded (32 chars) = 36 chars total.
/// The prefix makes client IDs recognizable in logs and configs. The 192 bits of
/// entropy from the random portion ensures collision resistance without coordination.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, sqlx::Type)]
#[sqlx(transparent)]
pub struct ClientId(String);

impl ClientId {
    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub(crate) fn new_unchecked(s: String) -> Self {
        Self(s)
    }
}

impl std::fmt::Display for ClientId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

/// Whether an OIDC application is a confidential or public client.
///
/// Confidential clients (server-side apps) authenticate with a `client_secret`.
/// Public clients (SPAs, native apps) have no secret — they authenticate via PKCE only.
#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type, Serialize, Deserialize)]
#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
#[serde(rename_all = "lowercase")]
pub enum ClientType {
    Confidential,
    Public,
}

/// A raw OAuth client secret — returned once on application creation.
///
/// 32 random bytes base64url-encoded (43 chars). Same entropy as session tokens.
/// The Argon2 hash of this value is stored as `client_secret_hash` in the
/// applications table. Never persisted.
#[derive(Debug, Clone)]
pub struct ClientSecret(String);

impl ClientSecret {
    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub(crate) fn new_unchecked(s: String) -> Self {
        Self(s)
    }
}

/// A role name as defined by the integrating application.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, sqlx::Type)]
#[sqlx(transparent)]
pub struct RoleName(String);

impl RoleName {
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[allow(dead_code)]
    pub(crate) fn new_unchecked(s: String) -> Self {
        Self(s)
    }
}

/// A permission scope as defined by the integrating application.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, sqlx::Type)]
#[sqlx(transparent)]
pub struct PermissionName(String);

impl PermissionName {
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[allow(dead_code)]
    pub(crate) fn new_unchecked(s: String) -> Self {
        Self(s)
    }
}

#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct User {
    pub id: UserId,
    pub email: Email,
    pub username: Option<Username>,
    #[serde(skip_serializing)]
    pub password_hash: Option<PasswordHash>,
    pub email_verified: bool,
    pub is_active: bool,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub custom_data: Option<Value>,
}

#[derive(Debug, Clone, sqlx::FromRow)]
pub struct Session {
    pub id: SessionId,
    pub token_hash: TokenHash,
    pub user_id: UserId,
    pub ip_address: Option<String>,
    pub user_agent: Option<String>,
    pub expires_at: DateTime<Utc>,
    pub created_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct Role {
    pub id: RoleId,
    pub name: RoleName,
    pub description: Option<String>,
    pub created_at: DateTime<Utc>,
}

#[derive(Debug, Clone, sqlx::FromRow)]
pub struct UserRole {
    pub user_id: UserId,
    pub role_id: RoleId,
    pub created_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct Permission {
    pub id: PermissionId,
    pub name: PermissionName,
    pub description: Option<String>,
    pub created_at: DateTime<Utc>,
}

#[derive(Debug, Clone, sqlx::FromRow)]
pub struct RolePermission {
    pub role_id: RoleId,
    pub permission_id: PermissionId,
}

#[derive(Debug, Clone, sqlx::FromRow)]
pub struct UserPermission {
    pub user_id: UserId,
    pub permission_id: PermissionId,
}

/// Metadata for an API token. Does not include the token hash.
/// The raw token is only returned once, at creation time.
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct ApiTokenInfo {
    pub id: ApiTokenId,
    pub user_id: UserId,
    pub name: String,
    pub metadata: Option<String>,
    pub expires_at: Option<DateTime<Utc>>,
    pub created_at: DateTime<Utc>,
}

/// Text-on-accent color. Must pair AAA against the accent fill.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, sqlx::Type)]
#[serde(rename_all = "lowercase")]
#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
pub enum AccentInk {
    Black,
    White,
}

impl AccentInk {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Black => "black",
            Self::White => "white",
        }
    }

    /// Hex color for inline CSS emission.
    pub fn as_hex(&self) -> &'static str {
        match self {
            Self::Black => "#000000",
            Self::White => "#ffffff",
        }
    }
}

impl std::str::FromStr for AccentInk {
    type Err = crate::error::AuthError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "black" => Ok(Self::Black),
            "white" => Ok(Self::White),
            _ => Err(crate::error::AuthError::Validation(
                "accent_ink must be 'black' or 'white'".into(),
            )),
        }
    }
}

/// UI color mode — dark is the Wave Funk default.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, sqlx::Type)]
#[serde(rename_all = "lowercase")]
#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
pub enum Mode {
    Dark,
    Light,
}

impl Mode {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Dark => "dark",
            Self::Light => "light",
        }
    }
}

impl std::str::FromStr for Mode {
    type Err = crate::error::AuthError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "dark" => Ok(Self::Dark),
            "light" => Ok(Self::Light),
            _ => Err(crate::error::AuthError::Validation(
                "forced_mode must be 'dark' or 'light'".into(),
            )),
        }
    }
}

/// Built-in splash-shape variants rendered by the default shader.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, sqlx::Type)]
#[serde(rename_all = "lowercase")]
#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
pub enum SplashPrimitive {
    Wordmark,
    Circle,
    Grid,
    Wave,
}

impl SplashPrimitive {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Wordmark => "wordmark",
            Self::Circle => "circle",
            Self::Grid => "grid",
            Self::Wave => "wave",
        }
    }
}

impl std::str::FromStr for SplashPrimitive {
    type Err = crate::error::AuthError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "wordmark" => Ok(Self::Wordmark),
            "circle" => Ok(Self::Circle),
            "grid" => Ok(Self::Grid),
            "wave" => Ok(Self::Wave),
            _ => Err(crate::error::AuthError::Validation(
                "splash_primitive must be one of wordmark|circle|grid|wave".into(),
            )),
        }
    }
}

#[cfg(test)]
mod wavefunk_enum_tests {
    use super::*;

    #[test]
    fn accent_ink_round_trip() {
        assert_eq!(AccentInk::Black.as_str(), "black");
        assert_eq!(AccentInk::White.as_str(), "white");
        assert_eq!("black".parse::<AccentInk>().unwrap(), AccentInk::Black);
        assert_eq!("white".parse::<AccentInk>().unwrap(), AccentInk::White);
        assert!("gray".parse::<AccentInk>().is_err());
    }

    #[test]
    fn mode_round_trip() {
        assert_eq!(Mode::Dark.as_str(), "dark");
        assert_eq!(Mode::Light.as_str(), "light");
        assert_eq!("dark".parse::<Mode>().unwrap(), Mode::Dark);
        assert_eq!("light".parse::<Mode>().unwrap(), Mode::Light);
        assert!("auto".parse::<Mode>().is_err());
    }

    #[test]
    fn splash_primitive_round_trip() {
        for (s, v) in [
            ("wordmark", SplashPrimitive::Wordmark),
            ("circle", SplashPrimitive::Circle),
            ("grid", SplashPrimitive::Grid),
            ("wave", SplashPrimitive::Wave),
        ] {
            assert_eq!(v.as_str(), s);
            assert_eq!(s.parse::<SplashPrimitive>().unwrap(), v);
        }
        assert!("square".parse::<SplashPrimitive>().is_err());
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::UserId;

    #[test]
    fn userid_fromstr_parses_valid_uuid() {
        let s = "550e8400-e29b-41d4-a716-446655440000";
        let id = UserId::from_str(s).unwrap();
        assert_eq!(id.to_string(), s);
    }

    #[test]
    fn userid_fromstr_rejects_invalid() {
        assert!(UserId::from_str("not-a-uuid").is_err());
    }
}