Powrót do strony głównej

FastAPI + Marzban: automatyzacja serwisu VPN

Serwis automatyzuje wydawanie kluczy VPN: rejestracja, płatność, vless od Marzban. Używa FastAPI async, PostgreSQL, webhooks YuKassa z idempotentnością, Cloudflare. Szczegóły kodu: modele, cachowanie, trial, zadania w tle.

Budowa serwisu VPN: FastAPI, Marzban, async SQLAlchemy
Advertisement 728x90

Zautomatyzowany serwis ochrony VPN z FastAPI, integracją Marzban i Dockerem

Backend FastAPI integruje się z Marzban do tworzenia użytkowników VPN, YooKassa do płatności, Resend do emaili. Użytkownik rejestruje się, weryfikuje email, płaci — natychmiast otrzymuje klucz vless. Architektura oparta na async SQLAlchemy zapewnia równoległe przetwarzanie webhooków, zapytań do API Marzban i wysyłkę emaili bez blokad.

Stos technologiczny: Python 3.11, FastAPI, PostgreSQL, React 18 + Vite + Tailwind, XRay-core przez Marzban, Docker Compose + Nginx + Cloudflare.

Architektura systemu

Ruch przechodzi przez Cloudflare → Nginx: statyczny React na :3000, API na :8080. Routery FastAPI (/auth, /configs, /payment) komunikują się z PostgreSQL, REST API Marzban, Resend i YooKassa/Plisio.

Google AdInline article slot

Marzban działa na hoście poza Dockerem; kontenery łączą się przez interfejs bridge.

Użytkownik
    ↓ HTTPS
Cloudflare
    ↓
Nginx
  / → frontend:3000
  /api/ → backend:8080
    ↓
FastAPI → PostgreSQL | Marzban | Resend | YooKassa

Modele bazy danych

Główne encje:

class User(Base):
    __tablename__ = "users"
    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str] = mapped_column(unique=True, index=True)
    hashed_password: Mapped[str]
    is_verified: Mapped[bool] = mapped_column(default=False)
    marzban_username: Mapped[str | None] = mapped_column(unique=True, nullable=True)
    referral_code: Mapped[str] = mapped_column(unique=True, default=lambda: secrets.token_urlsafe(8))
    trial_used: Mapped[bool] = mapped_column(default=False)
    email_verify_token: Mapped[str | None] = mapped_column(nullable=True, index=True)

class Subscription(Base):
    __tablename__ = "subscriptions"
    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    plan: Mapped[str]
    status: Mapped[str]  # active | expired | pending
    devices: Mapped[int] = mapped_column(default=1)
    started_at: Mapped[datetime] = mapped_column(server_default=func.now())
    expires_at: Mapped[datetime]
    marzban_expire_ts: Mapped[int]

class Payment(Base):
    __tablename__ = "payments"
    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    provider: Mapped[str]  # yookassa | plisio
    external_id: Mapped[str]
    amount: Mapped[float]
    status: Mapped[str]  # pending | paid | failed
    plan: Mapped[str]
    months: Mapped[int]

Integracja z Marzban

Buforowanie tokenu API

Token Marzban wygasa po godzinie. Bufor na 55 minut z asyncio.Lock zapobiega warunkom wyścigu:

Google AdInline article slot
class MarzbanService:
    def __init__(self):
        self._token: str | None = None
        self._token_expires_at: float = 0
        self._lock = asyncio.Lock()

    async def get_token(self) -> str:
        async with self._lock:
            if self._token and time.time() < self._token_expires_at:
                return self._token
            self._token = await self._fetch_token()
            self._token_expires_at = time.time() + 55 * 60
            return self._token

Tworzenie użytkownika VPN

async def create_user(self, username: str, months: int, days: int = 0) -> dict:
    expire_ts = _months_to_timestamp(months)
    if days:
        expire_ts = int(datetime.now(timezone.utc).timestamp()) + days * 86400

    payload = {
        "username": username,
        "proxies": {"vless": {"flow": "xtls-rprx-vision"}},
        "inbounds": {"vless": ["VLESS Reality"]},
        "expire": expire_ts,
        "data_limit": 0,
        "data_limit_reset_strategy": "no_reset",
    }
    async with httpx.AsyncClient(timeout=15) as client:
        resp = await client.post(
            f"{settings.MARZBAN_URL}/api/user",
            json=payload,
            headers=await self._headers(),
        )
        resp.raise_for_status()
        return resp.json()

Marzban zwraca gotowy vless://... w polu links.

Przedłużanie subskrypcji

Po wygaśnięciu subskrypcji przedłużenie zaczyna się od bieżącego czasu:

async def extend_subscription(self, username: str, months: int) -> dict:
    user = await self.get_user(username)
    current_expire = user.get("expire") or 0
    base = max(current_expire, int(time.time()))
    base_dt = datetime.fromtimestamp(base, tz=timezone.utc)
    # PUT /api/user/{username} z nową expire

Obsługa webhooków YooKassa

Idempotentność jest kluczowa: YooKassa duplikuje webhooki przy opóźnieniach >10s.

Google AdInline article slot
async def activate_subscription(payment: Payment) -> None:
    async with AsyncSessionLocal() as session:
        result = await session.execute(select(Payment).where(Payment.id == payment.id))
        fresh_payment = result.scalar_one()
        if fresh_payment.status == "paid":
            logger.info(f"Payment {payment.id} already activated, skipping")
            return
        try:
            await _do_activate(fresh_payment, session)
        except Exception as e:
            await session.rollback()
            logger.error(f"Activation failed: {e}", exc_info=True)
            raise

Używana jest świeża sesja DB, niezależna od webhooka.

Whitelist IP dla Cloudflare:

client_ip = request.headers.get("CF-Connecting-IP") or request.headers.get("X-Forwarded-For", "").split(",")[0].strip() or request.client.host
allowed_prefixes = ("185.71.76.", "185.71.77.", "77.75.153.", "77.75.154.", "77.75.156.")
if client_ip not in {"77.75.156.11", "77.75.156.35"} and not any(client_ip.startswith(p) for p in allowed_prefixes):
    raise HTTPException(403)

Trial i weryfikacja

3 dni VPN po potwierdzeniu emaila:

  • Użytkownik rejestruje się, otrzymuje token na email.
  • GET /verify-email/{token} aktywuje is_verified=True.
  • Zadanie w tle tworzy użytkownika Marzban z days=3, oznacza trial_used=True.

Sprawdzenie: brak aktywnej subskrypcji i trial nie został użyty.

Dynamiczne subskrypcje i urządzenia

Dokupienie urządzeń (+99 zł/szt) zachowuje się przy przedłużeniu:

extra_devices = max(0, existing_sub.devices - plan_cfg["devices"])
existing_sub.devices = plan_cfg["devices"] + extra_devices

Cena: podstawowa + extra_devices * DEVICE_ADD_PRICE.

Zadania w tle

APScheduler do automatyzacji:

  • Codzienny raport (8:00).
  • Przypomnienia o wygaśnięciu (9:00).
  • Sprawdzanie pending-płatności (co 5 min).
scheduler = AsyncIOScheduler(timezone="Europe/Warsaw")
scheduler.add_job(send_daily_report, CronTrigger(hour=8, minute=0), id="daily_report")

Problemy Docker Compose

v1.29 na Ubuntu 22.04 pada przy przebudowie: KeyError: 'ContainerConfig'. Rozwiązanie:

docker-compose stop service
docker-compose rm -f service
docker-compose up -d service

Co jest ważne

  • Async FastAPI + SQLAlchemy zapewnia równoległość bez problemów GIL.
  • Idempotentność webhooków zapobiega duplikacji subskrypcji.
  • Buforowanie tokenu Marzban z lockami minimalizuje zapytania API.
  • Cloudflare wymaga jawnej weryfikacji CF-Connecting-IP dla YooKassa.
  • Trial przez weryfikację emaila ogranicza nadużycia.

— Editorial Team

Advertisement 728x90

Czytaj dalej