Skip to main content

Python SDK for orchestrating sing-box VPN nodes

Project description

prismacore

Python SDK для управления sing-box VPN-нодами через PrismaCore Server API.

Оркестрация нескольких серверов, выбор ноды по региону/latency, сборка подписок для клиентов (Happ, v2rayNG и т.д.).

pip install prismacore

Требования: Python 3.10+. Redis опционален (кэш подписок).


Быстрый старт

import asyncio
from prismacore import PrismaCore

async def main():
    async with PrismaCore.single_node(
        url="http://203.0.113.10:8000",
        token="your-api-token",
    ) as core:
        await core.node().users.create_simple("alice", inbound_tags=["vless-in"])
        sub = await core.subscriptions.build("alice")
        print(sub[:80])

asyncio.run(main())

API-токен создаётся на server: POST /api/v1/auth/token.
Server — отдельный компонент, см. репозиторий.


Несколько серверов

from prismacore import PrismaCore, ServerConfig

core = PrismaCore([
    ServerConfig(url="https://de.example.com", token="...", region="de", name="de-1"),
    ServerConfig(url="https://fi.example.com", token="...", region="fi", name="fi-1"),
])

await core.node("de-1").users.list()
best = await core.regions.fastest_node("de")
Поле ServerConfig Назначение
url, token Адрес и токен PrismaCore server
region Логическая группа (de, fi, …)
name Идентификатор ноды для core.node("name")
role vpn или backup_vpn
public_host Публичный host (метка; ссылки строит server)

CRUD на ноде

node = core.node()  # или core.node("de-1")

await node.users.create_simple("alice", inbound_tags=["vless-in"])
await node.inbounds.create({"type": "vless", "tag": "vless-in", "listen_port": 443})
await node.outbounds.list()
await node.routes.delete(1)
await node.system.get_current_config()

Ресурсы: users, inbounds, outbounds, routes, system.
На каждом — create, list, get, update, delete.


Подписки

SDK собирает подписку с нескольких нод. HTTP-эндпoинт для клиентов не входит в пакет — оборачиваете сами:

text = await core.subscriptions.build(
    "alice",
    regions=["de", "fi"],
    fastest_only=True,   # одна быстрая нода на регион
    fmt="base64",        # или "raw"
)

await core.subscriptions.invalidate("alice", regions=["de", "fi"])

Пример FastAPI:

from fastapi.responses import PlainTextResponse

@app.get("/sub/{user_name}")
async def sub(user_name: str):
    body = await core.subscriptions.build(user_name, regions=["de", "fi"])
    return PlainTextResponse(body, media_type="text/plain", headers={
        "Profile-Title": "My VPN",
    })

Кэш (Redis)

from prismacore import CacheConfig

core = PrismaCore(servers=[...], cache_config=CacheConfig(enabled=True))

После изменения пользователей или инбаундов вызывайте subscriptions.invalidate(), иначе клиенты получат устаревшую подписку.


Ошибки

Исключение Когда
ConfigError Неверный конфиг, несколько нод без имени
TransportError Сеть
AuthError 403 — неверный token
NotFoundError 404
ConflictError 409

Все наследуют PrismaCoreError.


Импорт

from prismacore import (
    PrismaCore,
    ServerConfig, CacheConfig, ProbeConfig,
    UserCreate, InboundCreate, OutboundCreate, RouteCreate,
)

Документация

Полный reference: sdk.md

Server (отдельный репозиторий): PrismaCore

English: README.en.md


License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

prismacore-0.2.0.tar.gz (17.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

prismacore-0.2.0-py3-none-any.whl (22.3 kB view details)

Uploaded Python 3

File details

Details for the file prismacore-0.2.0.tar.gz.

File metadata

  • Download URL: prismacore-0.2.0.tar.gz
  • Upload date:
  • Size: 17.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.13

File hashes

Hashes for prismacore-0.2.0.tar.gz
Algorithm Hash digest
SHA256 dc5c5bdbbf00421336f8bad5fc641f0c1b22f2ea2e203cc582bb00ca1b87df93
MD5 24fbf9de0383c69db062595474a6301c
BLAKE2b-256 87571827f46ca11cf452a2c5b1cc79ac4c37e4764c3e08e9053c83be585a4f78

See more details on using hashes here.

File details

Details for the file prismacore-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: prismacore-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 22.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.13

File hashes

Hashes for prismacore-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 51c4361576f82c2743c7ce1db892d07b36deff6548f280c61e345376dc8fad35
MD5 bc50415fa967eb723165249aaaaac70f
BLAKE2b-256 a287916d3661e0d9de27b3bdf217f5d32158decf1622bfbca3c8ede6d4c5c4b3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page