feat(hub): add central service foundation and transactional mail
This commit is contained in:
parent
b14f036bdb
commit
a811de590a
25 changed files with 1521 additions and 4 deletions
99
hub/src/config.rs
Normal file
99
hub/src/config.rs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
use std::{net::SocketAddr, path::PathBuf};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use url::Url;
|
||||
|
||||
/// Public deployment configuration. Secret-bearing SMTP fields are intentionally not Debug.
|
||||
pub struct Config {
|
||||
pub bind: SocketAddr,
|
||||
pub data_dir: PathBuf,
|
||||
pub origin: Url,
|
||||
pub smtp: Option<SmtpConfig>,
|
||||
}
|
||||
|
||||
/// SMTP credentials are only read from the service environment, never command arguments.
|
||||
pub struct SmtpConfig {
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub user: String,
|
||||
pub password: String,
|
||||
pub from: String,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn from_env() -> Result<Self> {
|
||||
Self::from_lookup(|name| std::env::var(name).ok())
|
||||
}
|
||||
|
||||
pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Result<Self> {
|
||||
let bind = get("HUB_BIND")
|
||||
.unwrap_or_else(|| "127.0.0.1:17843".into())
|
||||
.parse::<SocketAddr>()
|
||||
.context("HUB_BIND must be an IP address and port")?;
|
||||
if !bind.ip().is_loopback() {
|
||||
bail!("HUB_BIND must be loopback; terminate HTTPS at the reverse proxy");
|
||||
}
|
||||
let origin = parse_origin(
|
||||
&get("PUBLIC_BASE_URL").unwrap_or_else(|| "https://central.loki-code.dev".into()),
|
||||
)?;
|
||||
let smtp_host = get("SMTP_HOST").unwrap_or_default();
|
||||
let smtp = if smtp_host.trim().is_empty() {
|
||||
if ["SMTP_USER", "SMTP_PASSWORD", "SMTP_PORT"]
|
||||
.iter()
|
||||
.any(|name| get(name).is_some_and(|value| !value.trim().is_empty()))
|
||||
{
|
||||
bail!("SMTP credentials/port require SMTP_HOST");
|
||||
}
|
||||
None
|
||||
} else {
|
||||
let port = get("SMTP_PORT")
|
||||
.unwrap_or_else(|| "587".into())
|
||||
.parse::<u16>()
|
||||
.context("SMTP_PORT must be a number")?;
|
||||
let user = get("SMTP_USER").unwrap_or_default();
|
||||
let password = get("SMTP_PASSWORD").unwrap_or_default();
|
||||
if user.is_empty() != password.is_empty() {
|
||||
bail!("SMTP_USER and SMTP_PASSWORD must be configured together");
|
||||
}
|
||||
if smtp_host.chars().any(char::is_whitespace)
|
||||
|| smtp_host.contains('/')
|
||||
|| smtp_host.contains('@')
|
||||
{
|
||||
bail!("SMTP_HOST must be a hostname, not a URL");
|
||||
}
|
||||
if port == 0 {
|
||||
bail!("SMTP_PORT cannot be zero");
|
||||
}
|
||||
Some(SmtpConfig {
|
||||
host: smtp_host,
|
||||
port,
|
||||
user,
|
||||
password,
|
||||
from: get("MAIL_FROM").unwrap_or_else(|| "Vnox <noreply@loki-code.dev>".into()),
|
||||
})
|
||||
};
|
||||
Ok(Self {
|
||||
bind,
|
||||
origin,
|
||||
smtp,
|
||||
data_dir: get("HUB_DATA_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("./dev/hub-data")),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_origin(value: &str) -> Result<Url> {
|
||||
let url = Url::parse(value).context("PUBLIC_BASE_URL must be an HTTPS origin")?;
|
||||
if url.scheme() != "https"
|
||||
|| url.host_str().is_none()
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
|| url.query().is_some()
|
||||
|| url.fragment().is_some()
|
||||
|| url.path() != "/"
|
||||
{
|
||||
bail!("PUBLIC_BASE_URL must be an HTTPS origin without credentials, path or query");
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
44
hub/src/database.rs
Normal file
44
hub/src/database.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
use std::{path::Path, time::Duration};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use sqlx::{SqlitePool, sqlite::SqliteConnectOptions};
|
||||
|
||||
use crate::identity::Issuer;
|
||||
|
||||
pub async fn open(directory: &Path, issuer: &Issuer) -> Result<SqlitePool> {
|
||||
let options = SqliteConnectOptions::new()
|
||||
.filename(directory.join("hub.sqlite3"))
|
||||
.create_if_missing(true)
|
||||
.foreign_keys(true)
|
||||
.busy_timeout(Duration::from_secs(5));
|
||||
let pool = sqlx::sqlite::SqlitePoolOptions::new()
|
||||
.max_connections(4)
|
||||
.acquire_timeout(Duration::from_secs(5))
|
||||
.connect_with(options)
|
||||
.await
|
||||
.context("opening Hub database")?;
|
||||
sqlx::migrate!("./migrations")
|
||||
.run(&pool)
|
||||
.await
|
||||
.context("migrating Hub database")?;
|
||||
let mut transaction = pool.begin().await?;
|
||||
for (name, value) in [
|
||||
("issuer_id", issuer.id.to_string()),
|
||||
("issuer_public_key", issuer.public_key.clone()),
|
||||
] {
|
||||
sqlx::query("INSERT OR IGNORE INTO hub_metadata(key,value) VALUES (?,?)")
|
||||
.bind(name)
|
||||
.bind(&value)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
let existing: String = sqlx::query_scalar("SELECT value FROM hub_metadata WHERE key=?")
|
||||
.bind(name)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await?;
|
||||
if existing != value {
|
||||
bail!("Hub database and issuer identity do not match; restore them together");
|
||||
}
|
||||
}
|
||||
transaction.commit().await?;
|
||||
Ok(pool)
|
||||
}
|
||||
148
hub/src/identity.rs
Normal file
148
hub/src/identity.rs
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
use std::{fs::OpenOptions, io::Write, path::Path};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use ed25519_dalek::SigningKey;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StoredIdentity {
|
||||
version: u32,
|
||||
issuer_id: Uuid,
|
||||
secret_key: String,
|
||||
public_key: String,
|
||||
}
|
||||
|
||||
/// Stable issuer identity. Only its public projection is exposed through HTTP.
|
||||
pub struct Issuer {
|
||||
pub id: Uuid,
|
||||
pub public_key: String,
|
||||
}
|
||||
|
||||
impl Issuer {
|
||||
pub fn load_or_create(directory: &Path) -> Result<Self> {
|
||||
let mut builder = std::fs::DirBuilder::new();
|
||||
builder.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
builder.mode(0o700);
|
||||
}
|
||||
builder
|
||||
.create(directory)
|
||||
.context("creating Hub data directory")?;
|
||||
check_private_directory(directory)?;
|
||||
let path = directory.join("issuer.json");
|
||||
let stored = match OpenOptions::new().read(true).open(&path) {
|
||||
Ok(file) => {
|
||||
check_private_permissions(&file)?;
|
||||
if file.metadata()?.len() > 4096 {
|
||||
bail!("Hub issuer identity exceeds the expected size");
|
||||
}
|
||||
let value: StoredIdentity =
|
||||
serde_json::from_reader(file).context("reading Hub issuer identity")?;
|
||||
value
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
let key = SigningKey::generate(&mut rand::rng());
|
||||
let value = StoredIdentity {
|
||||
version: 1,
|
||||
issuer_id: Uuid::new_v4(),
|
||||
secret_key: hex::encode(key.to_bytes()),
|
||||
public_key: hex::encode(key.verifying_key().to_bytes()),
|
||||
};
|
||||
persist_new_identity(&path, &value)?;
|
||||
value
|
||||
}
|
||||
Err(error) => return Err(error).context("opening Hub issuer identity"),
|
||||
};
|
||||
let secret = hex::decode(&stored.secret_key)
|
||||
.ok()
|
||||
.and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
|
||||
.context("Hub issuer private key has invalid encoding or length")?;
|
||||
let key = SigningKey::from_bytes(&secret);
|
||||
if stored.version != 1 || hex::encode(key.verifying_key().to_bytes()) != stored.public_key {
|
||||
bail!("Hub issuer identity failed integrity validation");
|
||||
}
|
||||
Ok(Self {
|
||||
id: stored.issuer_id,
|
||||
public_key: stored.public_key,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn check_private_permissions(file: &std::fs::File) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if file.metadata()?.permissions().mode() & 0o077 != 0 {
|
||||
bail!("Hub issuer identity must not be accessible to group/other users (use 0600)");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_private_directory(directory: &Path) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if std::fs::metadata(directory)?.permissions().mode() & 0o077 != 0 {
|
||||
bail!("Hub data directory must be private (use 0700)");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 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<()> {
|
||||
let temporary = path.with_extension(format!("{}.tmp", Uuid::new_v4()));
|
||||
let result = (|| -> Result<()> {
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
{
|
||||
let mut file = options
|
||||
.open(&temporary)
|
||||
.context("preparing Hub issuer identity")?;
|
||||
file.write_all(&serde_json::to_vec_pretty(identity)?)
|
||||
.context("writing Hub issuer identity")?;
|
||||
file.sync_all().context("syncing Hub issuer identity")?;
|
||||
}
|
||||
std::fs::hard_link(&temporary, path).context("publishing new Hub issuer identity")?;
|
||||
#[cfg(unix)]
|
||||
std::fs::File::open(path.parent().context("issuer directory is missing")?)?
|
||||
.sync_all()
|
||||
.context("syncing Hub issuer directory")?;
|
||||
Ok(())
|
||||
})();
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn publishing_never_overwrites_an_existing_identity_or_leaves_temp_files() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("issuer.json");
|
||||
std::fs::write(&path, b"existing issuer").unwrap();
|
||||
let key = SigningKey::generate(&mut rand::rng());
|
||||
let candidate = StoredIdentity {
|
||||
version: 1,
|
||||
issuer_id: Uuid::new_v4(),
|
||||
secret_key: hex::encode(key.to_bytes()),
|
||||
public_key: hex::encode(key.verifying_key().to_bytes()),
|
||||
};
|
||||
assert!(persist_new_identity(&path, &candidate).is_err());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"existing issuer");
|
||||
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
|
||||
}
|
||||
}
|
||||
5
hub/src/lib.rs
Normal file
5
hub/src/lib.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
pub mod config;
|
||||
pub mod database;
|
||||
pub mod identity;
|
||||
pub mod mail;
|
||||
pub mod web;
|
||||
59
hub/src/mail/layout.rs
Normal file
59
hub/src/mail/layout.rs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
/// Escape all dynamic HTML, including attribute values.
|
||||
pub fn escape(value: &str) -> String {
|
||||
value
|
||||
.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
.replace('\'', "'")
|
||||
}
|
||||
|
||||
pub struct Content<'a> {
|
||||
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 expiry: &'a str,
|
||||
pub origin: &'a str,
|
||||
}
|
||||
|
||||
/// Table-based inline HTML with a solid-color fallback for gradient support.
|
||||
pub fn render(content: &Content<'_>) -> String {
|
||||
let paragraphs = content
|
||||
.paragraphs
|
||||
.iter()
|
||||
.map(|value| {
|
||||
format!(
|
||||
"<p style=\"margin:0 0 16px;font-size:16px;line-height:26px;color:#eae6df\">{}</p>",
|
||||
escape(value)
|
||||
)
|
||||
})
|
||||
.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 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>
|
||||
<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>
|
||||
<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>
|
||||
<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>"##,
|
||||
preheader = escape(content.preheader),
|
||||
button = escape(content.button),
|
||||
expiry = escape(content.expiry),
|
||||
)
|
||||
}
|
||||
65
hub/src/mail/mod.rs
Normal file
65
hub/src/mail/mod.rs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
pub mod layout;
|
||||
pub mod templates;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use lettre::{
|
||||
AsyncSmtpTransport, AsyncTransport, Tokio1Executor,
|
||||
message::{Mailbox, Message, MultiPart},
|
||||
transport::smtp::authentication::Credentials,
|
||||
};
|
||||
|
||||
use crate::config::SmtpConfig;
|
||||
|
||||
/// TLS-only SMTP transport, deliberately without Debug or credential logging.
|
||||
pub struct Mailer {
|
||||
transport: AsyncSmtpTransport<Tokio1Executor>,
|
||||
from: Mailbox,
|
||||
}
|
||||
|
||||
impl Mailer {
|
||||
pub fn new(config: &SmtpConfig) -> Result<Self> {
|
||||
let builder = if config.port == 465 {
|
||||
AsyncSmtpTransport::<Tokio1Executor>::relay(&config.host)
|
||||
} else {
|
||||
AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&config.host)
|
||||
}
|
||||
.context("invalid SMTP TLS hostname")?;
|
||||
let mut builder = builder
|
||||
.port(config.port)
|
||||
.timeout(Some(Duration::from_secs(15)));
|
||||
if !config.user.is_empty() {
|
||||
builder = builder.credentials(Credentials::new(
|
||||
config.user.clone(),
|
||||
config.password.clone(),
|
||||
));
|
||||
}
|
||||
Ok(Self {
|
||||
transport: builder.build(),
|
||||
from: config.from.parse().context("MAIL_FROM must be a mailbox")?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Connect, negotiate TLS, authenticate and issue NOOP; never sends a message.
|
||||
pub async fn check_connection(&self) -> Result<()> {
|
||||
match self.transport.test_connection().await {
|
||||
Ok(true) => Ok(()),
|
||||
Ok(false) | Err(_) => bail!("SMTP TLS/authentication check failed"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal transport only. There is intentionally no public send-email HTTP endpoint.
|
||||
pub async fn deliver(&self, recipient: &str, email: templates::Email) -> Result<()> {
|
||||
let message = Message::builder()
|
||||
.from(self.from.clone())
|
||||
.to(recipient.parse().context("invalid recipient mailbox")?)
|
||||
.subject(email.subject)
|
||||
.multipart(MultiPart::alternative_plain_html(email.text, email.html))?;
|
||||
self.transport
|
||||
.send(message)
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("SMTP delivery failed"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
118
hub/src/mail/templates.rs
Normal file
118
hub/src/mail/templates.rs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
use anyhow::{Result, bail};
|
||||
use url::Url;
|
||||
|
||||
use super::layout::{self, Content};
|
||||
use crate::config::parse_origin;
|
||||
|
||||
/// A rendered transactional message; no recipient or delivery happens here.
|
||||
pub struct Email {
|
||||
pub subject: String,
|
||||
pub text: String,
|
||||
pub html: String,
|
||||
}
|
||||
|
||||
pub enum Kind<'a> {
|
||||
Verify { token: &'a str },
|
||||
Login { code: &'a str },
|
||||
NewDevice { device: &'a str },
|
||||
}
|
||||
|
||||
pub fn render(origin: &Url, kind: Kind<'_>) -> Result<Email> {
|
||||
parse_origin(origin.as_str())?;
|
||||
let (title, paragraphs, code, button, path, expiry) = match kind {
|
||||
Kind::Verify { token } => {
|
||||
if token.is_empty() || token.len() > 512 {
|
||||
bail!("invalid verification token length");
|
||||
}
|
||||
(
|
||||
"Подтверди свою почту",
|
||||
vec!["Добро пожаловать в Vnox!".to_owned(), "Подтверди адрес, чтобы завершить настройку профиля и пользоваться глобальными функциями.".to_owned()],
|
||||
None,
|
||||
"Подтвердить почту",
|
||||
("verify-email", Some(("token", token))),
|
||||
"Ссылка действует 24 часа и может быть использована только один раз.",
|
||||
)
|
||||
}
|
||||
Kind::Login { code } => {
|
||||
if code.len() != 8 || !code.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
bail!("login code must contain exactly eight ASCII digits");
|
||||
}
|
||||
(
|
||||
"Твой код входа",
|
||||
vec![
|
||||
"Используй этот одноразовый код, чтобы войти в Vnox. Никому его не сообщай."
|
||||
.to_owned(),
|
||||
],
|
||||
Some(code),
|
||||
"Открыть Vnox",
|
||||
("login", None),
|
||||
"Код действует 10 минут. Он не продлевается при повторном открытии письма.",
|
||||
)
|
||||
}
|
||||
Kind::NewDevice { device } => {
|
||||
if device.is_empty() || device.len() > 200 || device.chars().any(char::is_control) {
|
||||
bail!("invalid device description");
|
||||
}
|
||||
(
|
||||
"Новое устройство в аккаунте",
|
||||
vec![format!("К твоему аккаунту подключено устройство: {device}."), "Если это был не ты, проверь список устройств и отзови доступ незнакомого сеанса.".to_owned()],
|
||||
None,
|
||||
"Проверить устройства",
|
||||
("account/devices", None),
|
||||
"Уведомление не содержит ключей или токенов доступа.",
|
||||
)
|
||||
}
|
||||
};
|
||||
let mut url = origin.join(path.0)?;
|
||||
if let Some((name, value)) = path.1 {
|
||||
url.query_pairs_mut().append_pair(name, value);
|
||||
}
|
||||
let paragraph_refs = paragraphs.iter().map(String::as_str).collect::<Vec<_>>();
|
||||
let origin_text = origin.as_str().trim_end_matches('/');
|
||||
let content = Content {
|
||||
title,
|
||||
preheader: title,
|
||||
paragraphs: ¶graph_refs,
|
||||
code,
|
||||
button,
|
||||
url: url.as_str(),
|
||||
expiry,
|
||||
origin: origin_text,
|
||||
};
|
||||
let text = format!(
|
||||
"Vnox\n\n{title}\n\n{}\n\n{}\n{button}: {}\n\n{expiry}\n\nНе передавай код или ссылку другим людям.\n\n{origin_text}\n",
|
||||
paragraphs.join("\n\n"),
|
||||
code.map(|value| format!("Код: {value}\n"))
|
||||
.unwrap_or_default(),
|
||||
url.as_str(),
|
||||
);
|
||||
Ok(Email {
|
||||
subject: format!("Vnox — {title}"),
|
||||
text,
|
||||
html: layout::render(&content),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write_previews(directory: &std::path::Path, origin: &Url) -> Result<()> {
|
||||
std::fs::create_dir_all(directory)?;
|
||||
for (name, kind) in [
|
||||
(
|
||||
"verify",
|
||||
Kind::Verify {
|
||||
token: "DUMMY_PREVIEW_NOT_A_REAL_TOKEN",
|
||||
},
|
||||
),
|
||||
("login", Kind::Login { code: "12345678" }),
|
||||
(
|
||||
"new-device",
|
||||
Kind::NewDevice {
|
||||
device: "Linux Desktop · пример",
|
||||
},
|
||||
),
|
||||
] {
|
||||
let email = render(origin, kind)?;
|
||||
std::fs::write(directory.join(format!("{name}.html")), email.html)?;
|
||||
std::fs::write(directory.join(format!("{name}.txt")), email.text)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
80
hub/src/main.rs
Normal file
80
hub/src/main.rs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
use std::{path::PathBuf, sync::Arc, time::Instant};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use vnox_hub::{config::Config, database, identity::Issuer, mail, web};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| "vnox_hub=info".into()),
|
||||
)
|
||||
.init();
|
||||
let args = std::env::args().skip(1).collect::<Vec<_>>();
|
||||
if args == ["--help"] {
|
||||
println!(
|
||||
"vnox-hub [--check-smtp | --render-email-preview DIRECTORY]\nConfiguration is read from the protected service environment. No send-email CLI is exposed."
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let config = Config::from_env()?;
|
||||
if args == ["--check-smtp"] {
|
||||
let smtp = config.smtp.as_ref().context("SMTP is not configured")?;
|
||||
mail::Mailer::new(smtp)?.check_connection().await?;
|
||||
println!("SMTP TLS and authentication verified; no email was sent.");
|
||||
return Ok(());
|
||||
}
|
||||
if args
|
||||
.first()
|
||||
.is_some_and(|arg| arg == "--render-email-preview")
|
||||
&& args.len() == 2
|
||||
{
|
||||
mail::templates::write_previews(&PathBuf::from(&args[1]), &config.origin)?;
|
||||
println!(
|
||||
"Generated three HTML/plain-text previews with dummy credentials; no email was sent."
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if !args.is_empty() {
|
||||
bail!("unknown arguments; use --help");
|
||||
}
|
||||
let issuer = Issuer::load_or_create(&config.data_dir)?;
|
||||
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.
|
||||
if let Some(smtp) = &config.smtp {
|
||||
mail::Mailer::new(smtp)?;
|
||||
}
|
||||
let state = Arc::new(web::HubState {
|
||||
database,
|
||||
issuer,
|
||||
smtp_configured: config.smtp.is_some(),
|
||||
started: Instant::now(),
|
||||
});
|
||||
let listener = tokio::net::TcpListener::bind(config.bind)
|
||||
.await
|
||||
.context("binding Hub listener")?;
|
||||
tracing::info!(address = %listener.local_addr()?, "Vnox Hub foundation listening");
|
||||
axum::serve(listener, web::router(state.clone()))
|
||||
.with_graceful_shutdown(shutdown())
|
||||
.await
|
||||
.context("serving Hub HTTP")?;
|
||||
state.database.close().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn shutdown() {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
if let Ok(mut terminate) = signal(SignalKind::terminate()) {
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => {},
|
||||
_ = terminate.recv() => {},
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
}
|
||||
121
hub/src/web.rs
Normal file
121
hub/src/web.rs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
use axum::{
|
||||
Json, Router,
|
||||
body::Body,
|
||||
extract::State,
|
||||
http::{HeaderValue, Request, StatusCode},
|
||||
middleware::{self, Next},
|
||||
response::{Html, Response},
|
||||
routing::get,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::identity::Issuer;
|
||||
|
||||
pub struct HubState {
|
||||
pub database: SqlitePool,
|
||||
pub issuer: Issuer,
|
||||
pub smtp_configured: bool,
|
||||
pub started: Instant,
|
||||
}
|
||||
|
||||
pub fn router(state: Arc<HubState>) -> Router {
|
||||
Router::new()
|
||||
.route("/", get(index))
|
||||
.route("/health", get(health))
|
||||
.route("/ready", get(ready))
|
||||
.route("/version", get(version))
|
||||
.route("/v1/info", get(info))
|
||||
.route("/assets/vnox-mark.svg", get(logo))
|
||||
.route("/assets/vnox-mark.png", get(logo_png))
|
||||
.fallback(|| async { (StatusCode::NOT_FOUND, Json(json!({"error": "not_found"}))) })
|
||||
.layer(middleware::from_fn(headers))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
async fn health() -> Json<Value> {
|
||||
Json(json!({"status": "ok", "service": "vnox-hub"}))
|
||||
}
|
||||
|
||||
async fn ready(State(state): State<Arc<HubState>>) -> (StatusCode, Json<Value>) {
|
||||
match sqlx::query_scalar::<_, i64>("SELECT 1")
|
||||
.fetch_one(&state.database)
|
||||
.await
|
||||
{
|
||||
Ok(1) => (
|
||||
StatusCode::OK,
|
||||
Json(json!({"status": "ready", "database": "ready", "issuer": "loaded"})),
|
||||
),
|
||||
_ => (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(json!({"status": "not_ready"})),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
async fn version() -> Json<Value> {
|
||||
Json(json!({
|
||||
"service": "vnox-hub",
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"api_version": 1,
|
||||
"stage": "foundation"
|
||||
}))
|
||||
}
|
||||
|
||||
async fn info(State(state): State<Arc<HubState>>) -> Json<Value> {
|
||||
Json(json!({
|
||||
"service": "vnox-hub",
|
||||
"stage": "foundation",
|
||||
"issuer_id": state.issuer.id,
|
||||
"issuer_public_key": state.issuer.public_key,
|
||||
"uptime_seconds": state.started.elapsed().as_secs(),
|
||||
"smtp": {"configured": state.smtp_configured, "public_send_endpoint": false},
|
||||
"capabilities": {
|
||||
"email_auth": "not_enabled",
|
||||
"github_auth": "not_enabled",
|
||||
"server_registry": "not_enabled",
|
||||
"friends": "not_enabled",
|
||||
"direct_messages": "not_enabled",
|
||||
"marketplace": "not_enabled"
|
||||
},
|
||||
"retention_plan": {"dm_days": 7, "attachment_days": 4, "attachment_max_bytes": 20000000}
|
||||
}))
|
||||
}
|
||||
|
||||
async fn logo() -> ([(&'static str, &'static str); 1], &'static str) {
|
||||
(
|
||||
[("content-type", "image/svg+xml; charset=utf-8")],
|
||||
include_str!("../assets/vnox-mark.svg"),
|
||||
)
|
||||
}
|
||||
|
||||
async fn logo_png() -> ([(&'static str, &'static str); 1], &'static [u8]) {
|
||||
(
|
||||
[("content-type", "image/png")],
|
||||
include_bytes!("../assets/vnox-mark.png"),
|
||||
)
|
||||
}
|
||||
|
||||
async fn index() -> Html<&'static str> {
|
||||
Html(include_str!("../assets/index.html"))
|
||||
}
|
||||
|
||||
async fn headers(request: Request<Body>, next: Next) -> Response {
|
||||
let mut response = next.run(request).await;
|
||||
for (name, value) in [
|
||||
("cache-control", "no-store"),
|
||||
("x-content-type-options", "nosniff"),
|
||||
("referrer-policy", "no-referrer"),
|
||||
(
|
||||
"content-security-policy",
|
||||
"default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; frame-ancestors 'none'",
|
||||
),
|
||||
] {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(name, HeaderValue::from_static(value));
|
||||
}
|
||||
response
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue