Skip to main content

capy_auth/
verification.rs

1//! Framework-owned verification proofs with an application-owned delivery adapter.
2use crate::{LocalResetDelivery, MemoryResetDelivery, ResetDelivery, ResetMessage, Secret};
3use capy_core::Result;
4use std::{future::Future, pin::Pin};
5
6/// Deliver email-verification credentials privately; never log or queue plaintext proofs.
7pub trait VerificationDelivery: Send + Sync + 'static {
8    /// Accept a proof for delivery. Prefer a frontend URL fragment, never a query string.
9    fn deliver(
10        &self,
11        message: VerificationMessage,
12    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>>;
13    /// Declare an adapter that must be refused in production.
14    fn development_only(&self) -> bool {
15        false
16    }
17}
18/// Single-use proof. It is bound to a user and their current address in the database.
19pub struct VerificationMessage {
20    /// Private recipient address.
21    pub email: String,
22    /// Verification credential, distinct from password-reset credentials.
23    pub token: Secret,
24    /// Absolute expiration in Unix seconds.
25    pub expires_at: i64,
26}
27impl std::fmt::Debug for VerificationMessage {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        f.write_str("VerificationMessage([REDACTED])")
30    }
31}
32impl From<VerificationMessage> for ResetMessage {
33    fn from(message: VerificationMessage) -> Self {
34        Self {
35            email: message.email,
36            token: message.token,
37            expires_at: message.expires_at,
38        }
39    }
40}
41/// Private local file delivery, sharing the reset inbox's permissions and symlink checks.
42/// Select a separate directory, such as `.capy-verification-outbox`, outside public assets.
43#[derive(Clone, Debug)]
44pub struct LocalVerificationDelivery(LocalResetDelivery);
45impl LocalVerificationDelivery {
46    /// Select the private development-only directory.
47    pub fn new(directory: impl Into<std::path::PathBuf>) -> Self {
48        Self(LocalResetDelivery::new(directory))
49    }
50}
51impl VerificationDelivery for LocalVerificationDelivery {
52    fn deliver(
53        &self,
54        message: VerificationMessage,
55    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
56        self.0.deliver(message.into())
57    }
58    fn development_only(&self) -> bool {
59        true
60    }
61}
62/// Bounded, redacted verification inbox for integration tests. Refused in production.
63#[derive(Clone, Default, Debug)]
64pub struct MemoryVerificationDelivery(MemoryResetDelivery);
65impl MemoryVerificationDelivery {
66    /// Drain private delivery messages; the caller must not log the returned credentials.
67    pub fn take(&self) -> Vec<VerificationMessage> {
68        self.0
69            .take()
70            .into_iter()
71            .map(|message| VerificationMessage {
72                email: message.email,
73                token: message.token,
74                expires_at: message.expires_at,
75            })
76            .collect()
77    }
78}
79impl VerificationDelivery for MemoryVerificationDelivery {
80    fn deliver(
81        &self,
82        message: VerificationMessage,
83    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
84        self.0.deliver(message.into())
85    }
86    fn development_only(&self) -> bool {
87        true
88    }
89}
90
91/// Verification input. Send over a CSRF-protected request body, never a URL query.
92#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
93#[serde(deny_unknown_fields)]
94pub struct VerifyEmailRequest {
95    /// Single-use proof obtained through the private delivery adapter.
96    #[schemars(with = "String")]
97    pub token: Secret,
98}
99/// Verification state for the current authenticated identity.
100#[derive(Debug, serde::Serialize, schemars::JsonSchema)]
101pub struct VerificationStatus {
102    /// Whether the current address has been verified.
103    pub verified: bool,
104}
105
106/// Remove expired optional verification proofs. Call only after applying its migration.
107pub async fn prune(db: &sea_orm::DatabaseConnection) -> Result<u64> {
108    use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
109    Ok(crate::models::verification::Entity::delete_many()
110        .filter(crate::models::verification::Column::ExpiresAt.lte(crate::runtime::now()))
111        .exec(db)
112        .await?
113        .rows_affected)
114}
115
116/// Additional reversible migration; existing identity migrations must not be edited.
117pub mod migration {
118    use sea_orm_migration::prelude::*;
119    /// Register after the identity migration before enabling email-verification routes.
120    #[derive(DeriveMigrationName)]
121    pub struct EmailVerificationMigration;
122    #[async_trait::async_trait]
123    impl MigrationTrait for EmailVerificationMigration {
124        async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
125            manager
126                .create_table(
127                    Table::create()
128                        .table(Alias::new("email_verification_tokens"))
129                        .col(
130                            ColumnDef::new(Alias::new("user_id"))
131                                .big_integer()
132                                .not_null()
133                                .primary_key(),
134                        )
135                        .col(
136                            ColumnDef::new(Alias::new("token_hash"))
137                                .string_len(64)
138                                .not_null(),
139                        )
140                        .col(
141                            ColumnDef::new(Alias::new("email"))
142                                .string_len(254)
143                                .not_null(),
144                        )
145                        .col(
146                            ColumnDef::new(Alias::new("expires_at"))
147                                .big_integer()
148                                .not_null(),
149                        )
150                        .foreign_key(
151                            ForeignKey::create()
152                                .from_col(Alias::new("user_id"))
153                                .to(Alias::new("users"), Alias::new("id"))
154                                .on_delete(ForeignKeyAction::Cascade),
155                        )
156                        .to_owned(),
157                )
158                .await
159        }
160        async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
161            manager
162                .drop_table(
163                    Table::drop()
164                        .table(Alias::new("email_verification_tokens"))
165                        .to_owned(),
166                )
167                .await
168        }
169    }
170}