Skip to content

About

Fork of PasarGuard node_bridge_py, adding sing-box (Hysteria2), OpenVPN, and MTProto proxy types to the gRPC contract

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

PasarGuard Node Bridge (Python)

Note: This is the Free-Guy-IR fork of the original PasarGuard node_bridge_py, extended with OpenVPN and L2TP backends, Hysteria2, OpenVPN, TUIC and L2TP user credentials, and several backends on one node (add_backend, remove_backend, list_backends).

Wire compatibility: this fork numbers BackendType 3 and 5 as OPEN_VPN and L2TP, and Proxy fields 7, 8, 10, 11 and 12 as Hysteria2, OpenVPN, TUIC, L2TP and Masque. BackendType 2, where the fork's SING_BOX backend used to be, and BackendType 4 and Proxy field 9, where the fork's MTProto backend and credential used to be, are reserved by number and by name, as on the Free-Guy-IR node since those backends were removed. Wireguard field 3 is pre_shared_key here and upstream. Upstream PasarGuard gives BackendType 2 to its own MTProto backend, Proxy field 7 to Masque and field 8 to its own Mtproto message (bridge 0.9.5 and later, and the node's dev branch). Upstream node 0.5.4 refuses backend types 3 and 5 and ignores fields 7 to 12. Upstream nodes 0.5.6 and 0.5.7 read a fork user's Hysteria2 password as a Masque password. An upstream node with MTProto reads a fork user's OpenVPN credentials as MTProto credentials. Only the xray and WireGuard backends work the same on upstream nodes, and an upstream bridge must never drive a Free-Guy-IR node.

Async Python client for connecting to a PasarGuard node over gRPC or REST.

This package provides:

  • Strongly typed protobuf models (service_pb2)
  • Unified node API for both transport types
  • User sync helpers (single, batch, and chunked streaming)
  • Health/version helpers
  • On-demand log streaming
  • Node maintenance endpoints (update core/node/geofiles and hard reset)

Installation

This fork is not published to PyPI; pip install pasarguard-node-bridge installs the upstream package, which lacks the fork's backends and RPCs. Install it from git:

pip install "pasarguard-node-bridge @ git+https://github.com/Free-Guy-IR/node_bridge_py@main"

or, in a uv project:

[tool.uv.sources]
pasarguard-node-bridge = { git = "https://github.com/Free-Guy-IR/node_bridge_py", branch = "main" }

Requirements

  • Python >=3.12
  • A reachable PasarGuard node
  • Node service port (port) for gRPC or protobuf-REST
  • Node JSON API port (api_port) for maintenance endpoints
  • Optional PEM trust certificates or a SHA-256 leaf certificate fingerprint
  • API key (UUID string)

Import

import PasarGuardNodeBridge as Bridge
from PasarGuardNodeBridge.common import service_pb2 as service

Create A Node Client

node = Bridge.create_node(
    connection=Bridge.NodeType.grpc,  # Bridge.NodeType.grpc or Bridge.NodeType.rest
    address="127.0.0.1",
    port=2096,  # gRPC or protobuf-REST port (based on connection)
    api_port=2097,  # REST JSON API port (used internally for maintenance)
    server_ca=server_ca_pem_string,
    api_key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    name="node-1",  # optional
    extra={"region": "eu-1"},  # optional
    default_timeout=10,  # optional
    internal_timeout=15,  # optional
    proxy="socks5://user:pass@127.0.0.1:1080",  # optional
)

create_node(...) Parameters

  • connection: Bridge.NodeType.grpc or Bridge.NodeType.rest
  • address: node host/IP
  • port: node service port
  • api_port: node REST JSON API port
  • server_ca: optional PEM certificate content, defaulting to None for system trust
  • certificate_sha256: optional keyword-only SHA-256 leaf certificate fingerprint; takes precedence over PEM
  • api_key: UUID string
  • name: optional logger name
  • extra: optional metadata dictionary
  • logger: optional custom logger
  • default_timeout: default timeout for public API methods
  • internal_timeout: timeout used for internal sync/log operations
  • proxy: optional upstream proxy URL for node traffic
  • max_message_size: gRPC only, HTTP/2 window/message sizing

TLS verification

Every node and maintenance connection uses TLS and API-key authentication. Verification is selected from the saved fields, with no fallback after a failure:

Configuration Verification
Nonempty certificate_sha256 Exact leaf certificate pin, validity dates, and domain/IP SAN
Otherwise, nonempty server_ca Existing PEM trust store and hostname verification
Both absent/empty Runtime system trust store and standard identity verification

api_key is required. Both server_ca=None and certificate_sha256=None are keyword-only. Existing keyword-based PEM configurations continue working. For a publicly trusted certificate, omit server_ca and certificate_sha256 (or pass server_ca=None/""). For self-signed certificates, pass certificate_sha256="ab..." using the SHA-256 of the complete leaf certificate DER encoding. Contiguous hexadecimal and colon-separated byte pairs are accepted case-insensitively and normalized. Nonempty PEM is validated even when a pin takes precedence. Pinned verification requires a matching SAN; the Common Name is never used as a fallback.

The main service and maintenance endpoints must present the same leaf certificate when pinned, including behind a TLS-terminating proxy. The address and both ports identify the TLS frontend; the bridge has no plaintext backend option. HTTP redirects are disabled. Established streams and pooled connections remain usable after certificate expiry. Fresh connections repeat date, identity, and trust/pin verification before sending credentials; a matching pin never bypasses date checks. Health-check reconnection attempts use exponential backoff with jitter from one second up to one minute. Direct requests and interrupted mutations are not automatically replayed.

node.get_tls_status() returns separate service and maintenance observations in memory. Each contains fingerprint, not_valid_before, not_valid_after, observed_at (UTC datetimes), connection_error, error_at, unknown, and stale. Only a fresh verified handshake refreshes the certificate observation and clears a connection error. Errors retain the last verified certificate; unknown or expired observations are stale. Treat an expired observation as “last observed certificate expired”: an established connection may still work while fresh connections fail. Applications can apply additional age limits using observed_at. Creating a new client for an endpoint change or calling configure_tls(...) clears both observations. Pins and PEM are never automatically replaced.

NodeConfig and registry helpers preserve the optional fingerprint through serialization. To change verification on a live client, use await node.configure_tls(server_ca=pem, certificate_sha256=pin). This replaces both verification fields and retires existing connections and pools. Omitted fields are cleared: await node.configure_tls() selects system trust, and await node.configure_tls(server_ca=pem) restores PEM verification. Invalid replacement fields leave the current connections intact. Panel applications may instead dispose of the old client and create a new one whenever either verification field changes.

Proxy Formats

  • socks5://127.0.0.1:1080
  • socks5://user:pass@127.0.0.1:1080
  • socks4://127.0.0.1:1080
  • http://127.0.0.1:3128
  • http://user:pass@127.0.0.1:3128
  • https://user:pass@proxy.example.com:443

REST and maintenance requests support HTTPS proxies with certificate pinning. The proxy certificate is verified against the runtime system trust store, including its hostname, before proxy credentials are sent. The node certificate is verified separately against certificate_sha256 inside the tunnel. For a private proxy CA, configure the runtime trust store (for example, SSL_CERT_FILE); server_ca and certificate_sha256 describe the node. gRPC does not support HTTPS proxies.

Connection Types

  • Bridge.NodeType.grpc: gRPC transport via grpclib
  • Bridge.NodeType.rest: protobuf-over-HTTP transport

User/Proxy Builders

Use helpers for creating protobuf user/proxy payloads.

user = Bridge.create_user(
    email="alice@example.com",
    proxies=Bridge.create_proxy(
        vmess_id="0d59268a-9847-4218-ae09-65308eb52e08",
        vless_id="0d59268a-9847-4218-ae09-65308eb52e08",
        vless_flow="",
        trojan_password="",
        shadowsocks_password="",
        shadowsocks_method="",
        wireguard_public_key="",
        wireguard_peer_ips=["10.10.0.2/32"],
    ),
    inbounds=["inbound-tag-1"],
)

Start/Stop Lifecycle

You should start() before calling stats/sync/log methods.

await node.start(
    config=config_json_string,
    backend_type=service.BackendType.XRAY,
    users=[user],  # optional initial user set
    keep_alive=30,  # optional
    exclude_inbounds=[],  # optional
    timeout=20,
)

info = await node.info()
print(info.node_version, info.core_version)

await node.stop()

backend_type accepts XRAY, WIREGUARD, OPEN_VPN or L2TP.

Method Examples

1. Queue-Based User Updates (recommended for frequent updates)

update_user and update_users enqueue users and a background worker handles retries and batching.

The worker claims at most sync_batch_size users per delivery (default: 100). Nodes supporting chunked sync (>=0.2.0) use that transport even for small updates; older nodes retain the per-user transport. sync_chunk_size controls the number of users per stream message (default: 100). Both options are positive integers accepted by create_node(...) and create_node_from_config(..., **runtime_overrides).

sync_lease_seconds (default: 30) bounds the entire queued delivery, including storage reads, an optional resolver, waiting for the transport lock, and sending all chunks. Delivery is cancelled before the lease expires. Failed deliveries and storage errors retry with exponential backoff up to 30 seconds.

A node fails the whole batch when it cannot apply one user in it. Such a rejected batch is split until the rejected users are alone, so everyone else is still delivered. A round makes at most 16 sends for this and starts none that could outlast the round; users not tested by then go back to the queue at once (to be sent one by one if the round found as many rejected users as accepted ones). Every send after the first in a round is cancelled if the round's deadline passes, and its users are sent again in the next round. Users the node rejected before are retried as one batch, then one by one if it is rejected again. The rejected users leave the queue and are queued again after a backoff, so they never hold back later updates: 2 seconds doubling to 60 seconds; after about 10 minutes an add is retried every 5 minutes (a removal stays at 60 seconds) and one error is logged for that user. Nothing is dropped. A retry goes back through the store and is claimed with a lease like any other update, so a newer update for the same user always wins. A held payload is never queued again under a new revision. How a rejected user waits out its backoff depends on what the store provides:

  • Held retry, when the store has hold_users(node_id, tokens, retry_after) and retire_held(node_id, tokens) (the default store has both, see HeldRetryUserSyncStoreProtocol; a store with only one of them is used as a refresh or lease store, and each controller built on it logs one warning naming the missing method). The controller releases the claim with hold_users instead of ack_users, with retry_after set to the user's backoff in seconds; the users one round holds whose backoffs end within 1 second of each other share one call, held for the longest of their backoffs. For each token it still leases, the store must atomically release the claim and, when the queued entry still has the claimed revision, keep that entry queued at the same revision but not claimable until retry_after seconds have passed; a newer queued revision is not delayed. A token whose lease expired, or that was acknowledged, requeued or cleared, is ignored. A later enqueue_users for the user replaces the held entry and can be claimed at once. claim_users skips a hold that is not due and drops the hold when it claims the entry. has_pending does not report a hold that is not due, so no controller polls for it. capture_queued reports held entries with their revision, retire_captured drops a held entry whose captured revision it retires, and clear drops every hold. retire_held drops, for each token, the queued entry if it is still at the revision that token held (or still leases) and no other worker leases it; a newer revision is never dropped, and an unknown token is ignored. The retry thus lives in the store: a full sync through sync_users_from_source(...) on any controller covers it, a controller that stops does not lose it, and flush_pending_users() on any controller cancels it. Once it is due it is claimed at the next wake of a controller on the store: the holding controller wakes at its due time, and any controller wakes on an update, a connect(...) or wake_sync_worker(). A controller whose worker has exited is not woken by a hold ending, so if the holding controller stops, the retry waits for the next such wake. When the holding controller's due claim does not return the user (the store measures the hold on its own clock, or another worker claimed it), it claims again after 0.05, 0.25, 1 and 5 seconds. The controller only keeps the attempt count and the next delay.
  • Refresh, when the store has request_refresh(node_id, emails) but not both hold_users and retire_held, as a store that rebuilds payloads from application state does. The controller acknowledges the claim and, once the backoff is over, calls request_refresh so the store queues the user's current state. Until then the retry exists only in this controller's memory, so a controller that stops before it is due loses it, and the next full sync is what delivers that user.
  • Lease, when the store has neither request_refresh nor both held-retry methods. The controller neither acknowledges nor requeues the claim: it keeps the lease for the backoff, then returns the claim with requeue_users, so the queued entry keeps its revision and a newer update replaces it. While it keeps claims it does not poll has_pending; it still wakes at least every 5 seconds. Leases are not renewed, so on these stores a backoff lasts at most sync_lease_seconds, after which any controller can claim the user again. A newer update through the keeping controller returns that user's kept claim at once, a successful start(...) or sync_users(...) acknowledges its kept claims (an entry still at the kept revision is dropped, a newer one stays queued; a claim whose lease already expired, which happens when the backoff is longer than sync_lease_seconds, is not dropped and its payload may still be sent after the snapshot), and an active full-sync fence makes it return all its kept claims at its next wake, sync_batch_size per store call. A store call that fails or takes longer than internal_timeout while returning kept claims to an active fence is logged and tried again at a later wake, with the usual back-off, but it is not counted as a failed round: it is storage slowness, not the node, so it never brings a healthy node closer to a hard reset. A full sync therefore waits at most about 5 seconds for the kept claims of a controller whose worker runs against a healthy node, and otherwise (the controller stopped or died, or its node is disconnected or broken) at most one lease, when they expire. A newer update for a kept user through another controller is queued but cannot be claimed until the keeper returns its claim: up to the backoff or one lease, whichever ends first. Because has_pending reports leased work, every other controller whose worker is running polls the store (fence_state, claim_users, has_pending) every sync_poll_interval while a claim is kept; that is the cost of a store without hold_users or request_refresh. capture_queued_work() gives up after sync_lease_seconds + 5 seconds with TimeoutError, and then no snapshot is sent and nothing is retired.

A newer update through this controller forgets the user's backoff, and a successful start(...), sync_users(...) or flush_pending_users() clears all of them. After start(...) or sync_users(...) the payloads held for this controller's retries are dropped from the store when still at the rejected revision (retire_held, or ack_users of a kept claim whose lease is still live; a refresh store has nothing queued for them), so this controller's retries do not send a pre-snapshot payload over the snapshot; a newer revision stays queued. They are dropped sync_batch_size tokens per store call, each call within internal_timeout. Tokens a failed call did not drop are tried again at the next such snapshot and at each wake of the worker before it claims anything, so a claim never sends them over the snapshot; a failure there fails that round. A direct start(...) or sync_users(...) does not touch the retries of other controllers on the store: one of them can still send its held payload after the snapshot. Use sync_users_from_source(...), whose fence and capture cover every controller's queued and held work, when several controllers share a store. A delivery round whose send is still in flight may then hold again the users it sees rejected. The backoff state lives in this controller's memory, one entry per user, and each controller on a shared store keeps its own. While a full-sync fence is active, the claim of a user held for retry is returned to the queue for the snapshot instead of being held. sync_users_chunked sets rejected=True on its returned failed list for such node rejections; transport errors are retried as a whole.

On nodes with chunked sync, rejected users do not count as failed deliveries; on older nodes every user that fails to sync fails the round. A round fails when a delivery fails for any reason other than a node rejection (transport, a timeout of the send itself, the node's core not running or another node error) or the round raises an error (storage, resolver, or its deadline passing before its first send ends); a later send cut by the round's deadline does not fail the round, its users are only sent again in the next round, and a lease store failing to take back kept claims under an active full-sync fence (see Lease above) does not fail it either. To still flag a node whose backend refuses every user, each controller counts the users rejected in its rounds that accept nobody and do not fail, except users it is already retrying after the node rejected them on their own; a user that another controller put back for a retry counts as new. Once 5 are counted and 15 seconds have passed since the first of them, requires_hard_reset() returns true, unless a round of that controller has meanwhile accepted a user without failing, which clears the count and the flag. A healthy node is flagged too when 5 or more users it rejects for their own data arrive with nothing else to deliver in that window. Independently, 5 failed rounds set the flag when no round between them accepts a user without failing. connect(...) clears both counts and the flag, and a successful start(...) or sync_users(...) restarts the rejection count, though users rejected in a round already in flight still count.

disconnect() stops this controller's worker and preserves shared queued work. connect() wakes the worker to recover it. An external producer that writes directly to the store should also notify a healthy controller with await node.wake_sync_worker(); an idle controller is not a permanent queue poller.

await node.update_user(user)

more_users = [user1, user2, user3]
await node.update_users(more_users)

Shared Storage For Multiple Workers

By default, queued user updates are kept in a process-local in-memory store shared by node instances. This coordinates controllers in a single worker process when they use the same node_id (or the same service URL when node_id is omitted). For multi-process or multi-host deployments, pass a shared user_sync_store implementation so all workers claim from the same pending-user queue. The package only defines the async protocol; Redis, NATS KV, SQL, or any other backend can be implemented by your application.

store = MyRedisUserSyncStore(redis_client)  # implements Bridge.UserSyncStoreProtocol

node = Bridge.create_node(
    connection=Bridge.NodeType.grpc,
    address="127.0.0.1",
    port=2096,
    api_port=2097,
    server_ca=server_ca_pem_string,
    api_key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    node_id="node-1",
    worker_id="worker-a",
    user_sync_store=store,
)

A UserSyncStoreProtocol implementation must provide these async methods:

  • enqueue_users(node_id, users) stores latest user payloads by email.
  • claim_users(node_id, worker_id, limit, lease_seconds) atomically leases work and returns ClaimedUser items.
  • ack_users(node_id, tokens) removes successfully synced claims.
  • requeue_users(node_id, claimed_users) makes failed claims available again.
  • clear(node_id) clears pending and claimed updates for a node.

Delivery is at-least-once. A crashed worker may cause the same latest user payload to be synced again after its lease expires, so external adapters should use atomic claim/lease operations such as Redis Lua/transactions or NATS KV revision compare-and-set.

Claims must exclude concurrent delivery of the same email until release or lease expiry. Acknowledging an older revision must preserve a newer queued update; requeuing an expired, cleared or already acknowledged token must not recreate its old payload. The default store implements these rules and copies protobuf messages so caller mutations cannot change queued work. An optional has_pending(node_id) -> bool should include leased work, allowing the worker to keep polling until it can recover an abandoned lease. Without this optional method, the worker polls through a lease recovery window after reconnect or a storage failure.

Adapters that track uncertain acknowledgements may return the affected emails from ack_users; such adapters must also provide request_refresh(node_id, emails) to durably request delivery of current application state. A store with request_refresh should also implement hold_users(node_id, tokens, retry_after) and retire_held(node_id, tokens) as described above: without them, a user the node rejected is acknowledged and its retry is kept only in the rejecting controller's memory. An optional refresh_claimed(node_id, claimed_users) can similarly replace work delivered across a full-sync fence with refresh markers. Without that hook, the worker requeues those claims using the store's normal revision checks.

Cancellation limits how long this client sends a leased batch. It cannot undo a request that a remote server has already accepted, or provide exactly-once delivery. Process-local storage does not survive process termination; use a durable shared store when that is required.

Resolve queued users from current application state

Applications can pass user_sync_resolver=resolve_users when constructing a node. This optional async callback receives (node_id, emails) and returns one current protobuf User for each requested email immediately before delivery. The library does not access an application database. Return an explicit removal payload, as appropriate for the node backend, for a deleted user. A missing email or callback failure retries the batch without sending stale fallback data.

Coordinate full snapshots with background updates

Use a deferred loader when a full snapshot must coexist with queued updates:

async def load_users():
    return await application.load_current_node_users(node.node_id)


await node.sync_users_from_source(load_users, timeout=30)

This acquires a shared full-sync fence, waits for already claimed deliveries to finish, captures queued revisions, then calls the loader and sends the snapshot. Only a successful snapshot retires captured revisions. Updates queued during the snapshot remain available for subsequent delta delivery. Failures retain queued work, and loss of the renewable fence aborts the operation. A competing full sync receives NodeAPIError(409).

The default in-memory store supports this operation across controllers in one process. External stores must implement SnapshotUserSyncStoreProtocol with atomic begin_full_sync, renew_full_sync, end_full_sync, fence_state, capture_queued and retire_captured methods. A fence has an owner token, an expiry and a monotonically increasing generation. Claims must be blocked while it is active. Captures return pending revisions and the number of live claims; retirement removes only matching revisions. Stale owners cannot renew or release a replacement fence. All controllers sharing a store must honor this contract. Stores implementing only UserSyncStoreProtocol retain the queue API, but the new snapshot helper rejects them instead of silently using a local lock.

For custom orchestration, full_sync_fence(), capture_queued_work() and retire_queued_work(captured) expose the same steps. Keep capture, the authoritative read, transmission and retirement inside the fence; call the yielded hold's check() before transmission and retirement. Prefer sync_users_from_source() unless custom orchestration is necessary.

Existing direct sync_users(...) and sync_users_chunked(...) retain their behavior. Their explicit flush_pending=True option clears queued work before sending; use sync_users_from_source() when pending updates must survive a failed full sync. flush_pending_users() remains an explicit queue discard operation.

Lifecycle operations are coordinated through the same model. The default process-local coordinator prevents concurrent start(), stop(), update_node(), update_core(), update_geofiles(), and hard_reset() calls from controllers for the same node in one process. Pass a shared lifecycle_coordinator in multi-process or multi-host deployments so only one worker can perform a lifecycle operation at a time. Read-only status cron jobs can call stats/info normally; if they write shared observed status, use the current lifecycle epoch so stale cron results cannot overwrite a newer reconnect result.

While an operation runs, the controller renews its lease by calling the coordinator's heartbeat(lease) every third of lifecycle_lease_seconds. Return True when the lease was renewed and False when this lease is no longer held (released, or expired and taken by another worker); the controller then stops renewing. An exception from heartbeat is logged and the next renewal is tried as usual.

In this fork, None means the renewal was not reported (for example a coordinator whose store retries ran out): the controller keeps renewing. A False answer is confirmed before renewal stops: while get_state(node_id) still shows this lease's epoch, owner and operation, and less than lease_seconds has passed since the last renewal that answered True was sent (or since the lease was requested), the controller keeps renewing. A get_state call that raises counts as still held until that deadline. Only a True answer moves the deadline. Renewal ends once the operation releases its lease, even if the coordinator turns that cancellation into an ordinary error. A cancellation that a coordinator's own timeout delivers inside a renewal call and turns into an error does not end renewal; a cancellation that reaches the renewal task while it waits between renewals does.

lifecycle = MyRedisLifecycleCoordinator(redis_client)

node = Bridge.create_node(
    connection=Bridge.NodeType.grpc,
    address="127.0.0.1",
    port=2096,
    api_port=2097,
    server_ca=server_ca_pem_string,
    api_key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    node_id="node-1",
    worker_id="worker-a",
    user_sync_store=store,
    lifecycle_coordinator=lifecycle,
)

state = await node.get_lifecycle_state()
health = await node.get_health()
if state is not None:
    await node.update_observed_lifecycle(
        Bridge.LifecycleStatus.HEALTHY if health is Bridge.Health.HEALTHY else Bridge.LifecycleStatus.BROKEN,
        expected_epoch=state.epoch,
    )

A lifecycle adapter must atomically acquire/release leases and fence writes with the returned epoch. This prevents a cron status job or another worker from overwriting the result of a newer start(), stop(), or reconnect flow.

Node connection configs can also be stored through a registry protocol:

registry = MyNodeRegistry(...)
config = Bridge.NodeConfig(
    connection="grpc",
    address="127.0.0.1",
    port=2096,
    api_port=2097,
    server_ca=server_ca_pem_string,
    api_key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
)

await Bridge.save_node_config(registry, "node-1", config)
node = await Bridge.create_node_from_registry(
    registry,
    "node-1",
    user_sync_store=store,
    worker_id="worker-a",
)

2. Direct User Sync

Use direct sync when you want explicit control in your flow.

await node.sync_users([user1, user2], timeout=15)

3. Chunked Sync For Large Batches

failed_users = await node.sync_users_chunked(
    users=large_user_list,
    chunk_size=500,
    timeout=30,
)

if failed_users:
    print(f"Failed users: {len(failed_users)}")

4. Stats APIs

system_stats = await node.get_system_stats()
backend_stats = await node.get_backend_stats()
latencies = await node.get_outbounds_latency()

all_outbounds = await node.get_stats(
    stat_type=service.StatType.Outbounds,
    reset=False,
)

single_user_online = await node.get_user_online_stats("alice@example.com")
single_user_ips = await node.get_user_online_ip_list("alice@example.com")

5. Health And Version Helpers

health = await node.get_health()  # Bridge.Health enum
node_ver = await node.node_version()
core_ver = await node.core_version()
node_ver2, core_ver2 = await node.get_versions()
meta = await node.get_extra()

6. On-Demand Log Streaming

stream_logs() yields an asyncio.Queue that contains log lines (str) or Bridge.NodeAPIError.

import asyncio

async with node.stream_logs(max_queue_size=200) as log_queue:
    for _ in range(20):
        item = await asyncio.wait_for(log_queue.get(), timeout=2)
        if isinstance(item, Bridge.NodeAPIError):
            raise item
        print(item)

7. Maintenance Endpoints

These methods use the node-serviced REST JSON API (api_port) for both gRPC and REST clients. Requests include the configured x-api-key and return a buffered response; read the response body with response.json().

reachable = await node.check_connectivity()
await node.update_node()
await node.update_core({"core_version": "latest"})
await node.update_core({"core_version": "v26.10.17"})
await node.update_geofiles({"region": "iran"})
await node.hard_reset()

Core versions accept latest, vX.Y.Z, or X.Y.Z. Geofile regions accept iran, russia, or china (case-insensitive).

hard_reset() runs pg-node restart on the server and disconnects the local client after success. Call start(...) again to initialize the backend. Maintenance calls use dedicated timeouts (330 seconds for updates, 90 seconds for hard reset), independent of default_timeout. Errors raise NodeAPIError with the server's status code and detail; an unreachable management API raises code 503, and a conflicting lifecycle operation raises code 409.

8. Routing APIs

Routing operations work over both gRPC and REST. They are xray-only: on a non-xray (e.g. WireGuard) node the call fails with Bridge.NodeAPIError code 501.

rules = await node.list_routing_rules()
balancer = await node.get_balancer_info("balancer-tag")

route = await node.test_route(
    inbound_tag="inbound-1",
    network="tcp",
    target_domain="example.com",
    target_port=443,
)

# `rule` is one xray routing rule as JSON (same shape as a routing.rules[] entry).
# Appended by default (keeps existing rules); pass should_reset=True to clear all
# rules + balancers before adding.
await node.add_routing_rule('{"type":"field","outboundTag":"direct","domain":["example.com"],"ruleTag":"r1"}')
await node.remove_routing_rule("r1")
await node.override_balancer_target("balancer-tag", "outbound-tag")

API Reference

Lifecycle

  • start(config, backend_type, users, keep_alive=0, exclude_inbounds=[], timeout=None)
  • stop(timeout=None)
  • info(timeout=None)
  • add_backend(config, backend_type, users, exclude_inbounds=[], timeout=None) starts another backend next to the running ones
  • remove_backend(backend_type, timeout=None)
  • list_backends(timeout=None)

Health/Version

  • get_health()
  • node_version()
  • core_version()
  • get_versions()
  • get_extra()

Stats

  • get_system_stats(timeout=None)
  • get_backend_stats(timeout=None)
  • get_stats(stat_type, reset=True, name="", timeout=None)
  • get_outbounds_latency(name="", timeout=None)
  • get_user_online_stats(email, timeout=None)
  • get_user_online_ip_list(email, timeout=None)

User Sync

  • update_user(user) (queued/background)
  • update_users(users) (queued/background)
  • sync_users(users, flush_pending=False, timeout=None) (direct)
  • sync_users_chunked(users, chunk_size=100, flush_pending=False, timeout=None) (direct streaming)

Routing

Xray-only (gRPC and REST); on a non-xray backend these raise NodeAPIError(501).

  • list_routing_rules(timeout=None)
  • get_balancer_info(tag, timeout=None)
  • test_route(inbound_tag="", network="", target_ip="", target_domain="", target_port=0, protocol="", user="", attributes=None, field_selectors=None, publish_result=False, timeout=None)
  • add_routing_rule(rule, should_reset=False, timeout=None)
  • remove_routing_rule(rule_tag, timeout=None)
  • override_balancer_target(balancer_tag, target, timeout=None)

Logging

  • stream_logs(max_queue_size=1000) async context manager returning an asyncio.Queue

Maintenance

  • check_connectivity() → bool
  • update_node()
  • update_core(json)
  • update_geofiles(json)
  • hard_reset()

Error Handling

All transport and API errors are surfaced as Bridge.NodeAPIError:

try:
    await node.get_backend_stats(timeout=5)
except Bridge.NodeAPIError as e:
    print(e.code, e.detail)

Protobuf Access

For direct protobuf usage:

from PasarGuardNodeBridge.common import service_pb2 as service

Complete Minimal Example

import asyncio
import PasarGuardNodeBridge as Bridge
from PasarGuardNodeBridge.common import service_pb2 as service


async def main():
    with open("certs/ssl_cert.pem", "r", encoding="utf-8") as f:
        server_ca = f.read()
    with open("config/xray.json", "r", encoding="utf-8") as f:
        config = f.read()

    node = Bridge.create_node(
        connection=Bridge.NodeType.grpc,
        address="127.0.0.1",
        port=2096,
        api_port=2097,
        server_ca=server_ca,
        api_key="d04d8680-942d-4365-992f-9f482275691d",
        name="example-node",
    )

    await node.start(config=config, backend_type=service.BackendType.XRAY, users=[])
    print(await node.get_system_stats())
    await node.stop()


asyncio.run(main())

Keeping the protobuf definition in sync

PasarGuardNodeBridge/common/service.proto is a copy of common/service.proto from the Free-Guy-IR/node repository; proto.lock records the exact node commit it was taken from.

  • make sync_proto (optionally REF=<branch|tag|sha>) fetches the node proto, rewrites proto.lock and regenerates the stubs.

  • make check_proto fails when the copy differs from the pinned node commit, when the node main branch has changed the proto since, or when the checked-in stubs no longer match protoc output.

  • The Proto drift check workflow runs that check plus the unit tests on every push and pull request, and weekly.

  • A red freshness job (weekly or on demand) means the node repository changed common/service.proto after the pinned commit: run make sync_proto, review the regenerated stub diff, and commit. After a real proto change, upgrade the consumer with uv lock --upgrade-package pasarguard-node-bridge in the panel and rebuild its image.

About

Fork of PasarGuard node_bridge_py, adding sing-box (Hysteria2), OpenVPN, and MTProto proxy types to the gRPC contract

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages