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 client 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 client 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 client import CacheConfig
core = PrismaCore(servers=[...], cache_config=CacheConfig(enabled=True))
После изменения пользователей или инбаундов вызывайте subscriptions.invalidate(), иначе клиенты получат устаревшую подписку.
Ошибки
| Исключение | Когда |
|---|---|
ConfigError |
Неверный конфиг, несколько нод без имени |
TransportError |
Сеть |
AuthError |
403 — неверный token |
NotFoundError |
404 |
ConflictError |
409 |
Все наследуют PrismaCoreError.
Импорт
from client import (
PrismaCore,
ServerConfig, CacheConfig, ProbeConfig,
UserCreate, InboundCreate, OutboundCreate, RouteCreate,
)
Документация
Полный reference: docs/sdk.md
Monorepo (server + deploy): github.com/DevGMoree/PrismaCore
English: client/README.en.md
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file prismacore-0.1.1.tar.gz.
File metadata
- Download URL: prismacore-0.1.1.tar.gz
- Upload date:
- Size: 18.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9681990e5db6d959601ffe7766e24431674774004985cfab5c38dffe8cf81f9f
|
|
| MD5 |
c5fbfc5020760f9ddcbb7ed3b9b4fc49
|
|
| BLAKE2b-256 |
f65f27ebcd52291565201965defaccf9d315bd483d3daa721d89ead72e7d1f66
|
File details
Details for the file prismacore-0.1.1-py3-none-any.whl.
File metadata
- Download URL: prismacore-0.1.1-py3-none-any.whl
- Upload date:
- Size: 24.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6ca10df2252e5a2ff19c91ed2898a5cb912369ab04ea418df9ad7ca3192e4b72
|
|
| MD5 |
1f84b80f8a667b82c05e2b4f97b515c5
|
|
| BLAKE2b-256 |
aead3631a6538a9f29cfea01a093723e9fe1a2df646e0d2f5c27280855927293
|