From a811de590a767d93931941e87d33927561501318 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 14:15:48 +0200 Subject: [PATCH] feat(hub): add central service foundation and transactional mail --- Cargo.lock | 112 +++++++++++- Cargo.toml | 1 + deploy/central/README.md | 80 +++++++++ deploy/central/central.loki-code.dev.conf | 32 ++++ deploy/central/hub.env.example | 11 ++ deploy/central/vnox-central.service | 32 ++++ docs/design/brand/vnox-link.svg | 1 + docs/design/social-presence-sharing.md | 59 ++++++ hub/Cargo.toml | 29 +++ hub/README.md | 79 ++++++++ hub/assets/index.html | 4 + hub/assets/vnox-mark.png | Bin 0 -> 3114 bytes hub/assets/vnox-mark.svg | 1 + hub/migrations/0001_foundation.sql | 26 +++ hub/src/config.rs | 99 ++++++++++ hub/src/database.rs | 44 +++++ hub/src/identity.rs | 148 +++++++++++++++ hub/src/lib.rs | 5 + hub/src/mail/layout.rs | 59 ++++++ hub/src/mail/mod.rs | 65 +++++++ hub/src/mail/templates.rs | 118 ++++++++++++ hub/src/main.rs | 80 +++++++++ hub/src/web.rs | 121 +++++++++++++ hub/tests/foundation.rs | 210 ++++++++++++++++++++++ hub/tests/mail.rs | 109 +++++++++++ 25 files changed, 1521 insertions(+), 4 deletions(-) create mode 100644 deploy/central/README.md create mode 100644 deploy/central/central.loki-code.dev.conf create mode 100644 deploy/central/hub.env.example create mode 100644 deploy/central/vnox-central.service create mode 100644 docs/design/brand/vnox-link.svg create mode 100644 docs/design/social-presence-sharing.md create mode 100644 hub/Cargo.toml create mode 100644 hub/README.md create mode 100644 hub/assets/index.html create mode 100644 hub/assets/vnox-mark.png create mode 100644 hub/assets/vnox-mark.svg create mode 100644 hub/migrations/0001_foundation.sql create mode 100644 hub/src/config.rs create mode 100644 hub/src/database.rs create mode 100644 hub/src/identity.rs create mode 100644 hub/src/lib.rs create mode 100644 hub/src/mail/layout.rs create mode 100644 hub/src/mail/mod.rs create mode 100644 hub/src/mail/templates.rs create mode 100644 hub/src/main.rs create mode 100644 hub/src/web.rs create mode 100644 hub/tests/foundation.rs create mode 100644 hub/tests/mail.rs diff --git a/Cargo.lock b/Cargo.lock index 2993238..30849ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -42,7 +42,7 @@ dependencies = [ "asn1-rs-derive", "asn1-rs-impl", "displaydoc", - "nom", + "nom 7.1.3", "num-traits", "rusticata-macros", "thiserror", @@ -72,6 +72,17 @@ dependencies = [ "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]] name = "atoi" version = "2.0.0" @@ -428,7 +439,7 @@ checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" dependencies = [ "asn1-rs", "displaydoc", - "nom", + "nom 7.1.3", "num-bigint", "num-traits", "rusticata-macros", @@ -518,6 +529,22 @@ dependencies = [ "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]] name = "equivalent" version = "1.0.3" @@ -1038,6 +1065,33 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "libc" version = "0.2.191" @@ -1152,6 +1206,15 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -1382,6 +1445,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "quoted_printable" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478e0585659a122aa407eb7e3c0e1fa51b1d8a870038bd29f0cf4a8551eea972" + [[package]] name = "r-efi" version = "6.0.0" @@ -1486,7 +1555,7 @@ version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" dependencies = [ - "nom", + "nom 7.1.3", ] [[package]] @@ -1686,6 +1755,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "signature" version = "3.0.0" @@ -1982,6 +2061,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", + "getrandom 0.4.3", "once_cell", "rustix", "windows-sys 0.61.2", @@ -2072,6 +2152,7 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", "tokio-macros", "windows-sys 0.61.2", @@ -2313,6 +2394,7 @@ checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ "getrandom 0.4.3", "js-sys", + "serde_core", "wasm-bindgen", ] @@ -2363,6 +2445,28 @@ dependencies = [ "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]] name = "vnox-serverd" version = "0.1.0" @@ -2576,7 +2680,7 @@ dependencies = [ "data-encoding", "der-parser", "lazy_static", - "nom", + "nom 7.1.3", "oid-registry", "ring", "rusticata-macros", diff --git a/Cargo.toml b/Cargo.toml index 5bd6e30..41058cd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ members = [ "gateway", "voice-node", "serverd", + "hub", ] [workspace.package] diff --git a/deploy/central/README.md b/deploy/central/README.md new file mode 100644 index 0000000..499be11 --- /dev/null +++ b/deploy/central/README.md @@ -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/-/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. diff --git a/deploy/central/central.loki-code.dev.conf b/deploy/central/central.loki-code.dev.conf new file mode 100644 index 0000000..f1abf2b --- /dev/null +++ b/deploy/central/central.loki-code.dev.conf @@ -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; + } +} diff --git a/deploy/central/hub.env.example b/deploy/central/hub.env.example new file mode 100644 index 0000000..df18f40 --- /dev/null +++ b/deploy/central/hub.env.example @@ -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 " +RUST_LOG=vnox_hub=info diff --git a/deploy/central/vnox-central.service b/deploy/central/vnox-central.service new file mode 100644 index 0000000..6478cdf --- /dev/null +++ b/deploy/central/vnox-central.service @@ -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 diff --git a/docs/design/brand/vnox-link.svg b/docs/design/brand/vnox-link.svg new file mode 100644 index 0000000..4cede19 --- /dev/null +++ b/docs/design/brand/vnox-link.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/design/social-presence-sharing.md b/docs/design/social-presence-sharing.md new file mode 100644 index 0000000..123c430 --- /dev/null +++ b/docs/design/social-presence-sharing.md @@ -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). diff --git a/hub/Cargo.toml b/hub/Cargo.toml new file mode 100644 index 0000000..8c2862d --- /dev/null +++ b/hub/Cargo.toml @@ -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"] } diff --git a/hub/README.md b/hub/README.md new file mode 100644 index 0000000..17a05f6 --- /dev/null +++ b/hub/README.md @@ -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 " +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. diff --git a/hub/assets/index.html b/hub/assets/index.html new file mode 100644 index 0000000..31a1d82 --- /dev/null +++ b/hub/assets/index.html @@ -0,0 +1,4 @@ + +Vnox Central + +
Vnox Central
Сервис развёрнут · базовый этап

Центр сети Vnox

Здесь появятся общий профиль, друзья и поиск серверов. Сейчас подготовлены служба, постоянная identity, база данных и почтовый транспорт.

  • Регистрация и вход пока не включены.
  • Каталог серверов, личные сообщения и маркетплейс ещё разрабатываются.
  • Сообщества обслуживают свои чаты и голос самостоятельно.
Vnox · собственные сообщества, общее пространство для общения.
diff --git a/hub/assets/vnox-mark.png b/hub/assets/vnox-mark.png new file mode 100644 index 0000000000000000000000000000000000000000..fc064b2750c73ae1e1ba4e9589d9c5b4a291e342 GIT binary patch literal 3114 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 literal 0 HcmV?d00001 diff --git a/hub/assets/vnox-mark.svg b/hub/assets/vnox-mark.svg new file mode 100644 index 0000000..4cede19 --- /dev/null +++ b/hub/assets/vnox-mark.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/hub/migrations/0001_foundation.sql b/hub/migrations/0001_foundation.sql new file mode 100644 index 0000000..554dbcd --- /dev/null +++ b/hub/migrations/0001_foundation.sql @@ -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 +); diff --git a/hub/src/config.rs b/hub/src/config.rs new file mode 100644 index 0000000..e239a2e --- /dev/null +++ b/hub/src/config.rs @@ -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, +} + +/// 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::from_lookup(|name| std::env::var(name).ok()) + } + + pub fn from_lookup(get: impl Fn(&str) -> Option) -> Result { + let bind = get("HUB_BIND") + .unwrap_or_else(|| "127.0.0.1:17843".into()) + .parse::() + .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::() + .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 ".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 { + 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) +} diff --git a/hub/src/database.rs b/hub/src/database.rs new file mode 100644 index 0000000..3aa36cc --- /dev/null +++ b/hub/src/database.rs @@ -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 { + 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) +} diff --git a/hub/src/identity.rs b/hub/src/identity.rs new file mode 100644 index 0000000..f3afdf2 --- /dev/null +++ b/hub/src/identity.rs @@ -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 { + 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); + } +} diff --git a/hub/src/lib.rs b/hub/src/lib.rs new file mode 100644 index 0000000..af74370 --- /dev/null +++ b/hub/src/lib.rs @@ -0,0 +1,5 @@ +pub mod config; +pub mod database; +pub mod identity; +pub mod mail; +pub mod web; diff --git a/hub/src/mail/layout.rs b/hub/src/mail/layout.rs new file mode 100644 index 0000000..84ebe3c --- /dev/null +++ b/hub/src/mail/layout.rs @@ -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!( + "

{}

", + escape(value) + ) + }) + .collect::(); + let code = content.code.map(|value| format!("

{}

", escape(value))).unwrap_or_default(); + let title = escape(content.title); + let url = escape(content.url); + let origin = escape(content.origin); + format!( + r##"{title} + +
{preheader}
+
+ +
+
VVnox
+

Личное пространство для общения

+

{title}

+
{paragraphs}{code} +
{button}
+

{expiry}

+

Если кнопка не открывается, скопируй ссылку:

+
{url}
+

Не запрашивал это действие? Не передавай код или ссылку другим людям. Если это письмо о новом устройстве, проверь активные сеансы.

+
Автоматическое письмо Vnox. Отвечать на него не нужно.
{origin}
"##, + preheader = escape(content.preheader), + button = escape(content.button), + expiry = escape(content.expiry), + ) +} diff --git a/hub/src/mail/mod.rs b/hub/src/mail/mod.rs new file mode 100644 index 0000000..f3565c5 --- /dev/null +++ b/hub/src/mail/mod.rs @@ -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, + from: Mailbox, +} + +impl Mailer { + pub fn new(config: &SmtpConfig) -> Result { + let builder = if config.port == 465 { + AsyncSmtpTransport::::relay(&config.host) + } else { + AsyncSmtpTransport::::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(()) + } +} diff --git a/hub/src/mail/templates.rs b/hub/src/mail/templates.rs new file mode 100644 index 0000000..e967cef --- /dev/null +++ b/hub/src/mail/templates.rs @@ -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 { + 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::>(); + 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(()) +} diff --git a/hub/src/main.rs b/hub/src/main.rs new file mode 100644 index 0000000..d990fa1 --- /dev/null +++ b/hub/src/main.rs @@ -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::>(); + 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; +} diff --git a/hub/src/web.rs b/hub/src/web.rs new file mode 100644 index 0000000..453fbf0 --- /dev/null +++ b/hub/src/web.rs @@ -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) -> 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 { + Json(json!({"status": "ok", "service": "vnox-hub"})) +} + +async fn ready(State(state): State>) -> (StatusCode, Json) { + 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 { + Json(json!({ + "service": "vnox-hub", + "version": env!("CARGO_PKG_VERSION"), + "api_version": 1, + "stage": "foundation" + })) +} + +async fn info(State(state): State>) -> Json { + 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, 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 +} diff --git a/hub/tests/foundation.rs b/hub/tests/foundation.rs new file mode 100644 index 0000000..4d6c204 --- /dev/null +++ b/hub/tests/foundation.rs @@ -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 { + let values = values + .iter() + .map(|(key, value)| (*key, *value)) + .collect::>(); + 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) { + 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()); +} diff --git a/hub/tests/mail.rs b/hub/tests/mail.rs new file mode 100644 index 0000000..6cba93e --- /dev/null +++ b/hub/tests/mail.rs @@ -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\"&", + }, + ) + .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: "", + }, + ) + .unwrap(); + assert!(email.html.contains("<img src=x onerror=evil()>")); + assert!(!email.html.contains("")); +} + +#[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 ".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")); +}