feat(hub): add central service foundation and transactional mail

This commit is contained in:
Loki 2026-10-24 14:15:48 +02:00
parent b14f036bdb
commit a811de590a
Signed by: boba
GPG key ID: 253067914055423B
25 changed files with 1521 additions and 4 deletions

112
Cargo.lock generated
View file

@ -42,7 +42,7 @@ dependencies = [
"asn1-rs-derive", "asn1-rs-derive",
"asn1-rs-impl", "asn1-rs-impl",
"displaydoc", "displaydoc",
"nom", "nom 7.1.3",
"num-traits", "num-traits",
"rusticata-macros", "rusticata-macros",
"thiserror", "thiserror",
@ -72,6 +72,17 @@ dependencies = [
"syn 2.0.119", "syn 2.0.119",
] ]
[[package]]
name = "async-trait"
version = "0.1.92"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]] [[package]]
name = "atoi" name = "atoi"
version = "2.0.0" version = "2.0.0"
@ -428,7 +439,7 @@ checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
dependencies = [ dependencies = [
"asn1-rs", "asn1-rs",
"displaydoc", "displaydoc",
"nom", "nom 7.1.3",
"num-bigint", "num-bigint",
"num-traits", "num-traits",
"rusticata-macros", "rusticata-macros",
@ -518,6 +529,22 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "email-encoding"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "420b9da095f052ea597503e39073b5b3c522f7db933fbac202d91d24492693fd"
dependencies = [
"base64 0.23.1",
"memchr",
]
[[package]]
name = "email_address"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.3" version = "1.0.3"
@ -1038,6 +1065,33 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]]
name = "lettre"
version = "0.11.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae"
dependencies = [
"async-trait",
"base64 0.23.1",
"email-encoding",
"email_address",
"fastrand",
"futures-io",
"futures-util",
"httpdate",
"idna",
"mime",
"nom 8.0.0",
"percent-encoding",
"quoted_printable",
"rustls",
"socket2",
"tokio",
"tokio-rustls",
"url",
"webpki-roots",
]
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.191" version = "0.2.191"
@ -1152,6 +1206,15 @@ dependencies = [
"minimal-lexical", "minimal-lexical",
] ]
[[package]]
name = "nom"
version = "8.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "nu-ansi-term" name = "nu-ansi-term"
version = "0.50.3" version = "0.50.3"
@ -1382,6 +1445,12 @@ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]]
name = "quoted_printable"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "478e0585659a122aa407eb7e3c0e1fa51b1d8a870038bd29f0cf4a8551eea972"
[[package]] [[package]]
name = "r-efi" name = "r-efi"
version = "6.0.0" version = "6.0.0"
@ -1486,7 +1555,7 @@ version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
dependencies = [ dependencies = [
"nom", "nom 7.1.3",
] ]
[[package]] [[package]]
@ -1686,6 +1755,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]] [[package]]
name = "signature" name = "signature"
version = "3.0.0" version = "3.0.0"
@ -1982,6 +2061,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [ dependencies = [
"fastrand", "fastrand",
"getrandom 0.4.3",
"once_cell", "once_cell",
"rustix", "rustix",
"windows-sys 0.61.2", "windows-sys 0.61.2",
@ -2072,6 +2152,7 @@ dependencies = [
"libc", "libc",
"mio", "mio",
"pin-project-lite", "pin-project-lite",
"signal-hook-registry",
"socket2", "socket2",
"tokio-macros", "tokio-macros",
"windows-sys 0.61.2", "windows-sys 0.61.2",
@ -2313,6 +2394,7 @@ checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514"
dependencies = [ dependencies = [
"getrandom 0.4.3", "getrandom 0.4.3",
"js-sys", "js-sys",
"serde_core",
"wasm-bindgen", "wasm-bindgen",
] ]
@ -2363,6 +2445,28 @@ dependencies = [
"x25519-dalek", "x25519-dalek",
] ]
[[package]]
name = "vnox-hub"
version = "0.1.0"
dependencies = [
"anyhow",
"axum",
"ed25519-dalek",
"hex",
"lettre",
"rand",
"serde",
"serde_json",
"sqlx",
"tempfile",
"tokio",
"tower",
"tracing",
"tracing-subscriber",
"url",
"uuid",
]
[[package]] [[package]]
name = "vnox-serverd" name = "vnox-serverd"
version = "0.1.0" version = "0.1.0"
@ -2576,7 +2680,7 @@ dependencies = [
"data-encoding", "data-encoding",
"der-parser", "der-parser",
"lazy_static", "lazy_static",
"nom", "nom 7.1.3",
"oid-registry", "oid-registry",
"ring", "ring",
"rusticata-macros", "rusticata-macros",

View file

@ -4,6 +4,7 @@ members = [
"gateway", "gateway",
"voice-node", "voice-node",
"serverd", "serverd",
"hub",
] ]
[workspace.package] [workspace.package]

80
deploy/central/README.md Normal file
View file

@ -0,0 +1,80 @@
# Central Hub deployment
Current target: `central.loki-code.dev`, Ubuntu22.04, Nginx443 terminating HTTPS;
Hub listener `127.0.0.1:37623` (randomly selected free port). The foundation has no
public email-send/auth/registry/friends/DM endpoints. See `hub/README.md` for exact
capability status. SMTP sender display name is Vnox, address `noreply@loki-code.dev`.
## Layout
- `/opt/vnox-central/releases/<git-revision>-<binary-hash>/vnox-hub`: immutable release.
- `/opt/vnox-central/current`: symlink to selected release.
- `/etc/vnox-central/hub.env`: real config, root-owned0600, outside Git.
- `/var/lib/vnox-central/`: private service data0700, issuer0600 and SQLite.
- `/etc/systemd/system/vnox-central.service`: dedicated non-login service user.
- `/etc/nginx/sites-available/central.loki-code.dev`: dedicated virtual host.
Only copy explicitly authorized SMTP keys from the existing service in-process.
Do not dump Docker environment/config, source secrets into shell logs, add them to
command arguments, publish them in preview pages or commit them. Displaying a
successful SMTP test is enough; it does not require revealing credentials.
## Build and publish
Build from `VNOX-Server/`, after tests/review, on the installed Rust toolchain:
```sh
CC_x86_64_unknown_linux_musl=musl-gcc cargo build --locked --release \
--target x86_64-unknown-linux-musl -p vnox-hub
sha256sum target/x86_64-unknown-linux-musl/release/vnox-hub
```
The static musl build avoids depending on a newer local glibc than Ubuntu22.04.
Build and verify before uploading. Install into a new revision/hash directory,
verify its remote SHA256, switch `current` atomically, restart only
`vnox-central`, and verify readiness before pointing/reloading the Nginx proxy.
Keep the preceding release for rollback; do not replace identity or DB on update.
Install the service/config templates with local paths/port adjusted as needed.
Create `vnox-central` system user and private state dir first. SMTP credentials
are supplied only in protected `hub.env`; example credentials do not work.
## Certificate and renewal
Provision HTTP ACME webroot before requesting the cert:
```sh
certbot certonly --webroot -w /var/www/vnox-acme -d central.loki-code.dev \
--non-interactive --agree-tos
nginx -t
systemctl reload nginx
```
Keep the ACME path available after enabling the HTTP→HTTPS redirect. Certbot's
timer handles renewal; a deploy hook validates/reloads Nginx after renewal.
Check certificate chain/hostname from outside the VPS, not only with `nginx -t`.
Run renewal staging checks without unnecessary random sleep when unattended.
## Verification
```sh
systemctl is-active vnox-central
curl --fail http://127.0.0.1:37623/ready
curl --fail https://central.loki-code.dev/ready
curl --fail https://central.loki-code.dev/v1/info
```
Use a transient systemd service with the same protected EnvironmentFile to run
`vnox-hub --check-smtp` as the service user. It connects/authenticates and issues
NOOP without sending a message. Actual delivery needs a separately authorized
recipient/test. Previews use dummy tokens and must not be mistaken for working
verification links.
Restart once and verify the issuer ID/public key remain unchanged and `/ready`
returns200. Confirm the backend listener is loopback-only, key/env modes are
private, other Nginx virtual hosts still work, and SIGTERM exits cleanly.
Back up issuer and SQLite consistently (SQLite backup API/checkpoint or stopped
service), with encrypted/private storage; test paired restore. Do not back up
only DB and silently generate a new issuer if its key is missing. Future DM
payload/attachment backup policy is separate from account/registry state.

View file

@ -0,0 +1,32 @@
server {
listen 80;
listen [::]:80;
server_name central.loki-code.dev;
location ^~ /.well-known/acme-challenge/ {
root /var/www/vnox-acme;
default_type text/plain;
}
location / { return 301 https://central.loki-code.dev$request_uri; }
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name central.loki-code.dev;
ssl_certificate /etc/letsencrypt/live/central.loki-code.dev/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/central.loki-code.dev/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
server_tokens off;
client_max_body_size 1m;
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy no-referrer always;
location / {
proxy_pass http://127.0.0.1:37623;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Connection "";
proxy_connect_timeout 5s;
proxy_read_timeout 30s;
}
}

View file

@ -0,0 +1,11 @@
# Install a completed copy as /etc/vnox-central/hub.env, root:root mode 0600.
# This is an example, never add production secrets to Git.
HUB_BIND=127.0.0.1:37623
HUB_DATA_DIR=/var/lib/vnox-central
PUBLIC_BASE_URL=https://central.loki-code.dev
SMTP_HOST=smtp.provider.example
SMTP_PORT=587
SMTP_USER=replace-on-server
SMTP_PASSWORD=replace-on-server
MAIL_FROM="Vnox <noreply@loki-code.dev>"
RUST_LOG=vnox_hub=info

View file

@ -0,0 +1,32 @@
[Unit]
Description=Vnox Central Hub
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=vnox-central
Group=vnox-central
WorkingDirectory=/var/lib/vnox-central
EnvironmentFile=/etc/vnox-central/hub.env
ExecStart=/opt/vnox-central/current/vnox-hub
Restart=on-failure
RestartSec=5
TimeoutStopSec=30
StateDirectory=vnox-central
StateDirectoryMode=0700
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectHome=true
ProtectSystem=strict
ReadWritePaths=/var/lib/vnox-central
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
UMask=0077
LimitNOFILE=8192
[Install]
WantedBy=multi-user.target

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Vnox"><rect width="64" height="64" rx="17" fill="#202022"/><g fill="none" stroke="#dac5a6" stroke-width="5" stroke-linejoin="round" stroke-linecap="round"><path d="M16 20 32 46 48 20"/><path d="M16 20H26M38 20H48"/></g></svg>

After

Width:  |  Height:  |  Size: 308 B

View file

@ -0,0 +1,59 @@
# Vnox: активность, профиль, демонстрация, языки и вебхуки
Статус: продуктовый план по обратной связи пользователя, не заявление о готовых функциях. Логотип утверждён: «Связь», простой V (`brand/vnox-link.svg`). Текущий UI/Hub groundwork проверяется и коммитится отдельными изменениями.
## Активность и присутствие
В протоколе уже есть ONLINE/IDLE/DND/OFFLINE/INVISIBLE и типы playing/listening/watching/streaming/custom. Это заготовка; текущие broadcast и сериализация требуют согласования, а приватность ещё не реализована как законченный контракт.
Первый этап: статус, ручной текст, автоматический idle и отображение факта трансляции/звонка с отдельной видимостью. Автоопределение игры — opt-in, с выключателем для конкретных приложений. Пользователь выбирает аудиторию: никто, друзья, участники выбранных сообществ. DND управляет уведомлениями; Invisible означает offline для остальных и скрывает активность. Подписки и выдача API фильтруются сервером, а не только интерфейсом.
Процессы определяются локально; в Hub отправляются только выбранные сведения известного приложения, не полный список процессов/путей/заголовков окон. Закрытый сервер/канал не раскрывается посторонним через «сейчас в голосе». Активность имеет TTL и исчезает после потери устройства. Несколько устройств агрегируются, отключение одного не ставит пользователя offline при другом активном.
Rich Presence SDK — последующий этап: зарегистрированные application_id, проверяемый издатель, ограниченная локальная IPC-интеграция, allowlist полей/кнопок и явный пользовательский контроль. Нельзя позволять любому локальному процессу незаметно выдавать себя за другую игру.
## Социальные ссылки в профиле
В карточке: аватар, имя/handle, краткое «О себе», активность и компактный ряд социальных ссылок с узнаваемой иконкой и показом домена. Начальные типы GitHub, Telegram, YouTube, Twitch, Steam и собственный сайт; список расширяемый. До6 ссылок с порядком, подписью и настройкой видимости профиля/друзей/сообщества.
В первой версии это явно пользовательские ссылки, не доказательство владения аккаунтом. Значок подтверждённого владения появляется только после отдельного OAuth/проверки. GitHub, использованный для входа, не публикуется автоматически без выбора пользователя.
Разрешены проверенные HTTPS URL с ограниченными длинами, без javascript/data/file/custom-scheme и пользовательского HTML. Открытие в системном браузере, внешний домен виден до перехода. Сервер не выполняет запрос к произвольному URL ради превью по умолчанию; это предотвращает SSRF/трекинг. Изменения доступны только владельцу профиля, конфликты версий решаются явно.
## Демонстрация экрана
Диалог разделяет три выбора: видео (окно/экран), звук (выключен/конкретное приложение/весь системный звук) и параметры качества. Микрофон остаётся самостоятельным голосовым источником. Выключение микрофона не выключает звук приложения, остановка демки не завершает голосовой звонок. У зрителя отдельная громкость трансляции и голоса.
Режим по умолчанию для окна — звук того же приложения, только когда доступно надёжное сопоставление. Нельзя молча переключать отсутствующий per-app capture на запись всего устройства: уведомления и другие программы могут содержать приватные данные. Если сопоставления нет, показать «звук приложения недоступен» и предложить явный выбор. Захват процесса может включать несколько окон/дочерних процессов, особенно браузера; не обещать изоляцию отдельной вкладки без соответствующего API.
Windows: process loopback WASAPI (ActivateAudioInterfaceAsync) поддерживает выбранный процесс и его дерево на поддерживаемых версиях Windows. Проверять capability ОС, не предполагать наличие по общему названию Windows10.
Linux Wayland: видео через системный ScreenCast portal с пользовательским выбором; PipeWire для потоков. Audio per-app — отдельная работа с доступными PipeWire streams и политикой session manager. ScreenCast portal сам по себе не гарантирует per-app audio. Нельзя менять пользовательский PipeWire config ради запуска Vnox. X11/macOS получают отдельные adapters и проверку разрешений; первая цель — Linux/Windows.
Видео, звук демонстрации и микрофон имеют разные media tracks. Собственный голос/принимаемый Vnox звук исключаются из захвата по возможности, чтобы не создавать петлю; невозможность исключить источник отражается в UI. Синхронизация A/V, bitrate adaptation, потеря пакетов и ключевые кадры — обязательная часть медиа-протокола.
Для транспорта рассмотреть готовый WebRTC стек и встроенный SFU/relay модуль на том же сервере сообщества вместо самостоятельного изобретения видео-протокола. Отдельной голосовой/видео машины нет. Hop-by-hop media encryption не называть E2EE через сервер. Выбор Rust-библиотеки, codecs и hardware encoding подтверждается прототипом и тестами; новые зависимости в текущий groundwork не добавляются.
MVP: одна трансляция пользователя, ручной выбор зрителя, доступ по комнате и праву STREAM, смена источника/остановка/отзыв доступа. Качество по умолчанию до1080p30 с адаптацией; gaming60fps и несколько одновременных трансляций — после измерений. Отсутствие поддержки должно быть явным, а не кнопкой без результата.
## Языки клиента
Первый полноценный набор ru/en, включая ошибки, настройки, письма и формы входа. Выбор при первом запуске по системной locale с ручным переопределением. Далее uk, pl, de, es, fr и pt-BR по готовности качественных переводов; не показывать язык с половиной непереведённых строк как поддержанный.
Использовать native Slint @tr/gettext catalogs, извлечение строк, plural forms, стабильные контексты и общий подход для Rust errors/backend error codes. В протоколе передаются коды ошибок и параметры, а не готовая русская фраза. Протестировать длины переводов и форматирование дат/чисел; выбор языка независим от timezone. Сообщения пользователей не переводятся через внешний сервис без согласия.
## Вебхуки
Первыми — входящие вебхуки конкретного сервера в выбранный текстовый канал: GitHub/GitLab CI, игровые серверы, мониторинг. Создать/посмотреть/перевыпустить/отключить может роль с MANAGE_WEBHOOKS. Сообщения имеют отдельную webhook identity/метку и не могут незаметно имитировать человека. Разрешения не дают global DM, server administration или массовых mentions автоматически.
Endpoint принимает ограниченный JSON, с отдельным высокоэнтропийным секретом на hook, rate limits и idempotency/delivery_id. Секрет показывается владельцу при создании и может быть отозван. Не помещать его в обычные access logs; предпочтителен Authorization header, а провайдерские форматы валидируются адаптером. GitHub HMAC проверяется по исходным байтам тела до парсинга.
Исходящие hooks — второй этап: только явно выбранные события/каналы, HTTPS, HMAC подпись тела с event_id/timestamp, ограниченные повторы/таймауты и журнал доставки. Дубликаты возможны, потребитель должен дедуплицировать. Адреса назначения проверяются против SSRF, DNS rebinding и редиректов в локальную инфраструктуру. Содержимое закрытого канала не уходит по webhook без соответствующих прав и предупреждения администратора.
Вебхуки живут у сервера сообщества. Центральный Hub не проксирует всю интеграционную переписку. Discord-compatible payload adapter возможен позже, но совместимость с Discord API целиком не обещается.
## Очерёдность
Сначала закончить текущие UI/dependency/Hub deploy/commits, затем согласовать общий клиент-серверный протокол, права и auth. После этого ru/en infrastructure и профиль со ссылками, приватное присутствие, входящие hooks; демка — отдельный медиа-этап с реальными Linux/Windows тестами.
Источники: [Windows process loopback](https://learn.microsoft.com/en-us/samples/microsoft/windows-classic-samples/applicationloopbackaudio-sample/), [ScreenCast portal](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.ScreenCast.html), [PipeWire loopback](https://docs.pipewire.org/page_module_loopback.html), [Slint translations](https://docs.slint.dev/latest/docs/slint/guide/development/translations/), [GitHub webhook signatures](https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries), [OWASP SSRF](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html).

29
hub/Cargo.toml Normal file
View file

@ -0,0 +1,29 @@
[package]
name = "vnox-hub"
description = "Vnox central service foundation — identity, readiness and transactional mail"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
[dependencies]
anyhow.workspace = true
axum = "0.8"
ed25519-dalek.workspace = true
hex.workspace = true
rand.workspace = true
serde.workspace = true
serde_json.workspace = true
tokio = { workspace = true, features = ["signal"] }
tracing.workspace = true
tracing-subscriber.workspace = true
uuid = { workspace = true, features = ["serde"] }
sqlx = { version = "0.9", default-features = false, features = ["sqlite", "runtime-tokio", "migrate", "macros"] }
lettre = { version = "0.11.23", default-features = false, features = ["builder", "smtp-transport", "tokio1-rustls", "aws-lc-rs", "webpki-roots"] }
url = "2"
[dev-dependencies]
tempfile = "3"
tower = { version = "0.5", features = ["util"] }

79
hub/README.md Normal file
View file

@ -0,0 +1,79 @@
# Vnox Hub foundation
`vnox-hub` is the central service foundation. It starts as one HTTP service behind
an HTTPS reverse proxy and stores its issuer identity and SQLite database locally.
Community messages and voice never pass through this process.
## Implemented
- `/health`: process liveness.
- `/ready`: database readiness after successful migrations and issuer validation.
- `/version`: binary version and explicit `foundation` stage.
- `/v1/info`: public issuer ID/key and honest feature availability.
- `/`: deployment status page; `/assets/vnox-mark.svg`: approved V connection mark.
- Durable SQLite schema and issuer identity with a private `0600` key file.
- TLS-only SMTP transport and HTML/plain-text transactional email templates.
Email authentication, GitHub OAuth, server registration/discovery, friends, DM
storage and marketplace API are **not enabled**. There is no public endpoint for
sending mail. Existing schema tables are foundations, not working authentication.
Template links are previews of future routes; they do not create working tokens.
## Configuration
Set these in a protected systemd `EnvironmentFile` outside Git. Use a dedicated
service user, a private `0700` data directory, restrictive umask and loopback-only HTTP.
```ini
HUB_BIND=127.0.0.1:17843
HUB_DATA_DIR=/var/lib/vnox-hub
PUBLIC_BASE_URL=https://central.loki-code.dev
SMTP_HOST=smtp.provider.example
SMTP_PORT=587
SMTP_USER=provider-user
SMTP_PASSWORD=replace-outside-git
MAIL_FROM="Vnox <noreply@loki-code.dev>"
RUST_LOG=vnox_hub=info
```
`SMTP_HOST` may be omitted to disable the transport. Partially configured
credentials cause startup validation errors instead of silent fallback. Port465
uses implicit TLS; all other ports require STARTTLS with certificate validation.
No plaintext downgrade is supported. SMTP construction validates configuration;
readiness does not claim SMTP delivery was tested. Configure an external monitor
for `/ready` and perform SMTP connectivity checks separately.
`PUBLIC_BASE_URL` must be an HTTPS origin with no path, query, credentials or
fragment. It is the only source for email links; request Host headers are ignored.
Do not configure an untrusted hostname as the public origin.
## Run and verify
Run commands from `VNOX-Server/`:
```sh
cargo run -p vnox-hub
cargo run -p vnox-hub -- --check-smtp
cargo run -p vnox-hub -- --render-email-preview /tmp/vnox-mail-preview
cargo test -p vnox-hub
cargo clippy -p vnox-hub --all-targets -- -D warnings
```
`--check-smtp` connects, validates TLS/authentication and issues an SMTP NOOP. It
never sends mail. `--render-email-preview` writes three HTML/plain-text pairs with
dummy token/code values and never contacts SMTP. Do not use example values as
real verification credentials. Secrets must not be passed as command arguments.
## Deployment and backup
Terminate HTTPS at Nginx, keep the random Hub listener on loopback, and expose only
443/80 as required for HTTPS/ACME. Check configuration before reloading Nginx.
Use the supplied parent deployment configuration once reviewed. The process
handles SIGTERM/Ctrl-C with graceful HTTP shutdown and closes its SQLite pool.
Keep `issuer.json` and `hub.sqlite3` together in backup/restore. If their identities
differ, startup fails; it must never silently replace the issuer of an existing
Hub. An invalid/malformed issuer file likewise fails closed. Protect the entire
data directory, not only the JSON file. Additional account/device revocation,
registry authorization, mailbox lifecycle and storage policies require their own
implementation and security review before those capabilities are enabled.

4
hub/assets/index.html Normal file
View file

@ -0,0 +1,4 @@
<!doctype html>
<html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vnox Central</title>
<style>html{color-scheme:dark}*{box-sizing:border-box}body{margin:0;background:#151516;color:#e9e7e4;font:16px/1.6 system-ui,sans-serif;min-height:100vh;display:grid;place-items:center;padding:24px}main{max-width:660px;width:100%;border:1px solid #403a33;border-radius:18px;overflow:hidden;background:#202022}header{padding:32px;background:linear-gradient(125deg,#45382d,#292829);display:flex;gap:15px;align-items:center}img{width:50px;height:50px}header strong{font-size:24px;letter-spacing:-.5px}section{padding:30px 32px}h1{font-size:23px;line-height:1.3;margin:0 0 16px}p{color:#bab3aa;margin:0 0 20px}.status{display:inline-block;color:#bbcfad;font-size:13px;background:#30362e;padding:4px 10px;border-radius:6px}ul{padding-left:20px;color:#c7bfb4}footer{padding:18px 32px;border-top:1px solid #393531;color:#a49a90;font-size:13px}a{color:#d5b58a;text-underline-offset:3px}nav{display:flex;flex-wrap:wrap;gap:22px;margin-top:27px}</style></head>
<body><main><header><img src="/assets/vnox-mark.svg" alt=""><strong>Vnox Central</strong></header><section><span class="status">Сервис развёрнут · базовый этап</span><h1 style="margin-top:22px">Центр сети Vnox</h1><p>Здесь появятся общий профиль, друзья и поиск серверов. Сейчас подготовлены служба, постоянная identity, база данных и почтовый транспорт.</p><ul><li>Регистрация и вход пока не включены.</li><li>Каталог серверов, личные сообщения и маркетплейс ещё разрабатываются.</li><li>Сообщества обслуживают свои чаты и голос самостоятельно.</li></ul><nav><a href="/ready">Готовность службы</a><a href="/v1/info">Возможности API</a><a href="/version">Версия</a></nav></section><footer>Vnox · собственные сообщества, общее пространство для общения.</footer></main></body></html>

BIN
hub/assets/vnox-mark.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3 KiB

1
hub/assets/vnox-mark.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Vnox"><rect width="64" height="64" rx="17" fill="#202022"/><g fill="none" stroke="#dac5a6" stroke-width="5" stroke-linejoin="round" stroke-linecap="round"><path d="M16 20 32 46 48 20"/><path d="M16 20H26M38 20H48"/></g></svg>

After

Width:  |  Height:  |  Size: 308 B

View file

@ -0,0 +1,26 @@
-- No authentication/registry endpoints use these tables yet. Defining durable
-- IDs now does not imply that account/device authorization is implemented.
CREATE TABLE hub_metadata (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE accounts (
user_id TEXT PRIMARY KEY,
handle TEXT UNIQUE NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE devices (
device_id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES accounts(user_id) ON DELETE CASCADE,
public_key BLOB NOT NULL,
created_at INTEGER NOT NULL,
revoked_at INTEGER
);
CREATE TABLE servers (
server_id TEXT PRIMARY KEY,
owner_user_id TEXT NOT NULL REFERENCES accounts(user_id),
public_key BLOB UNIQUE NOT NULL,
address TEXT NOT NULL,
visibility TEXT NOT NULL CHECK (visibility IN ('private', 'unlisted', 'public')),
created_at INTEGER NOT NULL
);

99
hub/src/config.rs Normal file
View 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
View 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
View 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
View 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
View file

@ -0,0 +1,59 @@
/// Escape all dynamic HTML, including attribute values.
pub fn escape(value: &str) -> String {
value
.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
.replace('\'', "&#39;")
}
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
View 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
View 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: &paragraph_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
View 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
View 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
}

210
hub/tests/foundation.rs Normal file
View file

@ -0,0 +1,210 @@
use std::{collections::HashMap, sync::Arc, time::Instant};
use axum::{
body::Body,
http::{Request, StatusCode},
};
use tempfile::TempDir;
use tower::ServiceExt;
use vnox_hub::{
config::Config,
database,
identity::Issuer,
web::{self, HubState},
};
fn private_directory() -> TempDir {
let directory = TempDir::new().unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
}
directory
}
fn config(values: &[(&str, &str)]) -> anyhow::Result<Config> {
let values = values
.iter()
.map(|(key, value)| (*key, *value))
.collect::<HashMap<_, _>>();
Config::from_lookup(|key| values.get(key).map(|value| (*value).to_owned()))
}
#[test]
fn rejects_public_binding_and_untrusted_origins() {
assert!(config(&[("HUB_BIND", "0.0.0.0:18000")]).is_err());
for origin in [
"http://central.example",
"https://a.example/path",
"https://a.example?token=x",
"https://user:secret@a.example",
"https://a.example/#fragment",
] {
assert!(config(&[("PUBLIC_BASE_URL", origin)]).is_err(), "{origin}");
}
assert!(config(&[("PUBLIC_BASE_URL", "https://central.example")]).is_ok());
}
#[test]
fn rejects_incomplete_smtp_config_instead_of_silently_disabling_mail() {
assert!(config(&[("SMTP_PASSWORD", "not-a-real-secret")]).is_err());
assert!(config(&[("SMTP_HOST", "smtp.example"), ("SMTP_USER", "test")]).is_err());
assert!(config(&[("SMTP_HOST", "smtp.example"), ("SMTP_PORT", "0")]).is_err());
assert!(config(&[("SMTP_HOST", "smtp://smtp.example")]).is_err());
}
#[test]
fn issuer_identity_is_stable_and_private() {
let directory = private_directory();
let first = Issuer::load_or_create(directory.path()).unwrap();
let second = Issuer::load_or_create(directory.path()).unwrap();
assert_eq!(first.id, second.id);
assert_eq!(first.public_key, second.public_key);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let path = directory.path().join("issuer.json");
assert_eq!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o600
);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
assert!(Issuer::load_or_create(directory.path()).is_err());
}
}
#[test]
fn corrupt_identity_does_not_get_replaced_with_a_new_issuer() {
let directory = private_directory();
let issuer = Issuer::load_or_create(directory.path()).unwrap();
let path = directory.path().join("issuer.json");
let original = std::fs::read_to_string(&path).unwrap();
std::fs::write(&path, original.replace(&issuer.public_key, &"0".repeat(64))).unwrap();
assert!(Issuer::load_or_create(directory.path()).is_err());
assert!(
std::fs::read_to_string(path)
.unwrap()
.contains(&"0".repeat(64))
);
}
async fn state() -> (TempDir, Arc<HubState>) {
let directory = private_directory();
let issuer = Issuer::load_or_create(directory.path()).unwrap();
let pool = database::open(directory.path(), &issuer).await.unwrap();
(
directory,
Arc::new(HubState {
database: pool,
issuer,
smtp_configured: true,
started: Instant::now(),
}),
)
}
#[tokio::test]
async fn database_migrations_persist_and_refuse_a_different_issuer() {
let (directory, state) = state().await;
let tables: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN ('accounts','devices','servers')")
.fetch_one(&state.database).await.unwrap();
assert_eq!(tables, 3);
state.database.close().await;
let pool = database::open(directory.path(), &state.issuer)
.await
.unwrap();
pool.close().await;
let other_dir = private_directory();
let other = Issuer::load_or_create(other_dir.path()).unwrap();
assert!(database::open(directory.path(), &other).await.is_err());
}
#[tokio::test]
async fn readiness_reflects_database_failure() {
let (_directory, state) = state().await;
let app = web::router(state.clone());
let response = app
.clone()
.oneshot(
Request::builder()
.uri("/ready")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
state.database.close().await;
let response = app
.oneshot(
Request::builder()
.uri("/ready")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn capabilities_and_routes_do_not_pretend_authentication_is_ready() {
let (_directory, state) = state().await;
let app = web::router(state);
let response = app
.clone()
.oneshot(
Request::builder()
.uri("/v1/info")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.headers()["cache-control"], "no-store");
let body = axum::body::to_bytes(response.into_body(), 8192)
.await
.unwrap();
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
for capability in [
"email_auth",
"github_auth",
"server_registry",
"friends",
"direct_messages",
"marketplace",
] {
assert_eq!(value["capabilities"][capability], "not_enabled");
}
assert_eq!(value["smtp"]["public_send_endpoint"], false);
assert!(value.get("secret_key").is_none());
for path in [
"/v1/auth/email/start",
"/v1/servers/register",
"/v1/mail/send",
] {
let response = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri(path)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
}
#[cfg(unix)]
#[test]
fn refuses_a_world_readable_data_directory() {
use std::os::unix::fs::PermissionsExt;
let directory = private_directory();
std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
assert!(Issuer::load_or_create(directory.path()).is_err());
assert!(!directory.path().join("issuer.json").exists());
}

109
hub/tests/mail.rs Normal file
View file

@ -0,0 +1,109 @@
use vnox_hub::{
config::{SmtpConfig, parse_origin},
mail::{
Mailer,
templates::{self, Kind},
},
};
#[test]
fn mail_links_stay_on_configured_origin_and_escape_dynamic_content() {
let origin = parse_origin("https://central.loki-code.dev").unwrap();
let email = templates::render(
&origin,
Kind::Verify {
token: "abc\"&<https://evil.example>",
},
)
.unwrap();
assert!(
email
.html
.contains("https://central.loki-code.dev/verify-email?token=")
);
assert!(!email.html.contains("href=\"https://evil.example"));
assert!(!email.html.contains("token=abc\""));
let email = templates::render(
&origin,
Kind::NewDevice {
device: "<img src=x onerror=evil()>",
},
)
.unwrap();
assert!(email.html.contains("&lt;img src=x onerror=evil()&gt;"));
assert!(!email.html.contains("<img src=x"));
assert!(email.text.contains("<img src=x onerror=evil()>"));
}
#[test]
fn login_codes_are_validated_and_rendered_in_both_message_parts() {
let origin = parse_origin("https://central.loki-code.dev").unwrap();
for code in ["123", "1234567x", "123456789", "12345678"] {
assert!(templates::render(&origin, Kind::Login { code }).is_err());
}
let email = templates::render(&origin, Kind::Login { code: "12345678" }).unwrap();
assert!(email.html.contains("12345678"));
assert!(email.text.contains("12345678"));
assert!(email.html.contains("10 минут"));
assert!(email.subject.starts_with("Vnox"));
}
#[test]
fn previews_are_three_safe_html_and_text_pairs() {
let directory = tempfile::TempDir::new().unwrap();
let origin = parse_origin("https://central.loki-code.dev").unwrap();
templates::write_previews(directory.path(), &origin).unwrap();
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 6);
let verify = std::fs::read_to_string(directory.path().join("verify.html")).unwrap();
assert!(verify.contains("DUMMY_PREVIEW_NOT_A_REAL_TOKEN"));
assert!(!verify.contains("LoVisual"));
}
#[test]
fn smtp_setup_rejects_invalid_mailbox_and_tls_hostname() {
let config = SmtpConfig {
host: "smtp.example".into(),
port: 587,
user: "".into(),
password: "".into(),
from: "bad\r\nInjected: x".into(),
};
assert!(Mailer::new(&config).is_err());
}
#[tokio::test]
async fn smtp_probe_requires_tls_and_never_falls_back_to_cleartext_authentication() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
socket
.write_all(b"220 localhost ESMTP test\r\n")
.await
.unwrap();
let mut buffer = [0; 2048];
let len = socket.read(&mut buffer).await.unwrap();
let first = String::from_utf8_lossy(&buffer[..len]).to_string();
socket
.write_all(b"250-localhost\r\n250 AUTH PLAIN LOGIN\r\n")
.await
.unwrap();
let second = socket.read(&mut buffer).await.unwrap_or(0);
(first, buffer[..second].to_vec())
});
let mailer = Mailer::new(&SmtpConfig {
host: "localhost".into(),
port,
user: "user".into(),
password: "test-password".into(),
from: "Vnox <noreply@example.com>".into(),
})
.unwrap();
assert!(mailer.check_connection().await.is_err());
let (first, second) = server.await.unwrap();
assert!(first.to_uppercase().starts_with("EHLO"));
let commands = String::from_utf8_lossy(&second).to_uppercase();
assert!(!commands.contains("AUTH"));
assert!(!commands.contains("MAIL FROM"));
}