Commit Graph

9 Commits

Author SHA1 Message Date
nineap 864d4bc852 CI сам собирает .env на прод/dev VPS из repo Variables/Secrets
Раньше .env копировался на сервер руками по .env.example — теперь
deploy-prod/deploy-dev в deploy.yml пишут его сами перед docker compose up,
тем же принципом, что уже был у netrunner-data. .env.example остаётся
только как справочник по составу переменных, не инструкция "скопируй на
сервер".
2026-07-10 18:18:47 +07:00
nineap 591643d364 Чинит .env.example: убирает мёртвый ADMIN_TG_ID, добавляет PROXY_INTERNAL_SECRET
ADMIN_TG_ID нигде не читается с тех пор, как admin_guard заменили на ролевую
систему (owner/staff/node_manage/partner_guard) — оставлять его в примерах
вводит в заблуждение. PROXY_INTERNAL_SECRET, наоборот, обязателен (main.rs
падает без него при старте), но отсутствовал во всех трёх .env*.example.

Заодно поправлен src/modules/auth/README.md — описывал admin_guard,
которого больше не существует.
2026-07-09 15:33:33 +07:00
nineap 375b333978 Ролевая админка (Owner/Moderator/Partner) + оплата через @CryptoBot
Ролевая система вместо привязки к Telegram
----------------------------------------
Раньше единственный способ получить админ-доступ — admin_guard, пускавший
по ADMIN_TG_ID или role=="admin" (без сеттера для роли). Заменяет на
Owner/Moderator/Partner:

- migrations/0005_roles_and_partners.sql — username/password_hash на users
  (NULL у обычных Ghost/Telegram-юзеров, тот же паттерн, что и у seed_hash/
  tg_id), can_manage_nodes, commission_percent, partner_code,
  referred_by_partner_id; новые таблицы partner_commissions и
  withdrawal_requests.
- auth/guard.rs — admin_guard заменён на owner_guard/staff_guard/
  node_manage_guard/partner_guard; ADMIN_TG_ID убран из ApiState и main.rs.
- auth/service.rs — hash_password/login_staff со случайной Argon2-солью на
  каждого юзера (не общий фиксированный ARGON_SALT, который годится для
  высокоэнтропийных seed-логинов, но не для человеческих паролей).
- POST /api/v1/auth/admin/login — вход модератора/партнёра/овнера паролем,
  переиспользует существующий issue_session().
- --create-owner CLI-флаг (main.rs) со скрытым вводом пароля (rpassword) —
  вместо ручного SQL для создания первого владельца с VPS-консоли.
- src/modules/staff/ — эндпоинты создания модераторов/партнёров, переключения
  can_manage_nodes, списка заявок на вывод и их approve/reject/paid.
- Комиссия партнёра начисляется в BillingService::confirm_payment отдельным
  шагом после существующей рефералки, пересчитывается через
  get_plan_price(invoice.plan_name, invoice.currency) — НЕ через
  invoice.amount напрямую, потому что у провайдеров разная внутренняя
  единица (TON — nanoTON+2% буфер, CryptoBot — фиатные центы напрямую).
- bot.rs — /start p_XXXXXX привязывает покупателя к партнёру по коду
  (first-wins, до существующих веток numeric-tg_id-рефералки и кода входа).
- frontend/ — AdminLogin/AdminLayout/StaffPage/WithdrawalsPage/EarningsPage
  поверх существующего Vite-админ-фронта (без отдельного проекта).

Оплата через @CryptoBot
------------------------
- modules/billing/providers/cryptobot.rs — новый PaymentProvider (Crypto Pay
  API), плюс попутно исправлены два реальных бага в существующем коде:
  confirm_payment был жёстко завязан на TON-провайдера при любом инвойсе, и
  InvoiceRecord не хранил currency, из-за чего TON-курс молча применялся ко
  всем провайдерам вместо родной валюты инвойса.
- bot.rs — экран выбора способа оплаты для CryptoBot-инвойсов.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-08 22:53:02 +07:00
nineap 1a26403afb Переключить dev Caddy на порт 443 вместо 8443
Telegram Login Widget в браузере требует именно порт 443 — его CSP
frame-ancestors от oauth.telegram.org не учитывает порт домена и всегда
подразумевает дефолтный порт схемы, поэтому на 8443 виджет рендерился, но
iframe блокировался как cross-origin. VPN-нода, ранее занимавшая 443 на
dev VPS, перенесена на другой порт, так что конфликта больше нет.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-05 20:00:09 +07:00
nineap d22cd0de41 Add Caddy for real TLS on dev — Telegram Web Apps require https://
Bot buttons that open a Web App (Личный Кабинет/Тарифы/Синдикат) appeared
to load and then silently do nothing on the dev stand. Root cause:
teloxide's WebAppInfo::url (and the underlying Bot API) requires an HTTPS
URL — Telegram's client refuses to render a Web App served over plain
HTTP, with no error surfaced to the user, just a stuck loading state.
WEB_APP_BASE_URL was http://dev.netrunner-vpn.com:8080.

Port 443 on the dev VPS is already in use by a VPN node, and port 80 is
closed, so a normal HTTP-01 ACME challenge won't work. Added a custom
Caddy build (caddy-dns/cloudflare) terminating TLS via DNS-01 on port
8443 instead, reverse-proxying to the existing plain-HTTP app container.
WEB_APP_BASE_URL and the CORS/CSRF allowlists now point at the :8443
origin, and COOKIE_SECURE reverts to true (the default, matching prod) —
now that the backend actually has real TLS to serve it over, we no
longer need the plain-HTTP workaround introduced for the earlier
cookie-drop bug. Verified the custom image builds and the Caddyfile
validates (only the dummy Cloudflare token used for the local test is
rejected, as expected).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-04 19:36:38 +07:00
nineap acfcdbe90e Make the Secure cookie attribute configurable for TLS-less dev stands
Session cookies were hardcoded Secure, which is correct for prod but
silently breaks every non-localhost HTTP dev deployment: browsers (and
any spec-compliant HTTP client, verified with curl against a container IP
and against dev.netrunner-vpn.com directly) refuse to store a Secure
cookie received over plain HTTP unless the host is localhost. The dev VPS
serves everything over plain HTTP with no reverse-proxy/TLS by design, so
every login there was silently failing to persist a session at all —
this is a bigger, more fundamental gap than the cookie-sharing-with-the-
landing question that led to finding it.

Added COOKIE_SECURE (defaults true) alongside the existing COOKIE_DOMAIN,
logs a loud warning when disabled, and turned it off for the dev-remote
and local docker-dev env templates. Verified end-to-end against a
non-localhost address that the cookie now actually gets stored and a
follow-up authenticated request succeeds.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-04 19:20:14 +07:00
nineap a7607e4b33 dev-remote: use dev.netrunner-vpn.com instead of a bare IP for Telegram
Telegram Login Widget refuses to run on a raw IP ("Bot domain invalid")
— BotFather's /setdomain only accepts an actual domain name. Switched
WEB_APP_BASE_URL and the landing origin in CORS/CSRF allowlists to
dev.netrunner-vpn.com (DNS A-record -> 45.76.161.137), and called out
explicitly that the dev bot must be a separate BotFather bot from prod —
reusing the prod bot's username on this host was guaranteed to fail since
its domain is already registered to the real prod domain.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-04 18:48:51 +07:00
nineap 52531dd41a Unify auth into refresh-token cookie sessions; server-authoritative nodes and Cyberhack
Auth was effectively broken for every login path: the Telegram handler
built a Set-Cookie header but never attached it to the response, and
Ghost Protocol (seed) login never set a cookie at all — so billing, the
game, and admin actions never actually worked once the frontend was fixed
to stop trying to read an HttpOnly cookie from JS. Replaced the bare
10-minute JWT with AuthService::issue_session: a 15-minute access cookie
plus a rotating 30-day refresh cookie (opaque token, only its SHA-256
hash stored in the new refresh_sessions table); reusing an already-
rotated refresh token now revokes every session for that user. CSRF/CORS
origin allowlists moved from a single hardcoded domain to env-configured
lists so the same session works across the landing and account subdomains.
The bot's WebApp deep links (Личный Кабинет/Тарифы/Синдикат) now bridge
through a short-lived bootstrap token exchanged via POST /auth/exchange
instead of a bare access token in the URL.

Nodes: /nodes/routing now serializes the tunnel_* fields, public_key,
sni_domain and a one-time session token gated on an active subscription
instead of a stub ip/port/protocol list; node provisioning returns 202
immediately and finishes in the background instead of blocking the
request for the whole SSH run; a new background task TCP-pings nodes
every 60s and flips online/offline itself; admin can now force-restart a
node over SSH.

Billing: TON exchange rate is cached in Redis (60s) instead of hitting
TonAPI on every invoice, and the request/response now actually uses the
requested currency and TonAPI's real (uppercase) key casing — previously
only USD/RUB were ever requested and the lookup used the wrong case, so
non-USD/RUB plans could never price correctly.

Cyberhack: the server now generates and stores the board itself and
replays the client's raw click path to compute the score, instead of
clamping a client-reported number — closes the "final score is whatever
the browser sends" hole flagged in the security audit.

Frontend: api.ts no longer tries to read the HttpOnly session cookie from
JS (that never worked) and instead relies on same-origin credentials plus
a silent refresh-and-retry on 401; AdminDashboard's restart/delete actions
are wired up; Auth.tsx drops the artificial delays and requires an
explicit seed download/confirmation before continuing, since a lost Ghost
seed is unrecoverable.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-04 15:29:51 +07:00
nineap 465570267d ci: split deploy pipeline into dev (auto) and prod (manual) jobs
Add slim docker-compose.dev-remote.yml (app+db+redis, no monitoring)
for the remote dev VPS, and a deploy-dev job that auto-runs after a
successful image build on main. Bump Dockerfile.dev's Rust image so
edition2024 dependencies build. Stop tracking .env.dev (real secrets
were committed) in favor of .env.dev.example / .env.dev-remote.example
templates.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-03 15:56:16 +07:00