feat(hub): email one-time-code sign-in
POST /v1/auth/email/start and /verify with HMAC-protected 8-digit codes (10 min, 5 tries, atomic single use), browser-bound via a __Host- cookie, same-origin checks, per-address/source/global rate limits and an injectable sender. Enabled in /v1/info only when SMTP is configured. Email identities use external_identities(provider='email') and never merge with GitHub.
This commit is contained in:
parent
f1883e5001
commit
cca084b0ae
20 changed files with 1756 additions and 59 deletions
379
hub/src/auth/email.rs
Normal file
379
hub/src/auth/email.rs
Normal file
|
|
@ -0,0 +1,379 @@
|
|||
//! Passwordless email sign-in: address normalization, keyed MACs, one-time codes and
|
||||
//! rate limits. Nothing in this module logs addresses, codes or network sources.
|
||||
|
||||
use std::{future::Future, pin::Pin, sync::Arc};
|
||||
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
use sqlx::SqlitePool;
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
use super::store::{hash, now};
|
||||
use crate::mail::templates::Email;
|
||||
|
||||
/// Lifetime of a pending code. Also the cookie lifetime of the attempt binding.
|
||||
pub const CODE_TTL: i64 = 600;
|
||||
/// Verification tries per issued code, counted before the comparison.
|
||||
pub const MAX_FAILURES: i64 = 5;
|
||||
/// Pending attempts kept at once; protects the table from being filled by anonymous traffic.
|
||||
const MAX_PENDING: i64 = 4096;
|
||||
const CODE_DIGITS: usize = 8;
|
||||
|
||||
/// Delivery boundary. The production implementation is [`crate::mail::Mailer`]; tests
|
||||
/// inject a recorder so no network traffic or real mail is ever produced.
|
||||
pub trait CodeSender: Send + Sync {
|
||||
fn send<'a>(
|
||||
&'a self,
|
||||
recipient: &'a str,
|
||||
email: Email,
|
||||
) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'a>>;
|
||||
}
|
||||
|
||||
impl CodeSender for crate::mail::Mailer {
|
||||
fn send<'a>(
|
||||
&'a self,
|
||||
recipient: &'a str,
|
||||
email: Email,
|
||||
) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'a>> {
|
||||
Box::pin(self.deliver(recipient, email))
|
||||
}
|
||||
}
|
||||
|
||||
/// Send budgets. Every request that passes validation consumes budget, whether or not
|
||||
/// delivery later succeeds, so the limits bound SMTP use and address harassment.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct EmailLimits {
|
||||
/// Minimum seconds between two codes for the same address.
|
||||
pub address_cooldown: i64,
|
||||
pub per_address_hour: i64,
|
||||
pub per_source_hour: i64,
|
||||
pub global_hour: i64,
|
||||
}
|
||||
|
||||
impl Default for EmailLimits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
address_cooldown: 60,
|
||||
per_address_hour: 5,
|
||||
per_source_hour: 10,
|
||||
global_hour: 300,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Enabled email sign-in. Holds the server MAC key; deliberately not Debug.
|
||||
pub struct EmailAuth {
|
||||
key: [u8; 32],
|
||||
pub sender: Arc<dyn CodeSender>,
|
||||
pub limits: EmailLimits,
|
||||
}
|
||||
|
||||
impl EmailAuth {
|
||||
pub fn new(key: [u8; 32], sender: Arc<dyn CodeSender>) -> Self {
|
||||
Self {
|
||||
key,
|
||||
sender,
|
||||
limits: EmailLimits::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// HMAC-SHA256 under the server secret, domain separated and length prefixed so
|
||||
/// different field combinations can never produce the same input.
|
||||
pub fn mac(&self, domain: &str, parts: &[&str]) -> String {
|
||||
let mut mac = <Hmac<Sha256> as hmac::digest::KeyInit>::new_from_slice(&self.key)
|
||||
.expect("HMAC accepts any key length");
|
||||
for part in std::iter::once(domain).chain(parts.iter().copied()) {
|
||||
mac.update(&(part.len() as u64).to_be_bytes());
|
||||
mac.update(part.as_bytes());
|
||||
}
|
||||
hex::encode(mac.finalize().into_bytes())
|
||||
}
|
||||
|
||||
fn code_mac(&self, attempt_id: &str, email_mac: &str, code: &str) -> String {
|
||||
self.mac("vnox-email-code-v1", &[attempt_id, email_mac, code])
|
||||
}
|
||||
|
||||
pub fn email_mac(&self, email: &str) -> String {
|
||||
self.mac("vnox-email-address-v1", &[email])
|
||||
}
|
||||
|
||||
pub fn source_mac(&self, source: &str) -> String {
|
||||
self.mac("vnox-email-source-v1", &[source])
|
||||
}
|
||||
|
||||
/// Atomically checks every send budget and records the send in one statement, so
|
||||
/// concurrent requests cannot overshoot a limit.
|
||||
pub async fn reserve_send(
|
||||
&self,
|
||||
pool: &SqlitePool,
|
||||
email_mac: &str,
|
||||
source_mac: &str,
|
||||
) -> anyhow::Result<bool> {
|
||||
let t = now();
|
||||
let limits = self.limits;
|
||||
let result = sqlx::query(
|
||||
"INSERT INTO email_send_log(email_mac,source_mac,sent_at) SELECT ?,?,? WHERE \
|
||||
(SELECT COUNT(*) FROM email_send_log WHERE email_mac=? AND sent_at>?)=0 AND \
|
||||
(SELECT COUNT(*) FROM email_send_log WHERE email_mac=? AND sent_at>?)<? AND \
|
||||
(SELECT COUNT(*) FROM email_send_log WHERE source_mac=? AND sent_at>?)<? AND \
|
||||
(SELECT COUNT(*) FROM email_send_log WHERE sent_at>?)<?",
|
||||
)
|
||||
.bind(email_mac)
|
||||
.bind(source_mac)
|
||||
.bind(t)
|
||||
.bind(email_mac)
|
||||
.bind(t - limits.address_cooldown)
|
||||
.bind(email_mac)
|
||||
.bind(t - 3600)
|
||||
.bind(limits.per_address_hour)
|
||||
.bind(source_mac)
|
||||
.bind(t - 3600)
|
||||
.bind(limits.per_source_hour)
|
||||
.bind(t - 3600)
|
||||
.bind(limits.global_hour)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(result.rows_affected() == 1)
|
||||
}
|
||||
|
||||
/// Stores a new pending attempt, replacing the one bound to the browser's previous
|
||||
/// cookie (a resend). Returns the generated code. Fails when capacity is reached.
|
||||
pub async fn create_attempt(
|
||||
&self,
|
||||
pool: &SqlitePool,
|
||||
email: &str,
|
||||
browser: &str,
|
||||
previous_browser: Option<&str>,
|
||||
) -> anyhow::Result<(String, String)> {
|
||||
let mut transaction = pool.begin().await?;
|
||||
if let Some(previous) = previous_browser {
|
||||
sqlx::query("DELETE FROM email_attempts WHERE browser_hash=?")
|
||||
.bind(hash(previous))
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
let pending: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM email_attempts")
|
||||
.fetch_one(&mut *transaction)
|
||||
.await?;
|
||||
anyhow::ensure!(pending < MAX_PENDING, "email login capacity reached");
|
||||
let attempt_id = super::store::token();
|
||||
let code = generate_code();
|
||||
let email_mac = self.email_mac(email);
|
||||
sqlx::query(
|
||||
"INSERT INTO email_attempts(attempt_id,browser_hash,email_mac,code_mac,expires_at) VALUES(?,?,?,?,?)",
|
||||
)
|
||||
.bind(&attempt_id)
|
||||
.bind(hash(browser))
|
||||
.bind(&email_mac)
|
||||
.bind(self.code_mac(&attempt_id, &email_mac, &code))
|
||||
.bind(now() + CODE_TTL)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
Ok((attempt_id, code))
|
||||
}
|
||||
|
||||
pub async fn discard_attempt(&self, pool: &SqlitePool, attempt_id: &str) {
|
||||
let _ = sqlx::query("DELETE FROM email_attempts WHERE attempt_id=?")
|
||||
.bind(attempt_id)
|
||||
.execute(pool)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Checks a submitted code for the attempt bound to this browser.
|
||||
///
|
||||
/// The try counter is incremented by the same atomic statement that selects the row, so
|
||||
/// parallel guesses cannot exceed [`MAX_FAILURES`]. A correct code is consumed by a
|
||||
/// `DELETE ... RETURNING`: exactly one caller can win it. Every failure mode (missing,
|
||||
/// expired, exhausted, wrong address, wrong code) is reported identically.
|
||||
pub async fn verify(
|
||||
&self,
|
||||
pool: &SqlitePool,
|
||||
email: &str,
|
||||
code: &str,
|
||||
browser: &str,
|
||||
) -> anyhow::Result<bool> {
|
||||
let row: Option<(String, String, String, i64)> = sqlx::query_as(
|
||||
"UPDATE email_attempts SET failures=failures+1 WHERE browser_hash=? AND expires_at>? AND failures<? \
|
||||
RETURNING attempt_id,email_mac,code_mac,failures",
|
||||
)
|
||||
.bind(hash(browser))
|
||||
.bind(now())
|
||||
.bind(MAX_FAILURES)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
let Some((attempt_id, stored_email, stored_code, failures)) = row else {
|
||||
return Ok(false);
|
||||
};
|
||||
let email_ok = self
|
||||
.email_mac(email)
|
||||
.as_bytes()
|
||||
.ct_eq(stored_email.as_bytes());
|
||||
let code_ok = self
|
||||
.code_mac(&attempt_id, &stored_email, code)
|
||||
.as_bytes()
|
||||
.ct_eq(stored_code.as_bytes());
|
||||
if !bool::from(email_ok & code_ok) {
|
||||
if failures >= MAX_FAILURES {
|
||||
self.discard_attempt(pool, &attempt_id).await;
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
let consumed: Option<String> = sqlx::query_scalar(
|
||||
"DELETE FROM email_attempts WHERE attempt_id=? AND expires_at>? RETURNING attempt_id",
|
||||
)
|
||||
.bind(&attempt_id)
|
||||
.bind(now())
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(consumed.is_some())
|
||||
}
|
||||
}
|
||||
|
||||
/// Uniform eight-digit code from the OS-seeded CSPRNG, using rejection sampling to avoid
|
||||
/// modulo bias.
|
||||
pub fn generate_code() -> String {
|
||||
use rand::Rng;
|
||||
const SPAN: u64 = 10u64.pow(CODE_DIGITS as u32);
|
||||
const LIMIT: u64 = u64::MAX - u64::MAX % SPAN;
|
||||
loop {
|
||||
let mut bytes = [0u8; 8];
|
||||
rand::rng().fill_bytes(&mut bytes);
|
||||
let value = u64::from_le_bytes(bytes);
|
||||
if value < LIMIT {
|
||||
return format!("{:0width$}", value % SPAN, width = CODE_DIGITS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True for exactly eight ASCII digits.
|
||||
pub fn valid_code_shape(code: &str) -> bool {
|
||||
code.len() == CODE_DIGITS && code.bytes().all(|byte| byte.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// Trims and lowercases an address and accepts a deliberately conservative subset of RFC
|
||||
/// 5321: ASCII only, a dot-atom local part limited to `[a-z0-9._%+-]`, and a multi-label
|
||||
/// hostname whose last label is alphabetic (no IP literals). `+tags` are kept, so different
|
||||
/// tags are different identities. Unusual but legal addresses are rejected rather than
|
||||
/// risk look-alike or parser-differential identities.
|
||||
pub fn normalize_email(raw: &str) -> Option<String> {
|
||||
let value = raw.trim().to_ascii_lowercase();
|
||||
if value.len() > 254 || !value.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
let (local, domain) = value.split_once('@')?;
|
||||
if domain.contains('@') || local.is_empty() || local.len() > 64 {
|
||||
return None;
|
||||
}
|
||||
if local.starts_with('.')
|
||||
|| local.ends_with('.')
|
||||
|| local.contains("..")
|
||||
|| !local
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"._%+-".contains(&b))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if domain.len() > 253 {
|
||||
return None;
|
||||
}
|
||||
let labels: Vec<&str> = domain.split('.').collect();
|
||||
if labels.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
for label in &labels {
|
||||
if label.is_empty()
|
||||
|| label.len() > 63
|
||||
|| label.starts_with('-')
|
||||
|| label.ends_with('-')
|
||||
|| !label
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let tld = labels[labels.len() - 1];
|
||||
if tld.len() < 2 || !tld.bytes().all(|b| b.is_ascii_alphabetic()) {
|
||||
return None;
|
||||
}
|
||||
Some(value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hmac_sha256_matches_rfc_4231_case_2_construction() {
|
||||
// Sanity check of the primitive itself with the RFC 4231 test case 2 vector.
|
||||
let mut mac = <Hmac<Sha256> as hmac::digest::KeyInit>::new_from_slice(b"Jefe").unwrap();
|
||||
mac.update(b"what do ya want for nothing?");
|
||||
assert_eq!(
|
||||
hex::encode(mac.finalize().into_bytes()),
|
||||
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fields_are_domain_separated_and_unambiguous() {
|
||||
struct Nop;
|
||||
impl CodeSender for Nop {
|
||||
fn send<'a>(
|
||||
&'a self,
|
||||
_: &'a str,
|
||||
_: Email,
|
||||
) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'a>> {
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
}
|
||||
let auth = EmailAuth::new([7; 32], Arc::new(Nop));
|
||||
assert_ne!(auth.mac("a", &["bc"]), auth.mac("ab", &["c"]));
|
||||
assert_ne!(auth.mac("d", &["a", "bc"]), auth.mac("d", &["ab", "c"]));
|
||||
assert_ne!(auth.email_mac("x@y.zz"), auth.source_mac("x@y.zz"));
|
||||
let other = EmailAuth::new([8; 32], Arc::new(Nop));
|
||||
assert_ne!(auth.email_mac("x@y.zz"), other.email_mac("x@y.zz"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codes_are_eight_digits_and_vary() {
|
||||
let codes: std::collections::HashSet<String> = (0..64).map(|_| generate_code()).collect();
|
||||
assert!(codes.len() > 60);
|
||||
assert!(codes.iter().all(|code| valid_code_shape(code)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalization_accepts_and_rejects_expected_shapes() {
|
||||
assert_eq!(
|
||||
normalize_email(" Person.Name+Tag@Example.COM \n").as_deref(),
|
||||
Some("person.name+tag@example.com")
|
||||
);
|
||||
for bad in [
|
||||
"",
|
||||
"plain",
|
||||
"a@b",
|
||||
"a@@b.cc",
|
||||
"a@b@c.cc",
|
||||
"@b.cc",
|
||||
"a b@c.cc",
|
||||
".a@b.cc",
|
||||
"a.@b.cc",
|
||||
"a..b@c.cc",
|
||||
"\"a\"@b.cc",
|
||||
"a@b.c",
|
||||
"a@b.123",
|
||||
"a@[127.0.0.1]",
|
||||
"a@-b.cc",
|
||||
"a@b-.cc",
|
||||
"a@b..cc",
|
||||
"а@b.cc",
|
||||
"a@b.cc\r\nBcc: x@y.cc",
|
||||
"a<script>@b.cc",
|
||||
] {
|
||||
assert!(normalize_email(bad).is_none(), "{bad:?}");
|
||||
}
|
||||
assert!(normalize_email(&format!("{}@b.cc", "a".repeat(65))).is_none());
|
||||
assert!(normalize_email(&format!("a@{}.cc", "b".repeat(64))).is_none());
|
||||
assert!(normalize_email(&format!("a@{}.cc", "b.".repeat(130))).is_none());
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
pub mod email;
|
||||
pub mod provider;
|
||||
mod routes;
|
||||
pub mod store;
|
||||
|
|
@ -22,6 +23,8 @@ pub struct AuthService {
|
|||
pub pool: SqlitePool,
|
||||
pub origin: Url,
|
||||
pub provider: Option<Arc<dyn IdentityProvider>>,
|
||||
/// Present only when a mail transport is configured.
|
||||
pub email: Option<email::EmailAuth>,
|
||||
limits: Mutex<HashMap<String, (i64, u32)>>,
|
||||
}
|
||||
|
||||
|
|
@ -48,9 +51,18 @@ impl AuthService {
|
|||
pool,
|
||||
origin,
|
||||
provider,
|
||||
email: None,
|
||||
limits: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
/// Enables email sign-in. Callers do this only when SMTP is configured (or a test sender).
|
||||
pub fn with_email(mut self, email: email::EmailAuth) -> Self {
|
||||
self.email = Some(email);
|
||||
self
|
||||
}
|
||||
pub fn email_enabled(&self) -> bool {
|
||||
self.email.is_some()
|
||||
}
|
||||
pub fn configured(&self) -> bool {
|
||||
self.provider.is_some()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
use super::{AuthService, store};
|
||||
use crate::web::HubState;
|
||||
use super::{AuthService, email, store};
|
||||
use crate::{
|
||||
mail::{layout::Lang, templates},
|
||||
web::HubState,
|
||||
};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Query, State},
|
||||
extract::{DefaultBodyLimit, Query, State, rejection::JsonRejection},
|
||||
http::{HeaderMap, StatusCode, header},
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
routing::{get, post},
|
||||
|
|
@ -14,11 +17,20 @@ use serde_json::json;
|
|||
use std::sync::Arc;
|
||||
use subtle::ConstantTimeEq;
|
||||
const BROWSER: &str = "__Host-vnox_oauth";
|
||||
const EMAIL_BROWSER: &str = "__Host-vnox_email";
|
||||
const SESSION: &str = "__Host-vnox_session";
|
||||
pub fn router() -> Router<Arc<HubState>> {
|
||||
Router::new()
|
||||
.route("/v1/auth/github/start", get(start))
|
||||
.route("/v1/auth/github/callback", get(callback))
|
||||
.route(
|
||||
"/v1/auth/email/start",
|
||||
post(email_start).layer(DefaultBodyLimit::max(1024)),
|
||||
)
|
||||
.route(
|
||||
"/v1/auth/email/verify",
|
||||
post(email_verify).layer(DefaultBodyLimit::max(1024)),
|
||||
)
|
||||
.route("/v1/auth/session", get(session))
|
||||
.route("/v1/auth/logout", post(logout))
|
||||
}
|
||||
|
|
@ -61,15 +73,21 @@ fn set_cookie(response: &mut Response, name: &'static str, value: String, ttl: i
|
|||
.headers_mut()
|
||||
.append(header::SET_COOKIE, value.parse().expect("generated cookie"));
|
||||
}
|
||||
fn allowed(auth: &AuthService, headers: &HeaderMap) -> bool {
|
||||
fn client_ip(headers: &HeaderMap) -> String {
|
||||
// The loopback-only service trusts only the reverse proxy, which overwrites this header.
|
||||
let ip = headers
|
||||
headers
|
||||
.get("x-forwarded-for")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.parse::<std::net::IpAddr>().ok())
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_else(|| "local".into());
|
||||
auth.allow(&ip)
|
||||
.unwrap_or_else(|| "local".into())
|
||||
}
|
||||
fn allowed(auth: &AuthService, headers: &HeaderMap) -> bool {
|
||||
auth.allow(&client_ip(headers))
|
||||
}
|
||||
fn same_origin(auth: &AuthService, headers: &HeaderMap) -> bool {
|
||||
let origin = auth.origin.origin().ascii_serialization();
|
||||
headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) == Some(origin.as_str())
|
||||
}
|
||||
async fn start(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
|
||||
let auth = &state.auth;
|
||||
|
|
@ -129,16 +147,160 @@ async fn callback(
|
|||
let Ok((token, _)) = store::create_session(&auth.pool, &user.user_id).await else {
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
|
||||
};
|
||||
if let Some(old) = cookie(&headers, SESSION) {
|
||||
drop_old_session(auth, &headers).await;
|
||||
let mut response =
|
||||
Redirect::to(auth.origin.join("account").expect("fixed path").as_str()).into_response();
|
||||
set_cookie(&mut response, SESSION, token, store::SESSION_TTL);
|
||||
set_cookie(&mut response, BROWSER, String::new(), 0);
|
||||
response
|
||||
}
|
||||
/// A fresh login replaces any session the browser already holds (no session fixation).
|
||||
async fn drop_old_session(auth: &AuthService, headers: &HeaderMap) {
|
||||
if let Some(old) = cookie(headers, SESSION) {
|
||||
let _ = sqlx::query("DELETE FROM web_sessions WHERE token_hash=?")
|
||||
.bind(store::hash(&old))
|
||||
.execute(&auth.pool)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct EmailStart {
|
||||
email: String,
|
||||
lang: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct EmailVerify {
|
||||
email: String,
|
||||
code: String,
|
||||
}
|
||||
|
||||
/// Unauthenticated, state-changing POSTs have no session CSRF token to check. Instead:
|
||||
/// the exact `Origin` is required (browsers always send it on cross-origin POSTs), the body
|
||||
/// must be JSON (a non-simple request that cannot be forged by a plain form), and the code
|
||||
/// is bound to a random `__Host-` cookie created by `start`, so a code can only be redeemed
|
||||
/// by the browser that asked for it. A forged cross-site request can therefore neither
|
||||
/// plant an attacker's login in a victim's browser nor redeem a victim's code.
|
||||
async fn email_start(
|
||||
State(state): State<Arc<HubState>>,
|
||||
headers: HeaderMap,
|
||||
body: Result<Json<EmailStart>, JsonRejection>,
|
||||
) -> Response {
|
||||
let auth = &state.auth;
|
||||
let Some(mail) = &auth.email else {
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "email_not_configured");
|
||||
};
|
||||
if !same_origin(auth, &headers) {
|
||||
return failure(StatusCode::FORBIDDEN, "invalid_origin");
|
||||
}
|
||||
let Ok(Json(body)) = body else {
|
||||
return failure(StatusCode::BAD_REQUEST, "invalid_request");
|
||||
};
|
||||
if !allowed(auth, &headers) {
|
||||
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
|
||||
}
|
||||
let Some(address) = email::normalize_email(&body.email) else {
|
||||
return failure(StatusCode::BAD_REQUEST, "invalid_email");
|
||||
};
|
||||
let lang = Lang::from_tag(body.lang.as_deref());
|
||||
let source = mail.source_mac(&client_ip(&headers));
|
||||
let reserved = mail
|
||||
.reserve_send(&auth.pool, &mail.email_mac(&address), &source)
|
||||
.await;
|
||||
match reserved {
|
||||
Ok(true) => {}
|
||||
Ok(false) => return failure(StatusCode::TOO_MANY_REQUESTS, "try_later"),
|
||||
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
|
||||
}
|
||||
// Housekeeping failures must not block sign-in; expiry is enforced on every read.
|
||||
let _ = store::cleanup(&auth.pool).await;
|
||||
let browser = store::token();
|
||||
let previous = cookie(&headers, EMAIL_BROWSER);
|
||||
let Ok((attempt_id, code)) = mail
|
||||
.create_attempt(&auth.pool, &address, &browser, previous.as_deref())
|
||||
.await
|
||||
else {
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
|
||||
};
|
||||
let message = match templates::render_email_code(&auth.origin, &code, lang) {
|
||||
Ok(message) => message,
|
||||
Err(_) => {
|
||||
mail.discard_attempt(&auth.pool, &attempt_id).await;
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
|
||||
}
|
||||
};
|
||||
// Whether the address already has an account is never consulted here, so the response,
|
||||
// its timing and its cookie are identical for known and unknown addresses.
|
||||
let delivery = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(25),
|
||||
mail.sender.send(&address, message),
|
||||
)
|
||||
.await;
|
||||
if !matches!(delivery, Ok(Ok(()))) {
|
||||
mail.discard_attempt(&auth.pool, &attempt_id).await;
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
|
||||
}
|
||||
let mut response = (
|
||||
StatusCode::ACCEPTED,
|
||||
Json(json!({
|
||||
"status": "code_requested",
|
||||
"expires_in": email::CODE_TTL,
|
||||
"resend_after": mail.limits.address_cooldown
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
set_cookie(&mut response, EMAIL_BROWSER, browser, email::CODE_TTL);
|
||||
response
|
||||
}
|
||||
|
||||
async fn email_verify(
|
||||
State(state): State<Arc<HubState>>,
|
||||
headers: HeaderMap,
|
||||
body: Result<Json<EmailVerify>, JsonRejection>,
|
||||
) -> Response {
|
||||
let auth = &state.auth;
|
||||
let Some(mail) = &auth.email else {
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "email_not_configured");
|
||||
};
|
||||
if !same_origin(auth, &headers) {
|
||||
return failure(StatusCode::FORBIDDEN, "invalid_origin");
|
||||
}
|
||||
let Ok(Json(body)) = body else {
|
||||
return failure(StatusCode::BAD_REQUEST, "invalid_request");
|
||||
};
|
||||
if !allowed(auth, &headers) {
|
||||
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
|
||||
}
|
||||
let (Some(browser), Some(address)) = (
|
||||
cookie(&headers, EMAIL_BROWSER),
|
||||
email::normalize_email(&body.email),
|
||||
) else {
|
||||
return failure(StatusCode::BAD_REQUEST, "invalid_code");
|
||||
};
|
||||
if !email::valid_code_shape(&body.code) {
|
||||
return failure(StatusCode::BAD_REQUEST, "invalid_code");
|
||||
}
|
||||
match mail
|
||||
.verify(&auth.pool, &address, &body.code, &browser)
|
||||
.await
|
||||
{
|
||||
Ok(true) => {}
|
||||
Ok(false) => return failure(StatusCode::BAD_REQUEST, "invalid_code"),
|
||||
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
|
||||
}
|
||||
let Ok(user) = store::upsert_email_identity(&auth.pool, &address).await else {
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
|
||||
};
|
||||
let Ok((token, csrf)) = store::create_session(&auth.pool, &user.user_id).await else {
|
||||
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
|
||||
};
|
||||
drop_old_session(auth, &headers).await;
|
||||
let mut response =
|
||||
Redirect::to(auth.origin.join("account").expect("fixed path").as_str()).into_response();
|
||||
Json(json!({"authenticated":true,"user":user,"csrf_token":csrf})).into_response();
|
||||
set_cookie(&mut response, SESSION, token, store::SESSION_TTL);
|
||||
set_cookie(&mut response, BROWSER, String::new(), 0);
|
||||
set_cookie(&mut response, EMAIL_BROWSER, String::new(), 0);
|
||||
response
|
||||
}
|
||||
async fn session(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
|
||||
|
|
@ -155,8 +317,7 @@ async fn session(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Resp
|
|||
Json(json!({"authenticated":false})).into_response()
|
||||
}
|
||||
async fn logout(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
|
||||
let origin = state.auth.origin.origin().ascii_serialization();
|
||||
if headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) != Some(origin.as_str()) {
|
||||
if !same_origin(&state.auth, &headers) {
|
||||
return failure(StatusCode::FORBIDDEN, "invalid_origin");
|
||||
}
|
||||
let Some(token) = cookie(&headers, SESSION) else {
|
||||
|
|
|
|||
|
|
@ -41,6 +41,15 @@ pub async fn cleanup(pool: &SqlitePool) -> anyhow::Result<()> {
|
|||
.bind(now())
|
||||
.execute(pool)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM email_attempts WHERE expires_at<=?")
|
||||
.bind(now())
|
||||
.execute(pool)
|
||||
.await?;
|
||||
// The longest rate-limit window is one hour.
|
||||
sqlx::query("DELETE FROM email_send_log WHERE sent_at<=?")
|
||||
.bind(now() - 3600)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -70,13 +79,6 @@ pub async fn consume_attempt(
|
|||
}
|
||||
|
||||
pub async fn upsert_identity(pool: &SqlitePool, profile: &GitHubProfile) -> anyhow::Result<User> {
|
||||
let subject = profile.id.to_string();
|
||||
if let Some(user) = lookup_identity(pool, &subject).await? {
|
||||
return Ok(user);
|
||||
}
|
||||
let id = Uuid::new_v4();
|
||||
// Generated stable handle avoids claiming a privileged/reused handle from another provider.
|
||||
let handle = format!("u_{}", id.simple());
|
||||
let name = profile
|
||||
.name
|
||||
.as_deref()
|
||||
|
|
@ -92,6 +94,28 @@ pub async fn upsert_identity(pool: &SqlitePool, profile: &GitHubProfile) -> anyh
|
|||
&& url.password().is_none()
|
||||
})
|
||||
});
|
||||
upsert_external(pool, "github.com", &profile.id.to_string(), &name, avatar).await
|
||||
}
|
||||
|
||||
/// Account for a verified, normalized email address. The display name is deliberately
|
||||
/// neutral: the local part of an address must never become a public profile string.
|
||||
pub async fn upsert_email_identity(pool: &SqlitePool, email: &str) -> anyhow::Result<User> {
|
||||
upsert_external(pool, "email", email, "Vnox user", None).await
|
||||
}
|
||||
|
||||
async fn upsert_external(
|
||||
pool: &SqlitePool,
|
||||
provider: &str,
|
||||
subject: &str,
|
||||
name: &str,
|
||||
avatar: Option<&str>,
|
||||
) -> anyhow::Result<User> {
|
||||
if let Some(user) = lookup_identity(pool, provider, subject).await? {
|
||||
return Ok(user);
|
||||
}
|
||||
let id = Uuid::new_v4();
|
||||
// Generated stable handle avoids claiming a privileged/reused handle from another provider.
|
||||
let handle = format!("u_{}", id.simple());
|
||||
let mut transaction = pool.begin().await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO accounts(user_id,handle,created_at,display_name,avatar_url) VALUES(?,?,?,?,?)",
|
||||
|
|
@ -103,21 +127,25 @@ pub async fn upsert_identity(pool: &SqlitePool, profile: &GitHubProfile) -> anyh
|
|||
.bind(avatar)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
let inserted = sqlx::query("INSERT INTO external_identities(provider,subject,user_id,linked_at) VALUES('github.com',?,?,?) ON CONFLICT(provider,subject) DO NOTHING")
|
||||
.bind(&subject).bind(id.to_string()).bind(now()).execute(&mut *transaction).await?;
|
||||
let inserted = sqlx::query("INSERT INTO external_identities(provider,subject,user_id,linked_at) VALUES(?,?,?,?) ON CONFLICT(provider,subject) DO NOTHING")
|
||||
.bind(provider).bind(subject).bind(id.to_string()).bind(now()).execute(&mut *transaction).await?;
|
||||
if inserted.rows_affected() == 0 {
|
||||
transaction.rollback().await?;
|
||||
} else {
|
||||
transaction.commit().await?;
|
||||
}
|
||||
lookup_identity(pool, &subject)
|
||||
lookup_identity(pool, provider, subject)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("identity transaction failed"))
|
||||
}
|
||||
|
||||
async fn lookup_identity(pool: &SqlitePool, subject: &str) -> anyhow::Result<Option<User>> {
|
||||
Ok(sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,a.avatar_url FROM accounts a JOIN external_identities e ON e.user_id=a.user_id WHERE e.provider='github.com' AND e.subject=?")
|
||||
.bind(subject).fetch_optional(pool).await?)
|
||||
async fn lookup_identity(
|
||||
pool: &SqlitePool,
|
||||
provider: &str,
|
||||
subject: &str,
|
||||
) -> anyhow::Result<Option<User>> {
|
||||
Ok(sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,a.avatar_url FROM accounts a JOIN external_identities e ON e.user_id=a.user_id WHERE e.provider=? AND e.subject=?")
|
||||
.bind(provider).bind(subject).fetch_optional(pool).await?)
|
||||
}
|
||||
|
||||
pub async fn create_session(pool: &SqlitePool, user_id: &str) -> anyhow::Result<(String, String)> {
|
||||
|
|
|
|||
|
|
@ -72,6 +72,37 @@ impl Issuer {
|
|||
}
|
||||
}
|
||||
|
||||
/// Loads a 32-byte server secret stored as hex in a 0600 file, creating it from the OS
|
||||
/// CSPRNG on first use. The value is never logged and has no Debug/Serialize wrapper.
|
||||
pub fn load_or_create_secret(directory: &Path, name: &str) -> Result<[u8; 32]> {
|
||||
check_private_directory(directory)?;
|
||||
let path = directory.join(name);
|
||||
for _ in 0..2 {
|
||||
match OpenOptions::new().read(true).open(&path) {
|
||||
Ok(file) => {
|
||||
check_private_permissions(&file)?;
|
||||
if file.metadata()?.len() > 256 {
|
||||
bail!("Hub secret file exceeds the expected size");
|
||||
}
|
||||
let text = std::io::read_to_string(file).context("reading Hub secret file")?;
|
||||
return hex::decode(text.trim())
|
||||
.ok()
|
||||
.and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
|
||||
.context("Hub secret file has invalid encoding or length");
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
use rand::Rng;
|
||||
let mut bytes = [0u8; 32];
|
||||
rand::rng().fill_bytes(&mut bytes);
|
||||
// A concurrent creator winning the race is fine: the loop re-reads its file.
|
||||
let _ = persist_new_file(&path, hex::encode(bytes).as_bytes());
|
||||
}
|
||||
Err(error) => return Err(error).context("opening Hub secret file"),
|
||||
}
|
||||
}
|
||||
bail!("could not create Hub secret file")
|
||||
}
|
||||
|
||||
fn check_private_permissions(file: &std::fs::File) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
|
|
@ -97,6 +128,10 @@ fn check_private_directory(directory: &Path) -> Result<()> {
|
|||
// Publish a fully synced key file without replacing any concurrent issuer.
|
||||
// A failed first write must never leave a truncated final identity behind.
|
||||
fn persist_new_identity(path: &Path, identity: &StoredIdentity) -> Result<()> {
|
||||
persist_new_file(path, &serde_json::to_vec_pretty(identity)?)
|
||||
}
|
||||
|
||||
fn persist_new_file(path: &Path, contents: &[u8]) -> Result<()> {
|
||||
let temporary = path.with_extension(format!("{}.tmp", Uuid::new_v4()));
|
||||
let result = (|| -> Result<()> {
|
||||
let mut options = OpenOptions::new();
|
||||
|
|
@ -110,7 +145,7 @@ fn persist_new_identity(path: &Path, identity: &StoredIdentity) -> Result<()> {
|
|||
let mut file = options
|
||||
.open(&temporary)
|
||||
.context("preparing Hub issuer identity")?;
|
||||
file.write_all(&serde_json::to_vec_pretty(identity)?)
|
||||
file.write_all(contents)
|
||||
.context("writing Hub issuer identity")?;
|
||||
file.sync_all().context("syncing Hub issuer identity")?;
|
||||
}
|
||||
|
|
@ -129,6 +164,43 @@ fn persist_new_identity(path: &Path, identity: &StoredIdentity) -> Result<()> {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn generated_secret_is_stable_private_and_validated() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
|
||||
.unwrap();
|
||||
}
|
||||
let first = load_or_create_secret(directory.path(), "s.key").unwrap();
|
||||
assert_eq!(
|
||||
first,
|
||||
load_or_create_secret(directory.path(), "s.key").unwrap()
|
||||
);
|
||||
assert_ne!(first, [0; 32]);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(directory.path().join("s.key"))
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode();
|
||||
assert_eq!(mode & 0o077, 0);
|
||||
}
|
||||
std::fs::write(directory.path().join("bad.key"), "zz").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(
|
||||
directory.path().join("bad.key"),
|
||||
std::fs::Permissions::from_mode(0o600),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert!(load_or_create_secret(directory.path(), "bad.key").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publishing_never_overwrites_an_existing_identity_or_leaves_temp_files() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
|
|
@ -8,14 +8,44 @@ pub fn escape(value: &str) -> String {
|
|||
.replace('\'', "'")
|
||||
}
|
||||
|
||||
/// Language of the fixed layout chrome (tagline, footer, hints).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Lang {
|
||||
Ru,
|
||||
En,
|
||||
}
|
||||
|
||||
impl Lang {
|
||||
/// Parses a client supplied language tag; anything unknown falls back to Russian.
|
||||
pub fn from_tag(tag: Option<&str>) -> Self {
|
||||
match tag {
|
||||
Some("en") => Self::En,
|
||||
_ => Self::Ru,
|
||||
}
|
||||
}
|
||||
pub fn tag(self) -> &'static str {
|
||||
match self {
|
||||
Self::Ru => "ru",
|
||||
Self::En => "en",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Optional call-to-action. Code messages deliberately carry none.
|
||||
pub struct Link<'a> {
|
||||
pub button: &'a str,
|
||||
pub url: &'a str,
|
||||
}
|
||||
|
||||
pub struct Content<'a> {
|
||||
pub lang: Lang,
|
||||
pub title: &'a str,
|
||||
pub preheader: &'a str,
|
||||
pub paragraphs: &'a [&'a str],
|
||||
pub code: Option<&'a str>,
|
||||
pub button: &'a str,
|
||||
pub url: &'a str,
|
||||
pub link: Option<Link<'a>>,
|
||||
pub expiry: &'a str,
|
||||
pub warning: &'a str,
|
||||
pub origin: &'a str,
|
||||
}
|
||||
|
||||
|
|
@ -33,27 +63,51 @@ pub fn render(content: &Content<'_>) -> String {
|
|||
.collect::<String>();
|
||||
let code = content.code.map(|value| format!("<p style=\"margin:22px 0;padding:18px;background:#111112;border:1px solid #494238;border-radius:10px;font-family:Consolas,monospace;font-size:30px;font-weight:700;letter-spacing:6px;text-align:center;color:#f0d7ae\">{}</p>", escape(value))).unwrap_or_default();
|
||||
let title = escape(content.title);
|
||||
let url = escape(content.url);
|
||||
let (tagline, automatic) = match content.lang {
|
||||
Lang::Ru => (
|
||||
"Личное пространство для общения",
|
||||
"Автоматическое письмо Vnox. Отвечать на него не нужно.",
|
||||
),
|
||||
Lang::En => (
|
||||
"A personal space to talk",
|
||||
"Automatic message from Vnox. No need to reply.",
|
||||
),
|
||||
};
|
||||
let link = content
|
||||
.link
|
||||
.as_ref()
|
||||
.map(|link| {
|
||||
let url = escape(link.url);
|
||||
let button = escape(link.button);
|
||||
let hint = match content.lang {
|
||||
Lang::Ru => "Если кнопка не открывается, скопируй ссылку:",
|
||||
Lang::En => "If the button does not open, copy the link:",
|
||||
};
|
||||
format!(
|
||||
r##"<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:23px 0 17px"><tr><td bgcolor="#d5b58a" style="border-radius:9px"><a href="{url}" style="display:inline-block;padding:14px 26px;color:#231d16;text-decoration:none;font-size:15px;font-weight:700;border-radius:9px">{button}</a></td></tr></table>
|
||||
<p style="margin:0 0 9px;font-size:12px;color:#aca49a">{hint}</p>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td bgcolor="#171718" style="padding:13px;border:1px solid #3c3732;border-radius:9px;word-break:break-all;font-size:12px;line-height:20px"><a href="{url}" style="color:#d8bd98;text-decoration:none">{url}</a></td></tr></table>"##
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let origin = escape(content.origin);
|
||||
format!(
|
||||
r##"<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark light"><title>{title}</title></head>
|
||||
r##"<!doctype html><html lang="{lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark light"><title>{title}</title></head>
|
||||
<body style="margin:0;padding:0;background:#101011" bgcolor="#101011">
|
||||
<div style="display:none;max-height:0;overflow:hidden;opacity:0">{preheader}</div>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#101011"><tr><td align="center" style="padding:32px 12px">
|
||||
<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" bgcolor="#1c1c1e" style="width:100%;max-width:600px;border:1px solid #383634;border-radius:18px;overflow:hidden;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Arial,sans-serif">
|
||||
<tr><td bgcolor="#38312a" style="background:#38312a;background-image:linear-gradient(125deg,#514033 0%,#39312c 55%,#242426 100%);padding:30px 32px 32px">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td width="42" height="42" align="center" bgcolor="#151516" style="border-radius:11px;color:#e8d5b8;font-size:19px;font-weight:800"><img src="{origin}/assets/vnox-mark.png" width="42" height="42" alt="V" style="display:block;border:0;border-radius:11px"></td><td style="padding-left:12px;color:#f6f0e7;font-size:23px;font-weight:700">Vnox</td></tr></table>
|
||||
<p style="margin:25px 0 10px;color:#d1b998;font-size:12px">Личное пространство для общения</p>
|
||||
<p style="margin:25px 0 10px;color:#d1b998;font-size:12px">{tagline}</p>
|
||||
<h1 style="margin:0;color:#fff9ef;font-size:28px;line-height:35px;font-weight:700">{title}</h1>
|
||||
</td></tr><tr><td style="padding:32px 32px 12px">{paragraphs}{code}
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:23px 0 17px"><tr><td bgcolor="#d5b58a" style="border-radius:9px"><a href="{url}" style="display:inline-block;padding:14px 26px;color:#231d16;text-decoration:none;font-size:15px;font-weight:700;border-radius:9px">{button}</a></td></tr></table>
|
||||
</td></tr><tr><td style="padding:32px 32px 12px">{paragraphs}{code}{link}
|
||||
<p style="margin:0 0 24px;font-size:13px;line-height:21px;color:#aca49a">{expiry}</p>
|
||||
<p style="margin:0 0 9px;font-size:12px;color:#aca49a">Если кнопка не открывается, скопируй ссылку:</p>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td bgcolor="#171718" style="padding:13px;border:1px solid #3c3732;border-radius:9px;word-break:break-all;font-size:12px;line-height:20px"><a href="{url}" style="color:#d8bd98;text-decoration:none">{url}</a></td></tr></table>
|
||||
<p style="margin:26px 0 18px;font-size:13px;line-height:21px;color:#aca49a">Не запрашивал это действие? Не передавай код или ссылку другим людям. Если это письмо о новом устройстве, проверь активные сеансы.</p>
|
||||
</td></tr><tr><td bgcolor="#171718" style="border-top:1px solid #383634;padding:21px 32px;color:#9e978d;font-size:12px;line-height:20px">Автоматическое письмо Vnox. Отвечать на него не нужно.<br><a href="{origin}" style="color:#d8bd98;text-decoration:none">{origin}</a></td></tr></table></td></tr></table></body></html>"##,
|
||||
<p style="margin:26px 0 18px;font-size:13px;line-height:21px;color:#aca49a">{warning}</p>
|
||||
</td></tr><tr><td bgcolor="#171718" style="border-top:1px solid #383634;padding:21px 32px;color:#9e978d;font-size:12px;line-height:20px">{automatic}<br><a href="{origin}" style="color:#d8bd98;text-decoration:none">{origin}</a></td></tr></table></td></tr></table></body></html>"##,
|
||||
lang = content.lang.tag(),
|
||||
preheader = escape(content.preheader),
|
||||
button = escape(content.button),
|
||||
expiry = escape(content.expiry),
|
||||
warning = escape(content.warning),
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use anyhow::{Result, bail};
|
||||
use url::Url;
|
||||
|
||||
use super::layout::{self, Content};
|
||||
use super::layout::{self, Content, Lang, Link};
|
||||
use crate::config::parse_origin;
|
||||
|
||||
/// A rendered transactional message; no recipient or delivery happens here.
|
||||
|
|
@ -70,13 +70,17 @@ pub fn render(origin: &Url, kind: Kind<'_>) -> Result<Email> {
|
|||
let paragraph_refs = paragraphs.iter().map(String::as_str).collect::<Vec<_>>();
|
||||
let origin_text = origin.as_str().trim_end_matches('/');
|
||||
let content = Content {
|
||||
lang: Lang::Ru,
|
||||
title,
|
||||
preheader: title,
|
||||
paragraphs: ¶graph_refs,
|
||||
code,
|
||||
button,
|
||||
url: url.as_str(),
|
||||
link: Some(Link {
|
||||
button,
|
||||
url: url.as_str(),
|
||||
}),
|
||||
expiry,
|
||||
warning: "Не запрашивал это действие? Не передавай код или ссылку другим людям. Если это письмо о новом устройстве, проверь активные сеансы.",
|
||||
origin: origin_text,
|
||||
};
|
||||
let text = format!(
|
||||
|
|
@ -93,6 +97,54 @@ pub fn render(origin: &Url, kind: Kind<'_>) -> Result<Email> {
|
|||
})
|
||||
}
|
||||
|
||||
/// Sign-in code message for the passwordless email flow. It carries no link and no
|
||||
/// button: the code is typed into the page that requested it, never opened from a URL.
|
||||
pub fn render_email_code(origin: &Url, code: &str, lang: Lang) -> Result<Email> {
|
||||
parse_origin(origin.as_str())?;
|
||||
if code.len() != 8 || !code.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
bail!("email code must contain exactly eight ASCII digits");
|
||||
}
|
||||
let (title, paragraph, expiry, warning, subject, label) = match lang {
|
||||
Lang::Ru => (
|
||||
"Код для входа в Vnox",
|
||||
"Введи этот код на странице входа. Он подойдёт только в том браузере, где ты запросил вход.",
|
||||
"Код действует 10 минут и срабатывает один раз.",
|
||||
"Не запрашивал вход? Просто проигнорируй письмо и никому не сообщай код.",
|
||||
"Vnox: код для входа",
|
||||
"Код",
|
||||
),
|
||||
Lang::En => (
|
||||
"Your Vnox sign-in code",
|
||||
"Enter this code on the sign-in page. It only works in the browser where you asked to sign in.",
|
||||
"The code is valid for 10 minutes and works once.",
|
||||
"Did not ask to sign in? Ignore this message and never share the code.",
|
||||
"Vnox: sign-in code",
|
||||
"Code",
|
||||
),
|
||||
};
|
||||
let origin_text = origin.as_str().trim_end_matches('/');
|
||||
let paragraphs = [paragraph];
|
||||
let html = layout::render(&Content {
|
||||
lang,
|
||||
title,
|
||||
preheader: title,
|
||||
paragraphs: ¶graphs,
|
||||
code: Some(code),
|
||||
link: None,
|
||||
expiry,
|
||||
warning,
|
||||
origin: origin_text,
|
||||
});
|
||||
let text = format!(
|
||||
"Vnox\n\n{title}\n\n{paragraph}\n\n{label}: {code}\n\n{expiry}\n\n{warning}\n\n{origin_text}\n"
|
||||
);
|
||||
Ok(Email {
|
||||
subject: subject.to_owned(),
|
||||
text,
|
||||
html,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write_previews(directory: &std::path::Path, origin: &Url) -> Result<()> {
|
||||
std::fs::create_dir_all(directory)?;
|
||||
for (name, kind) in [
|
||||
|
|
|
|||
|
|
@ -43,15 +43,20 @@ async fn main() -> Result<()> {
|
|||
let database = database::open(&config.data_dir, &issuer).await?;
|
||||
// Validate configured SMTP eagerly without making startup depend on the
|
||||
// availability of an external provider. There is no public mail endpoint.
|
||||
// Email sign-in is enabled exactly when SMTP is configured. The code MAC key lives in
|
||||
// the private data directory next to the issuer identity and is generated on first use.
|
||||
let mut auth = vnox_hub::auth::AuthService::new(
|
||||
database.clone(),
|
||||
config.origin.clone(),
|
||||
config.github.as_ref(),
|
||||
)?;
|
||||
if let Some(smtp) = &config.smtp {
|
||||
mail::Mailer::new(smtp)?;
|
||||
let mailer = Arc::new(mail::Mailer::new(smtp)?);
|
||||
let key = vnox_hub::identity::load_or_create_secret(&config.data_dir, "email-auth.key")?;
|
||||
auth = auth.with_email(vnox_hub::auth::email::EmailAuth::new(key, mailer));
|
||||
}
|
||||
let state = Arc::new(web::HubState {
|
||||
auth: Arc::new(vnox_hub::auth::AuthService::new(
|
||||
database.clone(),
|
||||
config.origin.clone(),
|
||||
config.github.as_ref(),
|
||||
)?),
|
||||
auth: Arc::new(auth),
|
||||
database,
|
||||
issuer,
|
||||
smtp_configured: config.smtp.is_some(),
|
||||
|
|
|
|||
|
|
@ -75,7 +75,7 @@ async fn info(State(state): State<Arc<HubState>>) -> Json<Value> {
|
|||
"uptime_seconds": state.started.elapsed().as_secs(),
|
||||
"smtp": {"configured": state.smtp_configured, "public_send_endpoint": false},
|
||||
"capabilities": {
|
||||
"email_auth": "not_enabled",
|
||||
"email_auth": if state.auth.email_enabled() { "enabled" } else { "not_enabled" },
|
||||
"github_auth": if state.auth.configured() { "enabled" } else { "not_enabled" },
|
||||
"server_registry": "not_enabled",
|
||||
"friends": "not_enabled",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue