1mod delivery;
5
6use std::{future::Future, sync::Arc, time::Duration};
7
8use jiff::Timestamp;
9use topcoat::{
10 context::Cx,
11 mail::Mailbox,
12 router::{request::uri, response::Response},
13};
14
15use self::delivery::DynDelivery;
16pub(super) use self::delivery::send;
17pub use self::delivery::{AuthLetter, AuthLetterKind, AuthMailDelivery};
18use crate::auth::realm::{Realm, current_realm};
19
20pub struct AuthMail {
47 from: Mailbox,
48 base_url: String,
49 delivery: Option<Arc<dyn DynDelivery>>,
50}
51
52impl AuthMail {
53 #[must_use]
57 pub fn new(from: Mailbox, base_url: impl Into<String>) -> Self {
58 Self {
59 from,
60 base_url: base_url.into().trim_end_matches('/').to_string(),
61 delivery: None,
62 }
63 }
64
65 #[must_use]
69 pub fn delivery(mut self, delivery: impl AuthMailDelivery) -> Self {
70 self.delivery = Some(Arc::new(delivery));
71 self
72 }
73
74 fn sends_through_mailer(&self) -> bool {
76 self.delivery.is_none()
77 }
78
79 pub(crate) fn base_url_is_absolute(&self) -> bool {
81 self.base_url.parse::<http::Uri>().is_ok_and(|uri| {
82 matches!(uri.scheme_str(), Some("http" | "https"))
83 && uri.authority().is_some()
84 && uri.query().is_none()
85 }) && !self.base_url.contains('#')
86 }
87
88 pub(crate) fn base_url(&self) -> &str {
89 &self.base_url
90 }
91
92 pub(super) fn link(&self, path: &str, token: &topcoat::session::Token) -> String {
94 let query = form_urlencoded::Serializer::new(String::new())
95 .append_pair(TOKEN_FIELD, &token.encode())
96 .finish();
97 format!("{}{path}?{query}", self.base_url)
98 }
99
100 pub(super) fn letter(
103 &self,
104 kind: AuthLetterKind,
105 address: &str,
106 subject: String,
107 text: String,
108 lifetime: Option<Duration>,
109 ) -> topcoat::Result<AuthLetter> {
110 let expires_at = lifetime
111 .map(|lifetime| {
112 Timestamp::try_from(std::time::SystemTime::now() + lifetime)
113 .map_err(topcoat::Error::from)
114 })
115 .transpose()?;
116 AuthLetter::new(kind, &self.from, address, subject, text, expires_at)
117 }
118
119 pub(super) async fn hand(
122 &self,
123 cx: &Cx,
124 ex: &mut dyn toasty::Executor,
125 letter: AuthLetter,
126 ) -> topcoat::Result<Option<AuthLetter>> {
127 match &self.delivery {
128 Some(delivery) => {
129 delivery.deliver(cx, ex, letter).await?;
130 Ok(None)
131 }
132 None => Ok(Some(letter)),
133 }
134 }
135}
136
137impl std::fmt::Debug for AuthMail {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 f.debug_struct("AuthMail")
140 .field("from", &self.from.address())
141 .field("base_url", &self.base_url)
142 .field("delivery", &self.delivery.is_some())
143 .finish()
144 }
145}
146
147pub(super) const TOKEN_FIELD: &str = "token";
149
150pub(super) fn token_from_query(cx: &Cx) -> String {
152 uri(cx)
153 .query()
154 .and_then(|query| {
155 form_urlencoded::parse(query.as_bytes())
156 .find(|(key, _)| key == TOKEN_FIELD)
157 .map(|(_, value)| value.into_owned())
158 })
159 .unwrap_or_default()
160}
161
162pub(super) fn after_response<F, Fut>(cx: &Cx, what: &'static str, send: F)
166where
167 F: FnOnce(Cx, Arc<Realm>) -> Fut + Send + 'static,
168 Fut: Future<Output = topcoat::Result<()>> + Send + 'static,
169{
170 let Some(panel) = current_realm(cx).map(Arc::clone) else {
171 return;
172 };
173 let request = cx.clone();
174 crate::settle::AfterResponse::spawn(cx, async move {
175 let prefix = panel.prefix.clone();
176 if let Err(error) = send(request, panel).await {
177 tracing::error!(error = %error, panel = %prefix, "{what} not sent");
178 }
179 });
180}
181
182pub(super) fn private(mut response: Response) -> topcoat::Result<Response> {
185 response.headers_mut().insert(
186 http::header::REFERRER_POLICY,
187 http::HeaderValue::from_static("no-referrer"),
188 );
189 Ok(response)
190}
191
192pub(super) fn declaration_errors(
196 auth: &super::AuthConfig,
197 has_mail: bool,
198) -> Vec<crate::DeclarationErrorKind> {
199 use crate::{AuthMailFault, DeclarationErrorKind};
200
201 let mailing = auth.mailing();
202 if auth.is_disabled() || mailing.is_empty() {
203 return Vec::new();
204 }
205 let Some(mail) = auth.mail.as_ref() else {
206 return mailing
207 .into_iter()
208 .map(|feature| DeclarationErrorKind::AuthMail(AuthMailFault::Unset { feature }))
209 .collect();
210 };
211 let mut faults = Vec::new();
212 if !mail.base_url_is_absolute() {
213 faults.push(AuthMailFault::BaseUrl(mail.base_url().to_string()));
214 }
215 if !has_mail && mail.sends_through_mailer() {
216 faults.push(AuthMailFault::MissingMail);
217 }
218 faults
219 .into_iter()
220 .map(DeclarationErrorKind::AuthMail)
221 .collect()
222}