vgate
Zero-Trust L4-L7 Reverse Proxy, Multi-Tenant WAF, STUN/TURN & P2P Overlay

VGate — Zero-Trust Layer 4–7 Security Gateway & Private Overlay Mesh

VGate — Zero-Trust L4/L7 Reverse Proxy, Multi-Tenant WAF, STUN/TURN & P2P Overlay


1. Product Overview

Modern distributed teams face two distinct connectivity challenges whenever services, databases, containers, and engineers span multiple networks:

  1. North–South Public Ingress (vgate serve & vgate tunnel): Safely publishing web applications, SaaS customer portals, APIs, and webhook receivers over HTTPS—even when upstream backends run inside private VPCs, unprivileged containers, or NAT-isolated branch environments with zero inbound firewall ports.
  2. East–West Private Mesh Networking (vgate up & vgate exec): Connecting application servers, databases, CI/CD runners, and developer workstations directly to one another with end-to-end authenticated encryption and per-port Zero Standing Privilege (ZSP) access controls—without requiring root, CAP_NET_ADMIN, or kernel tun drivers.

Instead of deploying and stitching together five separate infrastructure daemons (an HTTP reverse proxy, an OIDC login gatekeeper, a public tunnel relay, a kernel VPN, and an external STUN/TURN server), vgate consolidates the entire edge and mesh stack into one self-contained binary.

VGate Live Edge Telemetry & Gateway Overview

Key Architectural Differentiators

Capability Domain What vgate Delivers Out of the Box Operational Advantage
Zero-Root Execution Runs 100% in user space (uid=1000, cap_drop: ALL) using 127.64.x.y loopback VIPs, --bind forwarders, .vgate Magic DNS, and an RFC 1928 SOCKS5h proxy (127.0.0.1:1080). Works inside restricted Kubernetes pods, AWS Fargate, Docker containers, WSL2, and locked-down laptops with zero kernel drivers.
Automated ACME TLS & SNI Built-in RFC 8555 HTTP-01 certificate provisioning, exact and wildcard (*.domain) SNI matching, zero-downtime certificate hot-reload, X.509 mTLS, and blind TLS ClientHello SNI pass-through. Eliminates external ACME sidecars while allowing customer private TLS keys to remain strictly on customer premises when desired.
Multi-Tenant WAF & Penalty Box Per-tenant block, challenge, or detect enforcement, 25 built-in CVE virtual patches, OWASP CRS & ModSecurity SecRule support, CIDR allow/blocklists, and automatic repeat-offender quarantine. Isolates tenant security policies so tuning rules for one workspace never disrupts sibling customer environments.
OIDC Identity-Aware Gate & JIT PAM Enforces OIDC Authorization Code + PKCE (S256) sign-in or signed vnet_tok_... credentials at the edge, plus time-bounded Just-In-Time (JIT) access grants with passive L7 SSH/PostgreSQL wire auditing. Replaces standing VPN access and heavy bastion clusters with expiring, ticket-linked leases and tamper-evident SHA-256 audit chains.
STUN/TURN & 3-Tier VNet Mesh Self-hosted RFC 5389 STUN and RFC 5766 TURN (4-byte ChannelData) relay paired with Ed25519-signed X25519 ECDHE and ChaCha20-Poly1305 AEAD (900s / 1.4 GB automatic key rotation). Seamlessly selects Direct UDP (Tier 1), TURN UDP Relay (Tier 2), or Multiplexed TCP/TLS :443 (Tier 3) across any corporate firewall.
Live Webhook Inspector & Replay Captures recent HTTP and webhook exchanges in a bounded ring buffer with automatic credential header redaction ([REDACTED]), HMAC verification, and 1-click editable replay. Accelerates Stripe, GitHub, and Slack webhook debugging without exposing live Authorization or Cookie secrets.
Programmable Wasm 3.0 Edge Filters (vvm) Executes tenant .wasm/.wat L7 edge filters in-process via vvm's B1+B3 Frame IR, deterministic --fuel budgets, and 4 KiB CoW memory reset per request, plus /_vgate/metrics & /metrics Prometheus export. Enables sub-millisecond custom routing, header mutation, and rate-guard plugins with zero native crash risk and sidecar protection for vvm studio.

2. Visual Tour of the VGate Control Plane

8-Workspace Web Console (/_vgate/ui) & Native Desktop Control Center (vgate gui)

Operators and tenant administrators can govern routes, upstream pools, SaaS subdomains, custom CNAME aliases, WAF rules, TagGrant ACLs, JIT access approvals, cluster synchronization, and webhook replays from either the browser-based Web Console or the chromeless Desktop Control Center.

VGate 8-Workspace Web Console Command Center

VGate Native Desktop Control Center

Edge Identity-Aware Proxy & Multi-Tenant WAF Studio

Public routes and reverse tunnels can enforce OIDC Single Sign-On (--require-auth) while inspecting inbound HTTP requests against built-in CVE virtual patches, custom SecRule definitions, and automated Penalty Box thresholds.

VGate Zero-Trust Edge Identity-Aware Proxy Sign-In

VGate Multi-Tenant WAF & SecRule Studio


3. Five-Minute Quickstart

Step 1: Initialize Sealed Production Configuration

Generate cryptographically random secrets and write an owner-only (0600) vgate.json file protected by a 256-bit master key (data/vnet/config.master.key):

BASH
# Initialize sealed configuration and verify schema integrity
vgate init --config vgate.json
vgate config check --config vgate.json

Step 2: Start the Edge Gateway & Mesh Coordinator

Launch vgate serve to activate the HTTP/HTTPS reverse proxy, ACME challenge responder, STUN/TURN server, and VNet mesh coordinator:

BASH
# Start VGate Edge Hub listening on HTTP :8088, HTTPS :8443, and STUN/TURN :3478/udp
vgate serve \
  --config vgate.json \
  --http-addr 0.0.0.0:8088 \
  --https-addr 0.0.0.0:8443 \
  --turn-addr 0.0.0.0:3478 \
  --upstream 127.0.0.1:8080 \
  --base-domain edge.example.com \
  --auto-subdomain true

Verify gateway readiness via the unauthenticated health probe:

BASH
curl -sS http://127.0.0.1:8088/_vgate/health

Step 3: Mint a Scoped Enrollment Token & Connect a Private Node

Mint an HMAC-signed token pinned to a tenant network (corp-prod) and machine tag (tag:app), then enroll a remote server or workstation without root privileges:

BASH
# Mint a 24-hour enrollment token for node app-01
APP_TOKEN=$(vgate token mint \
  --config vgate.json \
  --principal "host:app-01" \
  --net corp-prod \
  --roles "node" \
  --scopes "vnet:enroll,tunnel:expose" \
  --tags "tag:app,tag:public-tunnel" \
  --ttl 86400)

# Expose a private service publicly with an OIDC/role policy and join the encrypted P2P mesh
vgate tunnel \
  --hub https://edge.example.com:8443 \
  --net corp-prod \
  --name app-01 \
  --token "$APP_TOKEN" \
  --expose "portal.edge.example.com=127.0.0.1:3000" \
  --require-auth "role=eng,domain=example.com"

4. Documentation Suite Guide

Guide Audience Summary
How-To Guide DevOps, SREs, Platform Engineers Step-by-step recipes for Let's Encrypt ACME TLS, OIDC SSO & JIT PAM grants, WAF Penalty Box tuning, P2P mesh peering, and webhook replay.
End-User Guide Developers, Analysts, Portal Users Walkthroughs for the Web Dashboard, Desktop/TUI clients, 127.64.x.y loopback VIPs, SOCKS5h .vgate browsing, JIT access requests, and inspector workflows.
Administrator Guide Security & Cluster Administrators 4-layer config governance, config.master.key sealing & rotation, multi-tenant isolation, active-active hub state sync, rate limits, circuit breakers, and SIEM hash chains.
Operations & Use Cases Infrastructure & Production Teams Production runbooks for zero-root systemd/Docker/Kubernetes ingress, NAT-traversed private mesh, bastion-less SSH/PostgreSQL PAM, and DDoS mitigation.
Configuration & CLI Reference All Operators & Automation Complete subcommands, CLI flags, vgate.json Schema v2 reference, VGATE_* environment variables, and /_vgate/* Admin/Mesh REST API specifications.
Performance & Sizing Capacity Planners & Architects Empirical throughput and latency benchmarks, KernelReactor C100K memory profile, zero-thread stream splicing metrics, and VPS hardware sizing tables.
VNet Developer Guide V Developers & Platform Integrators Programmatic vnet module API, X25519 PFS sessions, TagGrant ACLs, LocalBridge forwarders, and runnable code examples.

VGate — Step-by-Step How-To Guide

VGate — Zero-Trust L4/L7 Reverse Proxy, Multi-Tenant WAF, STUN/TURN & P2P Overlay


Recipe 1: Publish HTTPS Upstreams with Automated Let's Encrypt ACME TLS

vgate includes a built-in RFC 8555 ACME HTTP-01 client, multi-domain SNI certificate store (certs/domains/), wildcard domain matcher (*.domain), and zero-downtime certificate hot-reloader.

1. Configure Public HTTP (:80) and HTTPS (:443) Listeners

Ensure DNS A/AAAA records for your domain (for example, api.example.com) point to your gateway's public IP address, then start vgate serve:

BASH
vgate serve \
  --config vgate.json \
  --http-addr 0.0.0.0:80 \
  --https-addr 0.0.0.0:443 \
  --upstream "10.0.1.20:8080,10.0.1.21:8080" \
  --lb-policy least_conn

2. Trigger On-Demand ACME HTTP-01 Provisioning

Request certificate issuance through the authenticated Admin API. vgate generates an ECDSA P-256 keypair, serves the /.well-known/acme-challenge/<token> response directly from memory, finalizes the order, and activates the PEM chain in the live SNI registry without dropping active sockets:

BASH
curl -sS -X POST http://127.0.0.1/_vgate/ui/acme/provision \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "domain": "api.example.com"
  }'

3. Register Custom Upstream Routes & Customer CNAME Domains

Add host-based or path-based load-balanced upstream pools dynamically or inside vgate.json:

JSON
{
  "schema_version": 2,
  "http_listen_addr": "0.0.0.0:80",
  "https_enabled": true,
  "https_listen_addr": "0.0.0.0:443",
  "lb_policy": "least_conn",
  "routes": [
    {
      "id": "payments-api",
      "host": "api.example.com",
      "path_prefix": "/v1/payments",
      "upstream": "10.0.1.20:8080,10.0.1.21:8080",
      "lb_policy": "least_conn",
      "strip_prefix": false,
      "require_auth": false
    }
  ]
}

VGate Dynamic Routes, Upstream Pools & Load Balancing

VGate SaaS Subdomains & Customer CNAME Virtual Hosts


Recipe 2: Enable OIDC Single Sign-On & Time-Bounded PAM/JIT Grants

Protect internal dashboards, staging portals, and private SSH/PostgreSQL services with OpenID Connect (S256 PKCE) at the HTTP edge and Zero Standing Privilege (ZSP) Just-In-Time (JIT) grants on the VNet mesh.

1. Configure Upstream OIDC Provider Settings

Set your OIDC issuer (such as vwarden, Okta, Keycloak, Google Workspace, or Microsoft Entra ID) via environment variables or vgate.json, then seal the client secret at rest:

BASH
export VGATE_OIDC_ENABLED=true
export VGATE_OIDC_ISSUER="https://idp.example.com"
export VGATE_OIDC_CLIENT_ID="vgate-edge-gateway"
export VGATE_OIDC_CLIENT_SECRET="super-secret-oidc-client-key"
export VGATE_OIDC_REDIRECT_URL="https://edge.example.com/_vgate/auth/callback"

# Persist and encrypt OIDC_CLIENT_SECRET into vgate.json as ENC[vgate-v2:...]
vgate config seal --config vgate.json

2. Expose a Protected Application with --require-auth

BASH
vgate tunnel \
  --hub https://edge.example.com \
  --net corp-prod \
  --name grafana-internal \
  --token "$NODE_TOKEN" \
  --expose "metrics.edge.example.com=127.0.0.1:3000" \
  --require-auth "role=sre,domain=example.com"

Unauthenticated visitors are redirected to /_vgate/auth/login. Once authenticated, vgate sets an HttpOnly; SameSite=Lax HMAC-signed session cookie, strips spoofable client headers, and injects verified X-VGate-Principal, X-VGate-Roles, and X-VGate-Network headers upstream.

3. Request and Approve a 30-Minute JIT PAM Grant

Engineers start with zero standing access to tag:prod-db. During an incident, the engineer requests a 30-minute (1800s) lease for PostgreSQL port 5432, and SecOps approves it:

BASH
# Step A: On-call engineer submits a time-bounded JIT request
curl -sS -X POST https://edge.example.com/_vgate/ui/jit \
  -H "X-VGate-Admin-Token: $ENGINEER_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_slug": "corp-prod",
    "src_tags": ["tag:oncall"],
    "dst_tags": ["tag:prod-db"],
    "allowed_ports": [5432],
    "ttl_secs": 1800,
    "reason": "INC-7741: Verify settlement index latency"
  }'

# Step B: Security administrator approves the pending request
curl -sS -X POST https://edge.example.com/_vgate/ui/jit/approve \
  -H "X-VGate-Admin-Token: $SECOPS_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"request_id": "jit_corp-prod_1730486400_1"}'

VGate Token Minter, TagGrant ACL Matrix & JIT Access Workspace


Recipe 3: Tune Multi-Tenant WAF Rules & Auto-Ban Penalty Box

Every tenant network (network_slug) maintains an isolated WAF policy (data/tenants/<slug>/waf.json) supporting block, challenge (stateless HMAC bot PoW), or detect mode, 25 built-in CVE virtual patches, custom ModSecurity SecRule directives, and automatic repeat-attacker quarantine.

1. Enable Blocking Mode, CIDR Allowlists & Penalty Box Auto-Bans

BASH
curl -sS -X POST https://edge.example.com/_vgate/ui/waf/policy \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_slug": "corp-prod",
    "mode": "block",
    "update_ip_lists": true,
    "ip_allowlist": ["10.20.0.0/16", "192.168.10.50/32"],
    "ip_blocklist": ["198.51.100.0/24"],
    "update_auto_ban": true,
    "auto_ban_enabled": true,
    "auto_ban_threshold": 5,
    "auto_ban_duration_secs": 900
  }'

2. Import Custom ModSecurity SecRule Directives

BASH
curl -sS -X POST https://edge.example.com/_vgate/ui/waf/modsec \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_slug": "corp-prod",
    "secrules_text": "SecRule REQUEST_URI \"@rx /internal/debug\" \"id:900101,phase:1,block,status:403,msg:Block internal debug endpoint\""
  }'

3. Unban a Quarantined Client IP Immediately

BASH
curl -sS -X POST https://edge.example.com/_vgate/ui/waf/unban \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_slug": "corp-prod",
    "ip": "203.0.113.77"
  }'

vgate up connects machines across distinct clouds, NAT routers, or unprivileged containers over an encrypted VNet overlay (100.64.0.0/10) mapped onto user-space 127.64.x.y loopback VIPs.

1. Publish a Private Database on Host A (db-01)

BASH
# Bind PostgreSQL locally to 127.0.0.1:5432, then publish it onto corp-prod mesh
vgate up --daemon \
  --hub https://edge.example.com \
  --net corp-prod \
  --name db-01 \
  --token "$DB_NODE_TOKEN" \
  --publish "pg=127.0.0.1:5432"

2. Authorize Port 5432 Between tag:app and tag:db

BASH
curl -sS -X POST https://edge.example.com/_vgate/ui/acl/grant \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "allow-app-to-postgres",
    "network_slug": "corp-prod",
    "src_tags": ["tag:app"],
    "dst_tags": ["tag:db"],
    "allowed_ports": [5432]
  }'

3. Connect from Host B (app-01) via Loopback VIP or vgate exec

BASH
# Option A: Bind db-01 onto local loopback VIP 127.64.0.11:5432 (Linux & Windows without root)
vgate up --daemon \
  --hub https://edge.example.com \
  --net corp-prod \
  --name app-01 \
  --token "$APP_NODE_TOKEN" \
  --bind "127.64.0.11:5432=db-01:pg" \
  --socks-addr 127.0.0.1:1080

psql -h 127.64.0.11 -p 5432 -U app_user -d orders

# Option B: Zero-config process wrapper (injects PGHOST/PGPORT automatically; works on Linux, Windows & macOS)
vgate exec \
  --net corp-prod \
  --bind "127.0.0.1:15432=db-01:pg" \
  -- psql -U app_user -d orders -c "SELECT now();"

VGate P2P Overlay Mesh, ChaCha20-Poly1305 Telemetry & Clientless Probes


Recipe 5: Inspect, Verify & Replay Webhooks

When developing or triaging Stripe, GitHub, or Slack integrations, enable edge webhook HMAC verification and use 1-click editable replay to re-deliver captured payloads to local or staging targets.

1. Start Tunnel or Hub with Webhook Verification

BASH
vgate serve \
  --config vgate.json \
  --inspect true \
  --inspect-bodies true \
  --webhook-provider stripe \
  --webhook-secret "$STRIPE_WEBHOOK_SECRET"

2. Query Captured Exchanges & Replay with Optional Target Override

BASH
# List recent redacted HTTP/webhook captures for corp-prod
curl -sS -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  "https://edge.example.com/_vgate/ui/state?net=corp-prod"

# Replay captured exchange #42 to a local staging listener
curl -sS -X POST https://edge.example.com/_vgate/ui/replay \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": 42,
    "override_to": "http://127.0.0.1:3001/webhooks/stripe"
  }'

VGate Editable Webhook Replay Studio & Live Syslog Stream

VGate — End-User & Developer Portal Guide

VGate — Zero-Trust L4/L7 Reverse Proxy, Multi-Tenant WAF, STUN/TURN & P2P Overlay


1. Signing In to Protected Applications (Edge Identity-Aware Proxy)

When an administrator protects a public tunnel or route with an access policy (--require-auth), opening the URL in your browser presents the VGate Zero-Trust Edge Sign-In Portal (/_vgate/auth/login).

VGate Edge Identity-Aware Proxy Sign-In Portal

Supported Sign-In Methods

  1. Single Sign-On (OIDC / OAuth 2.1 PKCE):
    • Click Continue with Single Sign-On to authenticate with your organization's identity provider (vwarden, Okta, Google, Entra ID, or Keycloak).
    • Upon callback to /_vgate/auth/callback, vgate verifies the S256 PKCE verifier, evaluates your roles, scopes, and email domain against the route policy, and issues an HttpOnly; SameSite=Lax session cookie (vgate_iap_session).
  2. Scoped Access Token (vnet_tok_...):
    • For CLI scripts, API automation, or temporary contractor access, paste a vnet_tok_... token directly into the login form or send it as an HTTP header:
BASH
     curl -sS https://staging-app.edge.example.com/api/status \
       -H "Authorization: Bearer $VGATE_ACCESS_TOKEN"

2. Navigating the Web Dashboard (/_vgate/ui)

The built-in Web Console at /_vgate/ui adapts automatically to your credential scope:

  • Tenant Self-Service Portal: When signing in with a tenant-scoped token (--net acme-app + role tenant-admin), you see only your own tenant's peers, public subdomains, custom CNAME aliases, WAF rules, JIT requests, and captured webhooks.
  • Global Super-Admin Studio: Hub operators see fleet-wide telemetry, multi-hub synchronization, SNI certificates, and cross-tenant governance across all 8 workspaces.

VGate 8-Workspace Web Console Overview

Overview of the 8 Interactive Workspaces

Workspace Primary Day-to-Day Tasks
1. Command Center Inspect live SVG network topology, active stream throughput, rate-limiter health, and SHA-256 log chain status.
2. SaaS & CNAME Tunnels View automatic <node>.<tenant>.<base-domain> URLs, bind custom CNAME domains, and provision on-demand ACME certificates.
3. Routes & Upstreams Inspect HTTP/WebSocket routing rules, backend load-balancing policies (round_robin, least_conn, ip_hash), and circuit-breaker state.
4. P2P Mesh & Probes View enrolled VNet peers, 100.64.x.y / 127.64.x.y VIPs, active transport tier (direct_udp, turn_channel, tls_mux), and run clientless probes.
5. Security, ACLs & JIT Mint scoped vnet_tok_... tokens, submit or approve time-bounded JIT access requests, and review passive L7 protocol audit events.
6. WAF & SecRule Studio Toggle block / challenge / detect modes, test CVE virtual patches, author ModSecurity SecRule policies, and manage the Penalty Box.
7. Config, Cluster & SNI Validate 4-layer configuration, inspect active-active hub sync peers, and review registered TLS SNI domains.
8. Webhook Inspector & Logs Filter live captured HTTP/webhook requests, edit headers or payloads for 1-click replay, and query RFC 5424 logs.

3. Desktop Control Center (vgate gui) & Terminal Dashboard (vgate tui)

Developers working on laptops or headless SSH workstations can monitor and control local tunnels, port bindings, and mesh status without manually managing URLs or tokens.

Launching the Native Desktop Control Center

BASH
# Opens a chromeless local desktop window pre-authenticated over loopback (127.0.0.1)
vgate gui

VGate Desktop Control Center

Launching the Terminal UI Dashboard

BASH
# Displays live peer latency, active tunnels, mux stream windows, and audit status in the terminal
vgate tui --config vgate.json

4. Connecting Local Applications, Browsers & CLI Tools

Because vgate runs 100% in user space without installing kernel VPN drivers, you have four frictionless ways to reach private mesh services from your workstation:

Workflow Command / Setting Best Use Case
1. Zero-Root Process Wrapper (vgate exec) vgate exec --bind 127.0.0.1:15432=db-01:pg -- psql -d app Running psql, redis-cli, curl, or migration scripts with automatic PGHOST/PGPORT/ALL_PROXY injection.
2. Loopback VIP Port Bind (--bind) vgate up --bind 127.64.0.11:5432=db-01:pg Keeping native ports (:5432, :22, :6379) across multiple remote hosts on Linux and Windows without port collisions.
3. Local SOCKS5h Proxy + .vgate Magic DNS vgate up --socks-addr 127.0.0.1:1080 Browsing private http://<node>.<tenant>.vgate:8080 web apps in Firefox/Chrome/Edge or connecting via ssh -o ProxyCommand.
4. Public Reverse Tunnel (vgate tunnel) vgate tunnel --expose demo.edge.example.com=127.0.0.1:3000 Sharing a local dev server with teammates or receiving external Stripe/GitHub webhooks over HTTPS.

Browser Setup for .vgate Magic DNS (127.0.0.1:1080)

  1. Start vgate up with the local SOCKS5h proxy enabled:
BASH
   vgate up --hub https://edge.example.com --net corp-prod --name dev-laptop --token "$DEV_TOKEN" --socks-addr 127.0.0.1:1080 --daemon
  1. In Firefox, open Settings -> Network Settings -> Manual proxy configuration, set SOCKS Host to 127.0.0.1, Port to 1080, select SOCKS v5, and check Proxy DNS when using SOCKS v5.
  2. Open any authorized mesh service directly by its .vgate name, such as http://staging-web.corp-prod.vgate:8080.

5. Requesting Just-In-Time (JIT) Access Sessions

When Zero Standing Privilege policies are active, sensitive servers (tag:prod-ssh, tag:pci-db) are hidden from your peer map until a time-bounded JIT lease is approved.

  1. Submit a Request: Open Workspace 5 (Security, ACLs & JIT) in /_vgate/ui (or call POST /_vgate/ui/jit), select the target tag (tag:prod-db), specify the required port (5432), choose a lease duration (such as 30m), and enter your incident or change ticket ID.
  2. Automatic Activation: As soon as an authorized approver clicks Approve, the target service appears in your vgate status peer map and accepts end-to-end encrypted connections.
  3. Automatic Expiration: When expires_at is reached, vgate revokes the temporary grant automatically—no manual cleanup required.

6. Using the Request Inspector & Editable Webhook Replay

During local development or production webhook troubleshooting, open Workspace 8 (Webhook Inspector & Syslog):

VGate Webhook Inspector & Editable Replay

  1. Inspect Redacted Traffic: Select any captured HTTP request to view status code, upstream latency, W3C traceparent ID, request/response headers (with Authorization, Cookie, and *-Token values masked as [REDACTED]), and body preview.
  2. 1-Click or Edited Replay: Click Replay to re-send the exact captured webhook to your tunnel target, or customize the target URL (override_to), HTTP method, headers, or JSON payload in the Replay Studio to test edge-case error handling.

VGate — Gateway & Cluster Administrator Guide

VGate — Zero-Trust L4/L7 Reverse Proxy, Multi-Tenant WAF, STUN/TURN & P2P Overlay


1. Four-Layer Configuration Governance & Secret Sealing

vgate resolves runtime configuration deterministically across four layers (highest priority last) and fails closed if an explicit configuration file is missing or any encrypted field fails authentication:

  1. Layer 1 — Built-In Hardened Defaults: Loopback-only listeners (127.0.0.1:8088, 127.0.0.1:8443, 127.0.0.1:3478), 32 KB header cap, 10 MB body cap, 10s header read deadline, and production secret enforcement (default ephemeral secrets are rejected unless --dev is explicitly passed).
  2. Layer 2 — JSON Configuration (vgate.json): Comment-tolerant (# and //) Schema v2 JSON loaded via --config <path> or VGATE_CONFIG_FILE.
  3. Layer 3 — Environment File & OS Environment (vgate.env / VGATE_*): Loaded via --env-file <path> (VGATE_ENV_FILE) and process environment variables.
  4. Layer 4 — Command-Line Flags: Explicit CLI arguments (--http-addr, --https-addr, --upstream, --net, etc.).

VGate Visual Configuration Studio, Cluster Sync & Multi-SNI TLS

Sealing Plaintext Secrets (vgate config seal) & Master Key Lifecycle

Administrators never need to store cleartext passwords or shared keys in vgate.json or .env backups. Sensitive fields (mesh_secret, mesh_secret_prev, turn_password, oidc_client_secret, vnet_token, vnet_socks_auth, and webhook_secret) are encrypted into authenticated ENC[vgate-v2:...] envelopes bound to their specific field name (contextual AAD) using an owner-only (0600) 256-bit master key (data/vnet/config.master.key).

BASH
# 1. Generate CSPRNG secrets and write a sealed 0600 vgate.json + 0600 config.master.key
vgate init --config ./config/vgate.json

# 2. If you edit vgate.json to paste a new OIDC or webhook secret in plaintext, seal it in-place:
vgate config seal --config ./config/vgate.json

# 3. Validate syntax, port ranges, TLS paths, and secret decryption without starting listeners:
vgate config check --config ./config/vgate.json

# 4. Rotate the 256-bit master key atomically (archives .prev key and re-seals all ENC[...] fields):
vgate config rotate-key --config ./config/vgate.json

2. Multi-Tenant Isolation & Governance (data/tenants/<slug>/)

When operating vgate for multiple business units or external SaaS customers, each tenant (network_slug) is isolated on disk (0700 directories, 0600 files) and in memory:

TEXT
data/tenants/
  acme-prod/
    tenant.json        # Per-tenant node/tunnel quotas, CNAME ownership & metadata
    acl.json           # Scoped TagGrant rules & bilateral cross-tenant peering approvals
    waf.json           # Isolated WAF mode, CVE toggles, custom SecRules & Penalty Box state
    tokens_meta.json   # Non-secret token ledger (sig32 token_id, claims, revocation status)

Administrative Role Separation

  • Global Super-Admin: Authenticated on the primary control network with admin privileges; governs global listeners, upstream pools, cluster peers, and cross-tenant quotas.
  • Tenant Self-Service Admin: Authenticated with a token scoped to --net <tenant-slug> and role tenant-admin. Tenant admins cannot mint global superadmin tokens, cannot overwrite another tenant's node_id or WAF rules, cannot claim unowned ACME domains, and cannot view or replay another tenant's webhooks.

3. Active-Active Multi-Hub State Synchronization

Multiple vgate serve hubs deployed across availability zones or geographic regions synchronize enrolled peers, public tunnel leases, token revocations, and per-tenant policy shards (tenant.json, acl.json, waf.json) over authenticated HTTPS gossip (/_vgate/cluster/sync) without requiring external Redis, etcd, or PostgreSQL clusters.

BASH
# Hub A (US-East)
vgate serve \
  --config ./config/vgate.json \
  --node-id hub-us-east \
  --cluster-peers "https://hub-eu-west.example.com:8443,https://hub-ap-south.example.com:8443"

# Hub B (EU-West)
vgate serve \
  --config ./config/vgate.json \
  --node-id hub-eu-west \
  --cluster-peers "https://hub-us-east.example.com:8443,https://hub-ap-south.example.com:8443"
  • Conflict Resolution: Last-Write-Wins (LWW) timestamps paired with explicit deletion tombstones ensure revoked tokens and deleted grants never resurrect across split-brain recoveries.
  • Zero-Downtime Cluster Secret Rotation: Populate mesh_secret_prev (VGATE_MESH_SECRET_PREV) during rolling secret upgrades so existing peers remain authenticated while transitioning to the new mesh_secret.

4. TLS Certificate Lifecycle & Mutual TLS (mTLS)

vgate supports four complementary TLS deployment patterns on --https-addr:

TLS Mode Configuration Operational Behavior
1. Static / Wildcard PEM + Hot-Reload --tls-cert certs/fullchain.pem --tls-key certs/privkey.pem Polls certificate mtimes every cert_reload_check_secs (10s), verifies complete PEM markers to avoid half-written reloads, and swaps keys with zero downtime.
2. Automated RFC 8555 ACME HTTP-01 acme_enabled: true, tls_certs_dir: "certs/domains" Provisions per-domain ECDSA P-256 certificates via POST /_vgate/ui/acme/provision and matches exact or *.domain SNI hostnames per handshake.
3. Edge Mutual TLS (mTLS) --tls-client-ca certs/client-ca.pem --mtls true Requires and verifies client X.509 certificates signed by your enterprise CA before accepting HTTP or control-plane requests.
4. Blind TLS ClientHello SNI Pass-Through Customer tunnel holds TLS key locally Peeks only at RFC 6066 SNI (0x0000) on port :443 and splices raw encrypted TLS bytes end-to-end to the peer tunnel without terminating TLS on the Hub.

5. Two-Tier Rate Limiting, Load Balancing & Circuit Breakers

To protect both backend services and /_vgate/* control endpoints against volumetric floods and cascading upstream outages, vgate enforces independent per-IP token buckets and 3-state upstream circuit breakers:

JSON
{
  "rate_limit_enabled": true,
  "rate_limit_rps": 120,
  "rate_limit_burst": 240,
  "control_rate_rps": 20,
  "control_rate_burst": 40,
  "pool_enabled": true,
  "lb_policy": "least_conn",
  "pool_max_idle_per_host": 32,
  "pool_idle_timeout_secs": 30,
  "cb_failure_threshold": 3,
  "cb_cooldown_secs": 10,
  "active_probe_interval_secs": 15
}
  • Two-Tier Token Bucket: Public ingress defaults to 120 req/s (burst 240), while /_vgate/* control routes are strictly capped at 20 req/s (burst 40) with bounded IP table eviction (16,384 max IPs, 180s idle TTL).
  • Fast-Fail Circuit Breaker: After 3 consecutive dial failures to a backend target, the target enters Open state for 10s, failing over immediately (< 1 ms) to healthy pool members (round_robin, least_conn, or ip_hash) until a Half-Open probe succeeds.

6. Tamper-Evident SHA-256 SIEM Logging & Prometheus Telemetry

Every operational event (logs/vgate.log) and security event (logs/vgate-security.log) is formatted as sanitized RFC 5424 structured syslog (stripping CR/LF injection characters) and linked into a rolling SHA-256 hash chain (chain = SHA256(prev_hash + entry)).

Streaming to External SIEM Collectors & Scraping Metrics

BASH
# Forward structured RFC 5424 security events over UDP to Splunk, Elastic, or vsight SIEM
export VGATE_SYSLOG_UDP="10.10.0.50:514"

# Query security audit logs via authenticated API (verifies SHA-256 chain integrity)
curl -sS -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  "https://edge.example.com/_vgate/logs?level=SECURITY&limit=50"

# Scrape Prometheus telemetry (connections, WAF blocks, CVE hits, TURN allocations, mux windows)
curl -sS -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  https://edge.example.com/_vgate/metrics

VGate — Production Operations & Use-Case Runbooks

VGate — Zero-Trust L4/L7 Reverse Proxy, Multi-Tenant WAF, STUN/TURN & P2P Overlay


Use Case 1: Zero-Root Edge Ingress on Linux systemd, Docker & Kubernetes

Because vgate requires zero kernel modules (kernel tun device) and zero root privileges (uid=1000), it deploys cleanly under strict container security profiles (PodSecurityStandard: restricted, cap_drop: ["ALL"], no-new-privileges: true).

Generate OS Service, Compose & Kubernetes Manifests Automatically

BASH
# Generates hardened systemd unit (LimitSTACK=512K), compose.yaml, and Kubernetes StatefulSet manifests
vgate service install --config ./config/vgate.json

Hardened systemd Unit (deploy/systemd/vgate.service)

To bind privileged ports :80 and :443 on Linux while running strictly as an unprivileged vgate system user (UID 1000), grant CAP_NET_BIND_SERVICE only:

INI
[Unit]
Description=VGate Zero-Trust Edge Gateway & VNet Mesh Coordinator
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=vgate
Group=vgate
WorkingDirectory=.
ExecStart=./bin/vgate serve --config ./config/vgate.json
Restart=always
RestartSec=2
LimitNOFILE=131072
LimitSTACK=512K
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=./data ./logs

[Install]
WantedBy=multi-user.target

Kubernetes Active-Active Hub & Zero-Root Sidecar Connector

BASH
# Deploy 3-replica Active-Active Hub StatefulSet + unprivileged sidecar connector
kubectl apply -f k8s/01-namespace-secret-configmap.yaml
kubectl apply -f k8s/02-hub-statefulset-service.yaml
kubectl apply -f k8s/03-sidecar-connector-deployment.yaml

Use Case 2: NAT-Traversed Multi-Cloud Private Mesh via 3-Tier Adaptive Transport

When connecting application containers in AWS to a private PostgreSQL cluster in an on-premises data center behind symmetric NAT or UDP-blocking firewalls, vgate up negotiates end-to-end Ed25519-signed X25519 ECDHE + ChaCha20-Poly1305 AEAD across three automatic transport tiers:

Tier Transport Mode Wire Overhead When Selected
Tier 1 direct_udp (STUN Hole-Punched P2P UDP) 36-byte AEAD header + tag Lowest latency when peers achieve direct reflexive UDP reachability.
Tier 2 turn_channel (RFC 5766 ChannelData :3478/udp) +4-byte channel frame (89% smaller than STUN) Symmetric NAT environments where direct UDP hole-punching is blocked.
Tier 3 tls_mux (vgate-mux/1.0 over TCP/TLS :443) 12-byte stream mux + 64 KB flow window Strict corporate networks that block all outbound UDP traffic.

Pure TCP :443 Mode (Zero Exposed UDP Ports)

If organizational firewall policy prohibits exposing UDP :3478, keep --turn-addr 127.0.0.1:3478 bound to loopback. All VNet peers and public tunnels operate seamlessly over outbound TCP/TLS :443 (tls_mux):

BASH
# Hub running in 100% Pure TCP/TLS :443 mode
vgate serve \
  --config ./config/vgate.json \
  --http-addr 0.0.0.0:80 \
  --https-addr 0.0.0.0:443 \
  --turn-addr 127.0.0.1:3478

Use Case 3: Zero-Trust PAM/JIT Bastion Replacement (SSH & PostgreSQL)

Replace public SSH jump hosts (:22) and intrusive database MITM proxies with loopback-bound services, time-bounded JIT grants, and passive Layer-7 wire protocol auditing.

1. Lock Down SSH & PostgreSQL to Loopback on the Target Host

Bind sshd (ListenAddress 127.0.0.1) and PostgreSQL (listen_addresses = '127.0.0.1') strictly to loopback so VPC and internet port scans see zero open ports, then publish them onto VNet:

BASH
vgate up --daemon \
  --hub https://edge.example.com \
  --net corp-prod \
  --name vault-db-01 \
  --token "$VAULT_HOST_TOKEN" \
  --publish "ssh=127.0.0.1:22,pg=127.0.0.1:5432"

2. Request & Approve a 30-Minute Port-Scoped JIT Lease

BASH
# On-call engineer requests 30-minute access strictly to port 5432 (SSH port 22 remains hidden!)
REQ_JSON=$(curl -sS -X POST https://edge.example.com/_vgate/ui/jit \
  -H "X-VGate-Admin-Token: $ONCALL_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_slug": "corp-prod",
    "src_tags": ["tag:oncall"],
    "dst_tags": ["tag:prod-db"],
    "allowed_ports": [5432],
    "ttl_secs": 1800,
    "reason": "INC-4092: Inspect deadlocked settlement row"
  }')

# SecOps approves the JIT request
curl -sS -X POST https://edge.example.com/_vgate/ui/jit/approve \
  -H "X-VGate-Admin-Token: $SECOPS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"request_id": "jit_corp-prod_1730486400_1"}'

3. Connect & Verify Passive Layer-7 Wire Protocol Audit

BASH
vgate exec \
  --net corp-prod \
  --bind "127.0.0.1:15432=vault-db-01:pg" \
  -- psql -U readonly_sre -d ledger_prod -c "SELECT pid, state FROM pg_stat_activity;"

Without requiring custom PostgreSQL CA certificates or Hub TLS decryption, the local bridge inspects the initial PostgreSQL v3.0 StartupMessage (or SSH-2.0-... client banner on port 22) and records principal, jit_grant, db_user="readonly_sre", and db_name="ledger_prod" in the SHA-256 hash-chained security log.


Use Case 4: Bilateral Cross-Tenant Vendor / Partner Peering

Allow an external vendor in isolated tenant vendor-net temporary access to a single diagnostic port in corp-prod without creating accounts inside your corporate tenant:

BASH
# 1. Vendor administrator proposes a 2-hour cross-tenant grant (created with peer_approved: false)
curl -sS -X POST https://edge.example.com/_vgate/ui/acl/grant \
  -H "X-VGate-Admin-Token: $VENDOR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "vendor-diag-ssh-2h",
    "network_slug": "vendor-net",
    "target_network_slug": "corp-prod",
    "src_tags": ["tag:vendor-support"],
    "dst_tags": ["tag:staging-appliance"],
    "allowed_ports": [22],
    "expires_at": 1730493600,
    "reason": "SUP-881: Firmware diagnostics"
  }'

# 2. Corp-Prod administrator bilaterally approves the inbound peering rule
curl -sS -X POST https://edge.example.com/_vgate/ui/acl/approve \
  -H "X-VGate-Admin-Token: $CORP_PROD_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"id": "vendor-diag-ssh-2h"}'

Use Case 5: Automated DDoS, Vulnerability Scanner & Credential Stuffing Mitigation

Combine vgate's two-tier token-bucket rate limiter, stateless HMAC bot challenge, 25 built-in CVE virtual patches, and Auto-Ban Penalty Box to stop automated vulnerability scanners at the edge before they consume backend compute:

BASH
# Enable stateless bot PoW challenge or strict blocking with automatic 30-minute IP quarantine after 3 hits
curl -sS -X POST https://edge.example.com/_vgate/ui/waf/policy \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_slug": "corp-prod",
    "mode": "block",
    "update_auto_ban": true,
    "auto_ban_enabled": true,
    "auto_ban_threshold": 3,
    "auto_ban_duration_secs": 1800
  }'

# Emergency token or node revocation (< 1 ms propagation locally, synced across cluster hubs)
curl -sS -X POST https://edge.example.com/_vgate/vnet/revoke \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"node_id": "compromised-laptop-04"}'

VGate — Configuration, CLI & REST API Reference (Appendix A)

VGate — Zero-Trust L4/L7 Reverse Proxy, Multi-Tenant WAF, STUN/TURN & P2P Overlay


Appendix A: Complete vgate CLI Subcommands & Flags

1. Subcommands

TEXT
vgate <subcommand> [action] [flags]
Subcommand Description
serve Start the full Edge Hub: HTTP/HTTPS reverse proxy, ACME responder, Multi-Tenant WAF, STUN/TURN server, and VNet Mesh Coordinator (default).
init Generate CSPRNG production secrets and write an owner-only (0600) sealed vgate.json (ENC[vgate-v2:...]) plus 0600 master key.
up Enroll in a VNet Zero-Root P2P Overlay Mesh (100.64.x.y / 127.64.x.y VIPs, --publish, --bind, and SOCKS5h proxy).
tunnel Expose a local HTTP or TCP service publicly through a VGate Edge Hub (--expose, --cname, --require-auth).
status Display live Hub health, enrolled P2P mesh peers, active transport tiers, and public tunnel leases.
token [mint|list|inspect] Mint HMAC-signed vnet_tok_... credentials (including automatic 68-byte compact reference tokens), list tenant tokens, or inspect claims.
config <init|check|seal|rotate-key> Initialize config, validate schema/TLS/secrets, seal plaintext fields in-place, or rotate config.master.key atomically.
service <install|uninstall|status|macos-lo0-alias> Generate or manage native systemd, Windows sc.exe, Docker Compose, Kubernetes, or macOS launchd / lo0 VIP aliases.
exec -- <cmd> [args...] Zero-root process wrapper that establishes --bind / SOCKS5h tunnels and injects PGHOST, PGPORT, REDIS_URL, and ALL_PROXY.
gui / desktop Launch the pre-authenticated native Desktop Control Center window bound to loopback (127.0.0.1).
tui Launch the interactive terminal telemetry dashboard.

2. Command-Line Flags

CLI Flag Corresponding Env Var Default Description
-h, --help — — Print usage summary and exit.
-v, --version — — Print vgate release version and exit.
--dev VGATE_DEV false Explicit local development mode (permits ephemeral default secrets and loopback UI auto-auth).
--daemon VGATE_DAEMON_MODE false Run vgate up or vgate tunnel client loop continuously in background daemon mode.
--config <path.json> VGATE_CONFIG_FILE vgate.json Load comment-tolerant JSON configuration file (Layer 2).
--save-config <path.json> — — Persist effective merged configuration as 0600 JSON with ENC[vgate-v2:...] sealed secrets.
--env-file <path.env> VGATE_ENV_FILE — Load KEY=VALUE environment overrides file (Layer 3).
--export-env <path.env> — — Export effective configuration as an owner-only (0600) KEY=VALUE .env file with sealed secrets.
--master-key-file <path> VGATE_MASTER_KEY_FILE data/vnet/config.master.key Path to the 0600 256-bit master encryption key.
--http-addr <ip:port> VGATE_HTTP_ADDR 127.0.0.1:8088 HTTP reverse proxy and ACME HTTP-01 listener bind address.
--https-addr <ip:port> VGATE_HTTPS_ADDR 127.0.0.1:8443 HTTPS TLS 1.2/1.3 listener bind address.
--tls-cert <path> VGATE_TLS_CERT certs/server.crt Default PEM certificate chain path.
--tls-key <path> VGATE_TLS_KEY certs/server.key Default PEM private key path.
--tls-client-ca <path> VGATE_TLS_CLIENT_CA — Client CA bundle path for X.509 Mutual TLS (mTLS) verification.
--mtls <bool> VGATE_MTLS_ENABLED false Enforce X.509 client certificate verification on HTTPS connections.
--upstream <targets> VGATE_DEFAULT_UPSTREAM 127.0.0.1:8080 Default upstream target or comma-separated backend pool.
--lb-policy <policy> VGATE_LB_POLICY round_robin Upstream load-balancing policy (round_robin, least_conn, ip_hash).
--turn-addr <ip:port> VGATE_TURN_ADDR 127.0.0.1:3478 Built-in RFC 5389 STUN / RFC 5766 TURN UDP listener address.
--turn-public-ip <ip> VGATE_TURN_PUBLIC_IP 127.0.0.1 Public IPv4 address advertised in TURN XOR-RELAYED-ADDRESS allocations.
--turn-pass <secret> VGATE_TURN_PASS (sealed) Long-term TURN credential secret or TURN REST HMAC secret.
--mesh-hub, --hub <url> VGATE_MESH_HUB_URL — Central VGate Hub URL for outbound peer enrollment and reverse tunnels.
--mesh-secret <secret> VGATE_MESH_SECRET (sealed) Cluster HMAC/enrollment secret (supports VGATE_MESH_SECRET_PREV for zero-downtime rotation).
--node-id, --name <id> VGATE_MESH_NODE_ID edge-gateway-01 Unique identifier for this Hub or VNet peer node.
--net <slug> VGATE_VNET_NETWORK corp-prod Tenant overlay network slug ([a-zA-Z0-9_-]).
--token <tok> VGATE_VNET_TOKEN — Scoped vnet_tok_... enrollment or API bearer token.
--tags <csv> VGATE_VNET_TAGS tag:default Machine ACL tags embedded when minting tokens (tag:web,tag:public-tunnel).
--principal <name> VGATE_VNET_PRINCIPAL admin Human or machine principal embedded in minted tokens.
--roles <csv> VGATE_VNET_ROLES — Subject roles for Edge IAP & UI RBAC (admin, tenant-admin, eng).
--scopes <csv> VGATE_VNET_SCOPES — Fine-grained permission scopes (vnet:enroll, api:read).
--ttl <seconds> VGATE_VNET_TTL_SECS 0 Token expiration TTL in seconds (0 = non-expiring).
--expose <host=target> VGATE_VNET_EXPOSE — Public tunnel mapping (app.example.com=127.0.0.1:3000).
--base-domain <domain> VGATE_BASE_DOMAIN vgate.local Root domain for automatic <node>.<net>.<base-domain> SaaS subdomains.
--auto-subdomain <bool> VGATE_AUTO_SUBDOMAIN false Automatically allocate tenant subdomains upon peer enrollment.
--cname <domain> VGATE_VNET_CNAME — Custom customer DNS CNAME virtual host mapped to a public tunnel.
--require-auth <policy> VGATE_VNET_REQUIRE_AUTH — Zero-Trust Edge IAP policy (role=eng,domain=example.com).
--publish <svc=addr> VGATE_VNET_PUBLISH — Publish local TCP/UDP services to authorized mesh peers (pg=127.0.0.1:5432).
--bind <local=peer:svc> VGATE_VNET_BIND — Bind local loopback port/VIP to a remote peer service (127.64.0.11:5432=db-01:pg).
--vpn-subnets <cidrs> VGATE_VPN_SUBNETS 192.168.0.0/16,... Private CIDR subnets advertised by a subnet-router peer.
--socks-addr <ip:port> VGATE_VNET_SOCKS_ADDR 127.0.0.1:1080 User-space RFC 1928 SOCKS5h + HTTP CONNECT + .vgate Magic DNS listener.
--socks-auth <cred> VGATE_VNET_SOCKS_AUTH — RFC 1929 user:pass or "token" auth (automatically enforced on non-loopback LAN binds).
--ui-addr <ip:port> VGATE_UI_ADDR — Optional dedicated bind address for the Web Console.
--inspect <bool> VGATE_INSPECT_ALL_ROUTES false Capture live HTTP inspector entries across general proxy routes.
--inspect-bodies <bool> VGATE_INSPECT_BODIES true Capture 4 KB body previews (false enforces strict Zero-Body HIPAA/PCI mode).
--webhook-provider <name> VGATE_WEBHOOK_PROVIDER — Edge HMAC webhook verifier (stripe, github, slack).
--webhook-secret <secret> VGATE_WEBHOOK_SECRET (sealed) Shared webhook signing secret for edge verification.
--max-nodes <count> VGATE_QUOTA_MAX_NODES 64 Maximum enrolled nodes per tenant network.
--max-tunnels <count> VGATE_QUOTA_MAX_TUNNELS 16 Maximum public tunnels per tenant network.
--state-file <path> VGATE_RUNTIME_STATE_FILE data/vnet/runtime_state.json Atomic 0600 JSON Coordinator persistence path.
--cluster-peers <urls> VGATE_CLUSTER_PEERS — Comma-separated peer Hub URLs for active-active state gossip.
--rekey-secs <sec> VGATE_REKEY_INTERVAL_SECS 900 P2P Signed-X25519 session key rotation time threshold (15 minutes).
--rekey-bytes <bytes> VGATE_REKEY_MAX_BYTES 1400000000 P2P session key rotation volume threshold (1.4 GB).
--rekey-packets <count> VGATE_REKEY_MAX_PACKETS 1000000 P2P session key rotation packet count threshold.
--rekey-grace-secs <sec> VGATE_REKEY_GRACE_SECS 15 Dual-epoch key overlap window preventing packet drops during rotation.
--trusted-proxies <csv> VGATE_TRUSTED_PROXIES — Trusted upstream L4/CDN proxy CIDRs permitted to supply X-Forwarded-For.
--max-header-bytes <n> VGATE_MAX_HEADER_BYTES 32768 Maximum inbound HTTP request header block size (32 KB).
--max-body-bytes <n> VGATE_MAX_BODY_BYTES 10485760 Maximum buffered HTTP body size (10 MB).

Exporting & Sealing Configuration via --save-config and --export-env

BASH
# Merge vgate.json + environment + CLI overrides and save sealed 0600 JSON + 0600 .env
vgate config check \
  --config vgate.json \
  --http-addr 0.0.0.0:8088 \
  --https-addr 0.0.0.0:8443 \
  --save-config ./config/vgate.sealed.json \
  --export-env ./config/vgate.env

3. vgate.json Schema v2 Example

Comments (// and #) are permitted inside vgate.json for operator annotations:

JSON
{
  // Schema v2 hierarchical & flat-compatible VGate configuration
  "schema_version": 2,
  "http_listen_addr": "0.0.0.0:8088",
  "https_enabled": true,
  "https_listen_addr": "0.0.0.0:8443",
  "tls_cert_path": "certs/fullchain.pem",
  "tls_key_path": "certs/privkey.pem",
  "tls_certs_dir": "certs/domains",
  "default_upstream": "127.0.0.1:8080",
  "lb_policy": "least_conn",
  "turn_enabled": true,
  "turn_listen_addr": "0.0.0.0:3478",
  "turn_public_ip": "203.0.113.10",
  "turn_realm": "edge.example.com",
  "turn_username": "vgate-turn",
  "turn_password": "ENC[vgate-v2:9f31...:c48a...:71b2...]",
  "rate_limit_enabled": true,
  "rate_limit_rps": 120,
  "rate_limit_burst": 240,
  "control_rate_rps": 20,
  "control_rate_burst": 40,
  "mesh_node_id": "hub-us-east-01",
  "mesh_secret": "ENC[vgate-v2:4a10...:88e1...:02d9...]",
  "vnet_network": "corp-prod",
  "vnet_cidr": "100.64.0.0/16",
  "base_domain": "edge.example.com",
  "auto_subdomain": true,
  "oidc_enabled": true,
  "oidc_issuer": "https://idp.example.com",
  "oidc_client_id": "vgate-edge",
  "oidc_client_secret": "ENC[vgate-v2:11b4...:55f0...:e93a...]",
  "quota_max_nodes_per_net": 64,
  "quota_max_tunnels_per_net": 16,
  "rekey_interval_secs": 900,
  "rekey_max_bytes": 1400000000,
  "rekey_grace_secs": 15,
  "max_header_bytes": 32768,
  "max_request_body_bytes": 10485760,
  "metrics_allow_local": true,
  "metrics_alias_root": false,
  "wasm_plugins_file": "data/vnet/wasm_plugins.json"
}

4. Admin, Mesh & VNet REST API Reference (/_vgate/*)

All /_vgate/* endpoints (except /_vgate/health and /_vgate/auth/* login pages) are protected by the dedicated Control-Plane Rate Limiter (20 rps) and require either X-VGate-Admin-Token: <vnet_tok_...>, Authorization: Bearer <vnet_tok_...>, or cluster HMAC headers (X-VGate-Timestamp + X-VGate-Signature).

Method & Endpoint Auth Scope Purpose
GET /_vgate/health Public Liveness and readiness JSON check (status: "ok").
GET /_vgate/metrics (and GET /metrics when VGATE_METRICS_ALIAS_ROOT=true) Admin / Local Prometheus text-format metrics for connections, WAF blocks, Wasm edge filters (vgate_wasm_filter_*), TURN relays, and mux streams.
GET /_vgate/wasm/plugins Admin List active WebAssembly 3.0 edge filter plugins (vvm B1+B3 IR + 4 KiB CoW).
POST /_vgate/wasm/plugins Admin Register and atomically persist (0600) a .wat or .wasm edge filter plugin with max_fuel, max_memory_pages, pool_size (1..32), and route scope.
DELETE /_vgate/wasm/plugins?id=... Admin Unregister an active WebAssembly 3.0 edge filter plugin.
GET /_vgate/logs Admin Query structured RFC 5424 operational and SECURITY logs (?level=SECURITY&limit=100).
GET /_vgate/auth/login Public Zero-Trust Edge IAP login portal (OIDC PKCE redirect or token sign-in).
GET /_vgate/auth/callback Public OIDC Authorization Code + PKCE (S256) callback verifier and HttpOnly cookie issuer.
POST /_vgate/vnet/enroll Node Token Enroll a VNet peer, allocate 100.64.x.y / 127.64.x.y VIP, and return ACL-filtered PeerMap.
GET /_vgate/vnet/map Node Token Poll updated ACL-filtered peer map, pinned Ed25519 keys, and active JIT grants.
POST /_vgate/vnet/expose Node Token Register a public SaaS subdomain or custom CNAME tunnel lease (PublicTunnelExposeRequest).
POST /_vgate/vnet/revoke Super / Tenant Admin Immediately revoke a vnet_tok_... credential or evict an enrolled node_id.
GET /_vgate/mesh/peers Cluster HMAC / Admin List registered mesh gateway peers and health status.
POST /_vgate/mesh/heartbeat Cluster HMAC Update peer latency, subnets, and STUN reflexive endpoint.
POST /_vgate/mesh/connect Node Token / HMAC Upgrade outbound TCP/TLS :443 connection into a persistent vgate-mux/1.0 reverse tunnel.
GET,POST /_vgate/cluster/sync Cluster HMAC Exchange Last-Write-Wins (LWW) CoordinatorSnapshot state and tombstones across active-active Hubs.
POST /_vgate/acme/challenge Admin Register or clear an RFC 8555 HTTP-01 key authorization token.
GET,POST /_vgate/acme/domains Admin List SNI domain certificates or register a validated PEM certificate/key pair.
GET /_vgate/ui Browser Session Render the 8-Workspace Web Console (Super-Admin or scoped Tenant Admin).
GET /_vgate/ui/state Super / Tenant Admin Fetch scoped JSON snapshot of routes, peers, tunnels, WAF counters, and inspector captures.
POST /_vgate/ui/waf/policy Super / Tenant Admin Update tenant WAF mode (block/challenge/detect), IP CIDRs, and Auto-Ban Penalty Box settings.
POST /_vgate/ui/waf/modsec Super / Tenant Admin Parse and activate custom ModSecurity SecRule directives (<= 8 KB line, <= 16 chain depth).
POST /_vgate/ui/waf/unban Super / Tenant Admin Remove a quarantined IP from the tenant Penalty Box.
GET,POST /_vgate/ui/jit Principal / Admin List pending/active JIT PAM requests or submit a new JitAccessRequest.
POST /_vgate/ui/jit/approve Super / Tenant Admin Approve a pending JIT request and mint an auto-expiring TagGrant (expires_at).
POST,DELETE /_vgate/ui/acl/grant Super / Tenant Admin Create or delete an intra-tenant or cross-tenant TagGrant rule.
POST /_vgate/ui/acl/approve Target Tenant Admin Bilaterally approve an inbound cross-tenant TagGrant (peer_approved = true).
POST /_vgate/ui/replay Super / Tenant Admin Re-send a captured HTTP/webhook exchange with optional override_to URL and edited headers/body.
POST /_vgate/ui/acme/provision Super / Tenant Admin Provision an on-demand ACME certificate for an owned domain.
POST /_vgate/ui/config Super-Admin Validate and atomically save updated configuration while preserving [REDACTED] secrets.

VGate — Empirical Performance, Memory Profile & Sizing Guide

VGate — Zero-Trust L4/L7 Reverse Proxy, Multi-Tenant WAF, STUN/TURN & P2P Overlay


1. Concurrency & Low-Memory Data-Plane Mechanics

To sustain tens of thousands of simultaneous connections without GC spikes, head-of-line blocking, or thread exhaustion, vgate combines five architectural techniques:

  1. Hybrid Pre-Warmed Worker Dispatcher:
    • Keeps 16 (VGATE_WORKER_THREADS) persistent worker threads warm for sub-millisecond HTTP request handling.
    • If all warm workers are occupied by long-lived WebSocket, Server-Sent Events (text/event-stream), or database streams, additional connections overflow onto lightweight dedicated threads up to VGATE_MAX_CONNS (4,096), preventing worker-pool starvation.
  2. Kernel Readiness Polling Before Buffer Allocation (KernelReactor):
    • Uses native OS event readiness (epoll on Linux, kqueue on macOS/BSD, WSAPoll on Windows) requiring only ~64 bytes of slab state per tracked socket descriptor.
    • Idle keep-alive or Slowloris sockets consume 0 bytes of 32 KB buffer-pool RAM until the kernel signals readable bytes (POLLIN).
  3. Single-Thread Bidirectional TCP Splicing:
    • Once HTTP headers are rewritten or a VNet local bridge stream opens, a single thread multiplexes bidirectional socket forwarding over 1 shared 32 KB buffer instead of spawning two pump threads with two 32 KB buffers—cutting active thread and buffer RAM usage by 50% while enforcing mid-stream JIT TTL expiration deadlines.
  4. Keep-Alive Connection Pooling & Fast-Fail Circuit Breakers:
    • Reuses up to 32 (VGATE_POOL_MAX_IDLE) warm upstream TCP sockets per backend host and trips open in < 1 ms after 3 consecutive backend failures (10s cooldown).
  5. Compact 4-Byte TURN ChannelData Framing & 512 KB Thread Stacks:
    • Replaces 36-byte STUN headers with 4-byte ChannelData (0x4000..0x7FFF) frames on bound TURN relays (89% header reduction) and configures LimitSTACK=512K under Linux systemd (16x lower virtual stack reservation than the 8 MB OS default).

2. Empirical Subsystem Benchmarks (Debug vs. Production -prod)

The table below reports measured single-core rates from vgate's built-in Tier 5 benchmark suite comparing unoptimized debug builds against production -prod (-O3) builds:

Subsystem & Measured Operation Single-Core Rate (Debug) Single-Core Rate (-prod -O3) Speedup & Architectural Notes
KernelReactor C100K Slab Lifecycle
(register + phase transition + unregister)
266,439 ops/sec
(~3.75 us / cycle)
554,323 ops/sec
(~1.80 us / cycle)
2.08x — ~64 B per tracked FD; idle connections hold 0 B of buffer-pool memory.
Single-Thread TCP Stream Splicing
(bidirectional socket pump + JIT TTL check)
1 thread + 1 x 32 KB
(vs. 2 threads + 64 KB)
2x Concurrent Streams
(50% RAM reduction)
Halves active thread count and buffer checkouts across HTTP proxy, reverse tunnels, and VNet binds.
Two-Tier Per-IP Token Bucket
(ingress rate-limiter check)
2,004,409 ops/sec
(~0.50 us / check)
2,004,409+ ops/sec
(68,702 ops/s full sweep)
O(1) hash lookup guarded by 16,384-IP cap and automatic 180s stale-bucket eviction.
Multi-Tenant WAF Deep Inspection
(6-stage deobfuscation + 25 CVEs + OWASP CRS)
757 req/sec
(single-core debug)
4,305 req/sec / core
(~34,400+ req/s on 8 cores)
5.69x — Inspects URI, query, headers, and payload with CIDR allowlist fast-path bypass.
ChaCha20-Poly1305 Encrypted Mesh AEAD
(1,400-byte MTU seal + open + anti-replay)
830 pkt/sec
(2,800 B/iter debug)
2,594 pkt/sec / core
(~29.1 Mbps/core; ~232 Mbps/8c)
3.13x — Pure-V RFC 8439 20-round ChaCha20 + Poly1305 MAC + 64-packet sliding replay window.
RFC 5389 STUN Binding Responder
(XOR-MAPPED-ADDRESS packet builder)
845,966 pkt/sec
(~1.18 us / packet)
3,192,440 pkt/sec
(~0.31 us / packet)
3.77x — Zero-allocation 32-byte STUN response builder on UDP :3478.

3. Runtime Memory Footprint Breakdown

Runtime Component Measured Memory Allocation Operational Notes
Base Process & Static Arenas ~14 – 22 MB RSS Includes 16 warm worker threads, 64 pre-allocated 32 KB buffers (2 MB), WAF CVE ruleset, and SNI table.
Per Idle Keep-Alive Socket ~64 Bytes Tracked inside KernelReactor slab with zero 32 KB buffer checkout until readable data arrives.
Per Active Spliced Stream 1 x 32 KB Buffer + 1 Worker Applies uniformly to HTTP/WebSocket streams, vgate-mux/1.0 reverse tunnels, and VNet local binds.
4,000 Active Concurrent Connections ~32 – 38 MB RSS Sustained under mixed HTTP, SSE, and reverse-tunnel load with LimitSTACK=512K.

4. Production Hardware Sizing Matrix

Hardware / VPS Tier Concurrent Active Streams (SSE, WS, Binds, Tunnels) Idle Keep-Alive Sockets (C100K Reactor Slab) Short-Lived HTTP Throughput (Keep-Alive Pool) HTTPS Throughput (TLS 1.2/1.3) STUN / TURN Relay Capacity
Nano / Edge Appliance
(1 vCPU, 512 MB – 1 GB RAM)
~1,500 – 2,800 ~10,000 – 25,000 ~2,500 – 4,200 req/s ~300 – 600 req/s ~10,000+ STUN pkt/s
~20 – 35 TURN media streams
Standard Cloud VPS
(2 vCPU, 2 GB – 4 GB RAM)
~5,000 – 9,000 ~40,000 – 65,000 ~7,000 – 12,000 req/s ~1,000 – 1,800 req/s ~25,000+ STUN pkt/s
~65 – 120 TURN media streams
Performance Dedicated Edge
(4–8 vCPU, 8 GB – 16 GB RAM)
~12,000 – 24,000 ~100,000+ (C100K) ~18,000 – 30,000 req/s ~3,000 – 5,500 req/s ~50,000+ STUN pkt/s
~250 – 500 TURN media streams

VNet Developer Guide — Programmatic P2P Overlay Mesh, Cryptography, ACLs & Zero-Root Bridges

VGate — Zero-Trust L4/L7 Reverse Proxy, Multi-Tenant WAF, STUN/TURN & P2P Overlay


1. Module Architecture & Capabilities

The vnet module implements VGate's software-defined private overlay network entirely in user space—requiring no kernel tun/tap drivers, no CAP_NET_ADMIN, and no root privileges. Developers import vnet alongside vgconfig, vgvpn, and vgjson to build custom mesh coordinators, embedded service sidecars, automated token minters, or encrypted P2P transports.

MESH & P2P CRYPTO

Zero-Root VNet LocalBridge, Signed-X25519 2D Key Ratchet & 3-Tier Adaptive Transport

Click any stage to inspect user-space VIP binding, forward-secret AEAD encryption, and Tier 1/2/3 path selection.

Interactive SVG • Click any node (4 components)
1. USER-SPACE BRIDGE & FORWARD-SECRET AEAD 127.64.x.y VIP -> Signed-X25519 + ChaCha20 2. 3-TIER ADAPTIVE NAT & FIREWALL PATHING Tier 1 Direct UDP -> Tier 2 TURN -> Tier 3 TLS :443 Plain Stream Tier 1 / 2 AEAD Tier 3 Fallback Zero-Root Client 1. Loopback VIP & SOCKS5h 127.64.x.y + .vgate DNS Crypto Ratchet 2. Signed-X25519 2D Ratchet VHP2 ECDHE + ChaCha20-Poly1305 UDP Tiers 1-2 3. Tier 1/2 UDP & TURN Direct UDP -> 4B ChannelData TCP Tier 3 4. Tier 3 vgate-mux/1.0 TCP/TLS :443 + 64KB Window
Components:
Zero-Root Client
1. Loopback VIP & SOCKS5h
User-Space LocalBridge L7 Audit
Component 1 of 4
Architectural Role & Purpose

Exposes authorized mesh services locally via 127.64.x.y VIPs, --bind ports, vgate exec, and SOCKS5h.

Contextual Description & System Interaction

Lets unmodified CLI tools and browsers access private mesh services safely.

Core Functionality & Security Mechanics
  • Operates 100% as uid=1000 with zero kernel tun device or CAP_NET_ADMIN
  • Enforces RFC 1929 auth and cloud-metadata SSRF guards on SOCKS5h
  • Passively extracts SSH-2.0 banners and PostgreSQL db_user/db_name
Crypto Ratchet
2. Signed-X25519 2D Ratchet
Signed-X25519 PFS 64-Pkt Replay
Component 2 of 4
Architectural Role & Purpose

Establishes pairwise forward-secret AEAD session keys with dual-epoch overlap and anti-replay windows.

Contextual Description & System Interaction

Ensures central TURN or TCP relays remain 100% blind to peer-to-peer payloads.

Core Functionality & Security Mechanics
  • Signs ephemeral X25519 keys with pinned Ed25519 identities and wipes scalars
  • Rotates keys every 900s or 1.4 GB (1M packets) with 15s grace window
  • Seals 1400B MTU frames with RFC 8439 ChaCha20-Poly1305 + 64-bit replay bitmap
UDP Tiers 1-2
3. Tier 1/2 UDP & TURN
Hole-Punch Prober TURN Relay
Component 3 of 4
Architectural Role & Purpose

Prioritizes direct STUN hole-punched UDP and falls back to 4-byte RFC 5766 ChannelData UDP relays.

Contextual Description & System Interaction

Sustains real-time low-jitter P2P transport across home, LTE/5G, and cloud NATs.

Core Functionality & Security Mechanics
  • Continuously probes direct reflexive UDP latency for lowest-RTT pathing
  • Switches seamlessly to bound TURN channels (0x4000..0x7FFF) behind CGNAT
  • Validates >=52-byte AEAD ChannelData payloads before unwrapping
TCP Tier 3
4. Tier 3 vgate-mux/1.0
Reverse Tunnel Mux Flow Control
Component 4 of 4
Architectural Role & Purpose

Multiplexes concurrent L4 streams over a single outbound TCP/TLS :443 connection when UDP is blocked.

Contextual Description & System Interaction

Guarantees resilient connectivity across the strictest corporate egress firewalls.

Core Functionality & Security Mechanics
  • Slices streams into 16 KB frames with 12-byte vgate-mux/1.0 headers
  • Enforces per-stream 64 KB receive windows via WINDOW_UPDATE (0x0A)
  • Supports pure TCP :443 deployments with zero exposed UDP ports

Subsystem Responsibilities

Subsystem Key Types & Entry Points Developer Responsibility
Mesh Coordinator Coordinator, new_coordinator, enroll_node, build_filtered_peer_map Manages IPAM (100.64.0.0/10 to 127.64.x.y), tenant isolation, TagGrant ACL filtering, public tunnel leases, and atomic 0600 JSON snapshots.
Identity & Tokens NodeIdentity, mint_subject_token, verify_token_to_subject, inspect_vnet_token Generates Ed25519 node keypairs and mints/verifies HMAC-SHA256 scoped vnet_tok_... credentials (including 68-byte SOCKS5-ready compact tokens).
PFS & AEAD Dataplane VNetDataPlane, new_dataplane, establish_pfs_pair, seal_peer_mux_frame, open_peer_mux_frame Executes Ed25519-signed RFC 7748 X25519 (VHP2) ephemeral key exchanges, directional HKDF subkeys, and RFC 8439 ChaCha20-Poly1305 packet sealing.
2D Key Ratchet SessionKeyRing, new_directional_keyring, ratchet_session_keyring_x25519, needs_rekey Rotates session epochs automatically by time (900s default) or volume (1.4 GB / 1,000,000 packets) with a 15s dual-epoch grace window.
3-Tier Path & NAT PeerPathState, wrap_vnet_packet_for_tier, encode_hole_punch_probe, select_optimal_path Encapsulates packets for direct_udp (Tier 1), turn_channel (Tier 2, 0x4000..0x7FFF), or tls_mux (Tier 3, vgvpn.MuxFrame).
Zero-Root Bridge LocalBridge, start_local_bridge, resolve_magic_dns, negotiate_socks5_handshake_with_auth Exposes local 127.64.x.y loopback VIPs, --bind TCP/UDP port forwarders, .vgate Magic DNS, and an RFC 1928/1929 SOCKS5h proxy.
Service & Ops generate_service_bundle, generate_k8s_and_compose_manifests Emits production systemd, Windows sc.exe, macOS launchd, Docker Compose, and Kubernetes manifests from a vgconfig.Config.

2. Core Data Structures & API Reference

Control Plane & Enrollment Types

Symbol Purpose Key Fields / Parameters
Coordinator Thread-safe mesh state & policy engine Initialized via vnet.new_coordinator(cfg). Holds peers, tunnels, revocations, TagGrants, JIT requests, and L7 audit events.
EnrollRequest Node registration payload node_id, network_slug, token, public_key_hex, tags, lan_endpoints, stun_endpoint, published_services, auto_expose_target, cname_host.
PeerMapResponse Filtered peer map returned on enroll/sync ok, self_peer, authorized_peers, public_tunnels, cluster_hubs, negotiated_transport, mux_window_bytes, hub_stun_addr.
EnrolledPeer Authenticated peer descriptor node_id, network_slug, overlay_ip (100.64.x.y), loopback_vip (127.64.x.y), magic_dns (<node>.<net>.vgate), public_key_hex, tags, transport_tier, published_services.
PublishedService Local service advertised to mesh peers name (e.g. 'pg'), proto ('tcp' or 'udp'), local_addr, port.
TagGrant Identity-based ACL rule id, network_slug, target_network_slug, peer_approved, src_tags, dst_tags, allowed_ports, allow_public_expose, allowed_domains, expires_at.
JitAccessRequest Temporary privileged access request request_id, network_slug, principal, src_tags, dst_tags, allowed_ports, ttl_secs, reason, status.

Cryptography & Data-Plane Types

Symbol Purpose Key Constants / Methods
NodeIdentity Persistent Ed25519 node identity generate_node_identity(node_id) or load_or_create_identity(data_dir, node_id).
VNetPacket Wire-format encrypted packet (VN magic) vnet_header_len = 20, vnet_tag_len = 16, vnet_pkt_data_chacha20 = 0x11, vnet_pkt_handshake = 0x02, vnet_pkt_probe = 0x03.
ReplayWindow 64-packet sliding anti-replay bitmask rw.check_and_accept(seq) rejects duplicate or stale sequence numbers.
VNetDataPlane High-level P2P session & frame manager initiate_peer_handshake, process_peer_handshake, establish_pfs_pair, seal_peer_mux_frame, open_peer_mux_frame.
SessionKeyRing Directional epoch keys + grace window new_directional_keyring, ratchet_session_keyring_x25519, seal_with_keyring, open_with_keyring, purge_expired_grace_key.

3. Developer Examples

All examples below use the vnet module directly and can be compiled inside a V project that has access to the vgate modules (v run .).

Example 1: Initialize a Coordinator, Mint Scoped Tokens & Enroll Peers

This example bootstraps an in-memory Coordinator, mints HMAC-signed subject tokens for two nodes (api-01 and db-01), generates their Ed25519 identities, and enrolls both into the corp-prod overlay namespace.

V
module main

import time
import vgconfig
import vnet

fn main() {
	cfg := vgconfig.Config{
		mesh_secret:  'replace-with-32-byte-hex-or-random-secret'
		vnet_network: 'corp-prod'
		vnet_cidr:    '100.64.0.0/16'
	}

	mut coord := vnet.new_coordinator(cfg)
	now := time.now().unix()

	// 1. Mint scoped enrollment tokens (ttl=3600s)
	api_tok := vnet.mint_subject_token(
		cfg.mesh_secret,
		'svc:api-01',
		'corp-prod',
		['node'],
		['vnet:enroll'],
		['tag:api'],
		3600,
	)
	db_tok := vnet.mint_subject_token(
		cfg.mesh_secret,
		'svc:db-01',
		'corp-prod',
		['node'],
		['vnet:enroll'],
		['tag:db'],
		3600,
	)

	// Verify token claims programmatically
	net_slug, subj := vnet.verify_token_to_subject(cfg.mesh_secret, api_tok, now) or {
		panic(err)
	}
	println('Verified token for ${subj.principal} in network ${net_slug}')

	// 2. Generate Ed25519 node identities
	ident_api := vnet.generate_node_identity('api-01') or { panic(err) }
	ident_db := vnet.generate_node_identity('db-01') or { panic(err) }

	// 3. Enroll peers into the Coordinator
	_ = coord.enroll_node(vnet.EnrollRequest{
		node_id:            'db-01'
		network_slug:       'corp-prod'
		token:              db_tok
		public_key_hex:     ident_db.public_key_hex
		tags:               ['tag:db']
		published_services: [
			vnet.PublishedService{
				name:       'pg'
				proto:      'tcp'
				local_addr: '127.0.0.1'
				port:       5432
			},
		]
	}) or { panic(err) }

	api_map := coord.enroll_node(vnet.EnrollRequest{
		node_id:        'api-01'
		network_slug:   'corp-prod'
		token:          api_tok
		public_key_hex: ident_api.public_key_hex
		tags:           ['tag:api']
	}) or { panic(err) }

	println('api-01 overlay IP   : ${api_map.self_peer.overlay_ip}')
	println('api-01 loopback VIP : ${api_map.self_peer.loopback_vip}')
	println('api-01 magic DNS    : ${api_map.self_peer.magic_dns}')
	println('Authorized peers    : ${api_map.authorized_peers.len}')
}

Example 2: Tag-Based ACLs (TagGrant) & Just-In-Time (JIT) Access

VNet enforces default-deny isolation between tags. You can grant standing tag-to-tag port access with upsert_tag_grant, or issue temporary, auto-expiring leases via the JIT workflow (request_jit_access -> approve_jit_access).

V
module main

import time
import vgconfig
import vnet

fn main() {
	cfg := vgconfig.Config{
		mesh_secret: 'replace-with-32-byte-hex-or-random-secret'
	}
	mut coord := vnet.new_coordinator(cfg)
	now := time.now().unix()

	// 1. Standing ACL: allow tag:api -> tag:db on PostgreSQL (5432) only
	coord.upsert_tag_grant(vnet.TagGrant{
		id:            'grant-api-to-db'
		network_slug:  'corp-prod'
		src_tags:      ['tag:api']
		dst_tags:      ['tag:db']
		allowed_ports: [5432]
		reason:        'Production API database access'
	})

	// Evaluate ACL policy directly
	can_pg := vnet.check_scoped_tag_grant(
		coord.list_grants_for_tenant('corp-prod', false),
		'corp-prod', ['tag:api'],
		'corp-prod', ['tag:db'],
		5432,
	)
	can_ssh := vnet.check_scoped_tag_grant(
		coord.list_grants_for_tenant('corp-prod', false),
		'corp-prod', ['tag:api'],
		'corp-prod', ['tag:db'],
		22,
	)
	println('api -> db:5432 allowed=${can_pg}, api -> db:22 allowed=${can_ssh}')

	// 2. Request a 15-minute (900s) Just-In-Time SSH break-glass grant
	jit_req := coord.request_jit_access(vnet.JitAccessRequest{
		request_id:    'jit-inc-4042'
		network_slug:  'corp-prod'
		principal:     'oncall@example.com'
		src_tags:      ['tag:oncall']
		dst_tags:      ['tag:db']
		allowed_ports: [22]
		ttl_secs:      900
		reason:        'INC-4042: Inspect PostgreSQL WAL replication lag'
	}, now) or { panic(err) }

	// 3. Approve the JIT request to mint an auto-expiring TagGrant
	jit_grant := coord.approve_jit_access(
		jit_req.request_id,
		'sec-lead@example.com',
		'corp-prod',
		false,
		now,
	) or { panic(err) }

	ttl_ms := vnet.resolve_grant_remaining_ttl_ms(
		[jit_grant],
		'corp-prod', ['tag:oncall'],
		'corp-prod', ['tag:db'],
		22,
		now,
	)
	println('Approved JIT grant ${jit_grant.id}, remaining TTL=${ttl_ms}ms')
}

Example 3: Forward-Secret P2P Session (VNetDataPlane + X25519 VHP2)

VNetDataPlane automates the Ed25519-signed X25519 VHP2 ephemeral handshake, derives directional tx_key/rx_key subkeys via HKDF-SHA256, and seals vgvpn.MuxFrame payloads inside ChaCha20-Poly1305 VNetPackets.

V
module main

import time
import vgconfig
import vgvpn
import vnet

fn main() {
	cfg := vgconfig.Config{
		mesh_secret: 'replace-with-32-byte-hex-or-random-secret'
	}
	now := time.now().unix()

	ident_a := vnet.generate_node_identity('node-a') or { panic(err) }
	ident_b := vnet.generate_node_identity('node-b') or { panic(err) }

	peer_a := vnet.EnrolledPeer{
		node_id:        'node-a'
		network_slug:   'corp-prod'
		overlay_ip:     '100.64.0.10'
		public_key_hex: ident_a.public_key_hex
		transport_tier: 'direct_udp'
	}
	peer_b := vnet.EnrolledPeer{
		node_id:        'node-b'
		network_slug:   'corp-prod'
		overlay_ip:     '100.64.0.11'
		public_key_hex: ident_b.public_key_hex
		transport_tier: 'direct_udp'
	}

	mut dp_a := vnet.new_dataplane(cfg, ident_a, peer_a.overlay_ip)
	mut dp_b := vnet.new_dataplane(cfg, ident_b, peer_b.overlay_ip)

	// Execute bidirectional X25519 VHP2 handshake (or pass syn_wire/ack_wire over network)
	dp_a.establish_pfs_pair(mut dp_b, peer_a, peer_b, now) or { panic(err) }
	println('PFS established on A=${dp_a.has_pfs_session("node-b")}')

	// Seal a MuxFrame from node-a -> node-b
	outbound := vgvpn.MuxFrame{
		frame_type: vgvpn.frame_stream_data
		flags:      0
		stream_id:  42
		payload:    'SELECT 1;'.bytes()
	}
	tier, wire_bytes := dp_a.seal_peer_mux_frame(peer_b, outbound) or { panic(err) }
	println('Sealed ${wire_bytes.len} bytes for transport tier=${tier}')

	// Open and verify on node-b (enforces Poly1305 tag + 64-packet ReplayWindow)
	decoded := dp_b.open_peer_mux_frame(peer_a, wire_bytes) or { panic(err) }
	println('Decoded stream=${decoded.stream_id} payload="${decoded.payload.bytestr()}"')
}

Example 4: Low-Level Packet Sealing, Anti-Replay & 2D Key Ratchet

When building custom transports or testing epoch rotation directly, use seal_packet_chacha20, open_packet_chacha20, ReplayWindow, and SessionKeyRing.

V
module main

import time
import vgconfig
import vgvpn
import vnet

fn main() {
	cfg := vgconfig.Config{
		mesh_secret:         'replace-with-32-byte-hex-or-random-secret'
		rekey_interval_secs: 900
		rekey_max_bytes:     1_400_000_000
	}
	now := time.now().unix()

	// 1. Direct pairwise session key & ChaCha20-Poly1305 packet sealing
	skey := vnet.derive_pairwise_session_key(cfg.mesh_secret, 'pubA', 'pubB', 1)
	src_ip := vgvpn.parse_ipv4_u32('100.64.0.10') or { u32(0) }
	dst_ip := vgvpn.parse_ipv4_u32('100.64.0.11') or { u32(0) }

	pkt := vnet.VNetPacket{
		pkt_type:  vnet.vnet_pkt_data_chacha20
		key_epoch: 1
		src_ip:    src_ip
		dst_ip:    dst_ip
		seq:       1
		payload:   'heartbeat-ok'.bytes()
	}
	wire := vnet.seal_packet_chacha20(skey, pkt) or { panic(err) }

	mut rw := vnet.ReplayWindow{}
	opened := vnet.open_packet_chacha20(skey, wire, mut rw) or { panic(err) }
	println('Opened seq=${opened.seq} payload="${opened.payload.bytestr()}"')

	// Replaying the exact same wire packet is rejected by ReplayWindow
	if _ := vnet.open_packet_chacha20(skey, wire, mut rw) {
		panic('Replay should have been rejected')
	} else {
		println('Duplicate packet correctly rejected: ${err}')
	}

	// 2. Directional SessionKeyRing & X25519 epoch ratchet
	mut ring := vnet.new_directional_keyring(cfg, 'node-a', 'node-b', skey, now)
	mut kp_a := vnet.generate_x25519_keypair() or { panic(err) }
	kp_b := vnet.generate_x25519_keypair() or { panic(err) }

	// Ratchet to epoch 2 (retains epoch 1 for rekey_grace_secs=15s)
	vnet.ratchet_session_keyring_x25519(mut ring, mut kp_a, kp_b.public_point_hex, cfg.mesh_secret, 2, now + 901) or {
		panic(err)
	}
	println('Ratcheted keyring to epoch=${ring.current_epoch}, needs_rekey=${vnet.needs_rekey(ring, now + 901)}')
}

Example 5: Zero-Root Local Bridge, Magic DNS, Port Binds & L7 Inspection

LocalBridge translates user-space --publish, --bind, and .vgate Magic DNS lookups into vgvpn.StreamOpenRequest frames without touching OS routing tables.

V
module main

import vgconfig
import vnet

fn main() {
	cfg := vgconfig.Config{
		mesh_node_id:    'workstation-01'
		vnet_network:    'corp-prod'
		vnet_socks_addr: '127.0.0.1:1080'
		vnet_bind:       '127.64.0.11:5432=db-01:pg,udp://127.0.0.1:15353=dns-01:53'
	}

	// Parse published services and local port binds
	published := vnet.parse_published_services('pg=127.0.0.1:5432,metrics=127.0.0.1:9090')
	binds := vnet.parse_local_binds(cfg.vnet_bind)
	println('Parsed ${published.len} published services and ${binds.len} local binds')

	peers := [
		vnet.EnrolledPeer{
			node_id:            'db-01'
			network_slug:       'corp-prod'
			overlay_ip:         '100.64.0.11'
			loopback_vip:       '127.64.0.11'
			magic_dns:          'db-01.corp-prod.vgate'
			published_services: published
		},
	]

	// Resolve .vgate Magic DNS hostname or 127.64.x.y VIP
	if peer := vnet.resolve_magic_dns('db-01.corp-prod.vgate', peers) {
		println('Resolved ${peer.magic_dns} -> overlay=${peer.overlay_ip} vip=${peer.loopback_vip}')
	}

	// Resolve a LocalPortBind into a target peer + Mux StreamOpenRequest
	target_peer, open_req := vnet.resolve_bind_stream_open(binds[0], peers) or { panic(err) }
	println('Bind ${binds[0].bind_addr} -> ${target_peer.node_id} (${open_req.target_host}:${open_req.target_port})')

	// Passive L7 wire protocol detection (PostgreSQL, SSH, Redis, HTTP, TLS)
	ssh_banner := 'SSH-2.0-OpenSSH_9.6\r\n'.bytes()
	l7 := vnet.inspect_l7_wire_protocol(ssh_banner, 22)
	println('Detected L7 protocol=${l7.protocol} detail=${l7.summary}')
}

Example 6: Public Tunnel Leases, Atomic State Persistence & Deployment Bundles

You can register ngrok-style public ingress tunnels with OIDC/role policies, persist the Coordinator state atomically (0600), and generate Docker Compose, Kubernetes, systemd, Windows, and macOS service manifests.

V
module main

import vgconfig
import vnet

fn main() {
	cfg := vgconfig.Config{
		mesh_node_id:       'edge-hub-01'
		vnet_network:       'corp-prod'
		base_domain:        'edge.example.com'
		runtime_state_file: 'data/vnet/runtime_state.json'
	}

	mut coord := vnet.new_coordinator(cfg)

	// 1. Register a public reverse tunnel protected by Edge IAP policy
	lease := coord.register_public_tunnel_with_policy(
		'app-01',
		'portal.edge.example.com',
		'127.0.0.1:3000',
		'role=eng,domain=example.com',
	) or { panic(err) }
	println('Registered tunnel ${lease.public_host} -> ${lease.local_target} (auth=${lease.require_auth})')

	// 2. Persist Coordinator state atomically (0600) and reload
	coord.save_state() or { panic(err) }
	loaded_peers := coord.load_state() or { panic(err) }
	println('Reloaded coordinator state (${loaded_peers} peers)')

	// 3. Generate deployment manifests (compose.yaml + vgate-k8s.yaml + OS daemons)
	bundle := vnet.generate_service_bundle(cfg) or { panic(err) }
	println('Generated systemd unit: ${bundle.systemd_unit_path}')
	println('Generated compose file: ${bundle.compose_path}')
	println('Generated K8s manifest: ${bundle.k8s_manifest_path}')
}

4. HTTP Control-Plane & Mesh API Integration (/_vgate/*)

External services, CI/CD pipelines, and non-V clients can manage vnet over HTTPS/HTTP against a running vgate serve hub using a scoped vnet_tok_... bearer token (Authorization: Bearer <token> or X-VGate-Admin-Token: <token>).

BASH
# 1. Check hub readiness (unauthenticated)
curl -sS http://127.0.0.1:8088/_vgate/health

# 2. Enroll a peer or fetch the ACL-filtered peer map
curl -sS -X POST http://127.0.0.1:8088/_vgate/vnet/enroll \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $VNET_TOKEN" \
  -d '{
    "node_id": "worker-01",
    "network_slug": "corp-prod",
    "token": "'"$VNET_TOKEN"'",
    "tags": ["tag:worker"],
    "published_services": [{"name": "metrics", "proto": "tcp", "local_addr": "127.0.0.1", "port": 9090}]
  }'

# 3. List enrolled peers visible to this tenant
curl -sS http://127.0.0.1:8088/_vgate/vnet/peers \
  -H "Authorization: Bearer $ADMIN_TOKEN"

# 4. Revoke a compromised token or node immediately
curl -sS -X POST http://127.0.0.1:8088/_vgate/vnet/tokens/revoke \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -d '{"token": "'"$COMPROMISED_TOKEN"'"}'

5. Security & Operational Best Practices

  1. Always Bind Loopback VIPs (127.64.x.y) in User Space: Use overlay_ip_to_loopback_vip when exposing remote mesh services locally so processes run as non-root (uid=1000, cap_drop: ALL) without kernel tun devices.
  2. Enforce SOCKS5 Authentication on Non-Loopback Binds: requires_socks5_auth(cfg) automatically requires RFC 1929 username/password or vnet_tok_... authentication whenever --socks-addr binds outside 127.0.0.1 / ::1. Use mint_compact_subject_token when tokens must fit within the 255-byte RFC 1929 password limit.
  3. Never Skip ReplayWindow or Reuse Nonces: Always pass a mutable ReplayWindow to open_packet_chacha20 / unwrap_mux_from_vnet_packet and use VNetDataPlane.next_sequence() for monotonic 64-bit sequence numbers.
  4. Keep SessionKeyRing Rotation Enabled: Retain the default rekey_interval_secs = 900 and rekey_max_bytes = 1_400_000_000 with rekey_grace_secs = 15 so in-flight packets survive epoch transitions without dropping streams.
  5. Seal Secrets at Rest: Store mesh_secret and vnet_token encrypted inside vgate.json (ENC[vgate-v2:...]) protected by data/vnet/config.master.key (0600), and rotate the master key periodically via vgate config rotate-key.

VGate — Consolidated End-User, Administrator & Operations Handbook

VGate — Zero-Trust L4/L7 Reverse Proxy, Multi-Tenant WAF, STUN/TURN & P2P Overlay


Part I: VGate — Zero-Trust Layer 4–7 Security Gateway & Private Overlay Mesh


1. Product Overview

Modern distributed teams face two distinct connectivity challenges whenever services, databases, containers, and engineers span multiple networks:

  1. North–South Public Ingress (vgate serve & vgate tunnel): Safely publishing web applications, SaaS customer portals, APIs, and webhook receivers over HTTPS—even when upstream backends run inside private VPCs, unprivileged containers, or NAT-isolated branch environments with zero inbound firewall ports.
  2. East–West Private Mesh Networking (vgate up & vgate exec): Connecting application servers, databases, CI/CD runners, and developer workstations directly to one another with end-to-end authenticated encryption and per-port Zero Standing Privilege (ZSP) access controls—without requiring root, CAP_NET_ADMIN, or kernel tun drivers.

Instead of deploying and stitching together five separate infrastructure daemons (an HTTP reverse proxy, an OIDC login gatekeeper, a public tunnel relay, a kernel VPN, and an external STUN/TURN server), vgate consolidates the entire edge and mesh stack into one self-contained binary.

VGate Live Edge Telemetry & Gateway Overview

Key Architectural Differentiators

Capability Domain What vgate Delivers Out of the Box Operational Advantage
Zero-Root Execution Runs 100% in user space (uid=1000, cap_drop: ALL) using 127.64.x.y loopback VIPs, --bind forwarders, .vgate Magic DNS, and an RFC 1928 SOCKS5h proxy (127.0.0.1:1080). Works inside restricted Kubernetes pods, AWS Fargate, Docker containers, WSL2, and locked-down laptops with zero kernel drivers.
Automated ACME TLS & SNI Built-in RFC 8555 HTTP-01 certificate provisioning, exact and wildcard (*.domain) SNI matching, zero-downtime certificate hot-reload, X.509 mTLS, and blind TLS ClientHello SNI pass-through. Eliminates external ACME sidecars while allowing customer private TLS keys to remain strictly on customer premises when desired.
Multi-Tenant WAF & Penalty Box Per-tenant block, challenge, or detect enforcement, 25 built-in CVE virtual patches, OWASP CRS & ModSecurity SecRule support, CIDR allow/blocklists, and automatic repeat-offender quarantine. Isolates tenant security policies so tuning rules for one workspace never disrupts sibling customer environments.
OIDC Identity-Aware Gate & JIT PAM Enforces OIDC Authorization Code + PKCE (S256) sign-in or signed vnet_tok_... credentials at the edge, plus time-bounded Just-In-Time (JIT) access grants with passive L7 SSH/PostgreSQL wire auditing. Replaces standing VPN access and heavy bastion clusters with expiring, ticket-linked leases and tamper-evident SHA-256 audit chains.
STUN/TURN & 3-Tier VNet Mesh Self-hosted RFC 5389 STUN and RFC 5766 TURN (4-byte ChannelData) relay paired with Ed25519-signed X25519 ECDHE and ChaCha20-Poly1305 AEAD (900s / 1.4 GB automatic key rotation). Seamlessly selects Direct UDP (Tier 1), TURN UDP Relay (Tier 2), or Multiplexed TCP/TLS :443 (Tier 3) across any corporate firewall.
Live Webhook Inspector & Replay Captures recent HTTP and webhook exchanges in a bounded ring buffer with automatic credential header redaction ([REDACTED]), HMAC verification, and 1-click editable replay. Accelerates Stripe, GitHub, and Slack webhook debugging without exposing live Authorization or Cookie secrets.
Programmable Wasm 3.0 Edge Filters (vvm) Executes tenant .wasm/.wat L7 edge filters in-process via vvm's B1+B3 Frame IR, deterministic --fuel budgets, and 4 KiB CoW memory reset per request, plus /_vgate/metrics & /metrics Prometheus export. Enables sub-millisecond custom routing, header mutation, and rate-guard plugins with zero native crash risk and sidecar protection for vvm studio.

2. Visual Tour of the VGate Control Plane

8-Workspace Web Console (/_vgate/ui) & Native Desktop Control Center (vgate gui)

Operators and tenant administrators can govern routes, upstream pools, SaaS subdomains, custom CNAME aliases, WAF rules, TagGrant ACLs, JIT access approvals, cluster synchronization, and webhook replays from either the browser-based Web Console or the chromeless Desktop Control Center.

VGate 8-Workspace Web Console Command Center

VGate Native Desktop Control Center

Edge Identity-Aware Proxy & Multi-Tenant WAF Studio

Public routes and reverse tunnels can enforce OIDC Single Sign-On (--require-auth) while inspecting inbound HTTP requests against built-in CVE virtual patches, custom SecRule definitions, and automated Penalty Box thresholds.

VGate Zero-Trust Edge Identity-Aware Proxy Sign-In

VGate Multi-Tenant WAF & SecRule Studio


3. Five-Minute Quickstart

Step 1: Initialize Sealed Production Configuration

Generate cryptographically random secrets and write an owner-only (0600) vgate.json file protected by a 256-bit master key (data/vnet/config.master.key):

BASH
# Initialize sealed configuration and verify schema integrity
vgate init --config vgate.json
vgate config check --config vgate.json

Step 2: Start the Edge Gateway & Mesh Coordinator

Launch vgate serve to activate the HTTP/HTTPS reverse proxy, ACME challenge responder, STUN/TURN server, and VNet mesh coordinator:

BASH
# Start VGate Edge Hub listening on HTTP :8088, HTTPS :8443, and STUN/TURN :3478/udp
vgate serve \
  --config vgate.json \
  --http-addr 0.0.0.0:8088 \
  --https-addr 0.0.0.0:8443 \
  --turn-addr 0.0.0.0:3478 \
  --upstream 127.0.0.1:8080 \
  --base-domain edge.example.com \
  --auto-subdomain true

Verify gateway readiness via the unauthenticated health probe:

BASH
curl -sS http://127.0.0.1:8088/_vgate/health

Step 3: Mint a Scoped Enrollment Token & Connect a Private Node

Mint an HMAC-signed token pinned to a tenant network (corp-prod) and machine tag (tag:app), then enroll a remote server or workstation without root privileges:

BASH
# Mint a 24-hour enrollment token for node app-01
APP_TOKEN=$(vgate token mint \
  --config vgate.json \
  --principal "host:app-01" \
  --net corp-prod \
  --roles "node" \
  --scopes "vnet:enroll,tunnel:expose" \
  --tags "tag:app,tag:public-tunnel" \
  --ttl 86400)

# Expose a private service publicly with an OIDC/role policy and join the encrypted P2P mesh
vgate tunnel \
  --hub https://edge.example.com:8443 \
  --net corp-prod \
  --name app-01 \
  --token "$APP_TOKEN" \
  --expose "portal.edge.example.com=127.0.0.1:3000" \
  --require-auth "role=eng,domain=example.com"

4. Documentation Suite Guide

Guide Audience Summary
How-To Guide DevOps, SREs, Platform Engineers Step-by-step recipes for Let's Encrypt ACME TLS, OIDC SSO & JIT PAM grants, WAF Penalty Box tuning, P2P mesh peering, and webhook replay.
End-User Guide Developers, Analysts, Portal Users Walkthroughs for the Web Dashboard, Desktop/TUI clients, 127.64.x.y loopback VIPs, SOCKS5h .vgate browsing, JIT access requests, and inspector workflows.
Administrator Guide Security & Cluster Administrators 4-layer config governance, config.master.key sealing & rotation, multi-tenant isolation, active-active hub state sync, rate limits, circuit breakers, and SIEM hash chains.
Operations & Use Cases Infrastructure & Production Teams Production runbooks for zero-root systemd/Docker/Kubernetes ingress, NAT-traversed private mesh, bastion-less SSH/PostgreSQL PAM, and DDoS mitigation.
Configuration & CLI Reference All Operators & Automation Complete subcommands, CLI flags, vgate.json Schema v2 reference, VGATE_* environment variables, and /_vgate/* Admin/Mesh REST API specifications.
Performance & Sizing Capacity Planners & Architects Empirical throughput and latency benchmarks, KernelReactor C100K memory profile, zero-thread stream splicing metrics, and VPS hardware sizing tables.
VNet Developer Guide V Developers & Platform Integrators Programmatic vnet module API, X25519 PFS sessions, TagGrant ACLs, LocalBridge forwarders, and runnable code examples.

Part II: VGate — Step-by-Step How-To Guide


Recipe 1: Publish HTTPS Upstreams with Automated Let's Encrypt ACME TLS

vgate includes a built-in RFC 8555 ACME HTTP-01 client, multi-domain SNI certificate store (certs/domains/), wildcard domain matcher (*.domain), and zero-downtime certificate hot-reloader.

1. Configure Public HTTP (:80) and HTTPS (:443) Listeners

Ensure DNS A/AAAA records for your domain (for example, api.example.com) point to your gateway's public IP address, then start vgate serve:

BASH
vgate serve \
  --config vgate.json \
  --http-addr 0.0.0.0:80 \
  --https-addr 0.0.0.0:443 \
  --upstream "10.0.1.20:8080,10.0.1.21:8080" \
  --lb-policy least_conn

2. Trigger On-Demand ACME HTTP-01 Provisioning

Request certificate issuance through the authenticated Admin API. vgate generates an ECDSA P-256 keypair, serves the /.well-known/acme-challenge/<token> response directly from memory, finalizes the order, and activates the PEM chain in the live SNI registry without dropping active sockets:

BASH
curl -sS -X POST http://127.0.0.1/_vgate/ui/acme/provision \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "domain": "api.example.com"
  }'

3. Register Custom Upstream Routes & Customer CNAME Domains

Add host-based or path-based load-balanced upstream pools dynamically or inside vgate.json:

JSON
{
  "schema_version": 2,
  "http_listen_addr": "0.0.0.0:80",
  "https_enabled": true,
  "https_listen_addr": "0.0.0.0:443",
  "lb_policy": "least_conn",
  "routes": [
    {
      "id": "payments-api",
      "host": "api.example.com",
      "path_prefix": "/v1/payments",
      "upstream": "10.0.1.20:8080,10.0.1.21:8080",
      "lb_policy": "least_conn",
      "strip_prefix": false,
      "require_auth": false
    }
  ]
}

VGate Dynamic Routes, Upstream Pools & Load Balancing

VGate SaaS Subdomains & Customer CNAME Virtual Hosts


Recipe 2: Enable OIDC Single Sign-On & Time-Bounded PAM/JIT Grants

Protect internal dashboards, staging portals, and private SSH/PostgreSQL services with OpenID Connect (S256 PKCE) at the HTTP edge and Zero Standing Privilege (ZSP) Just-In-Time (JIT) grants on the VNet mesh.

1. Configure Upstream OIDC Provider Settings

Set your OIDC issuer (such as vwarden, Okta, Keycloak, Google Workspace, or Microsoft Entra ID) via environment variables or vgate.json, then seal the client secret at rest:

BASH
export VGATE_OIDC_ENABLED=true
export VGATE_OIDC_ISSUER="https://idp.example.com"
export VGATE_OIDC_CLIENT_ID="vgate-edge-gateway"
export VGATE_OIDC_CLIENT_SECRET="super-secret-oidc-client-key"
export VGATE_OIDC_REDIRECT_URL="https://edge.example.com/_vgate/auth/callback"

# Persist and encrypt OIDC_CLIENT_SECRET into vgate.json as ENC[vgate-v2:...]
vgate config seal --config vgate.json

2. Expose a Protected Application with --require-auth

BASH
vgate tunnel \
  --hub https://edge.example.com \
  --net corp-prod \
  --name grafana-internal \
  --token "$NODE_TOKEN" \
  --expose "metrics.edge.example.com=127.0.0.1:3000" \
  --require-auth "role=sre,domain=example.com"

Unauthenticated visitors are redirected to /_vgate/auth/login. Once authenticated, vgate sets an HttpOnly; SameSite=Lax HMAC-signed session cookie, strips spoofable client headers, and injects verified X-VGate-Principal, X-VGate-Roles, and X-VGate-Network headers upstream.

3. Request and Approve a 30-Minute JIT PAM Grant

Engineers start with zero standing access to tag:prod-db. During an incident, the engineer requests a 30-minute (1800s) lease for PostgreSQL port 5432, and SecOps approves it:

BASH
# Step A: On-call engineer submits a time-bounded JIT request
curl -sS -X POST https://edge.example.com/_vgate/ui/jit \
  -H "X-VGate-Admin-Token: $ENGINEER_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_slug": "corp-prod",
    "src_tags": ["tag:oncall"],
    "dst_tags": ["tag:prod-db"],
    "allowed_ports": [5432],
    "ttl_secs": 1800,
    "reason": "INC-7741: Verify settlement index latency"
  }'

# Step B: Security administrator approves the pending request
curl -sS -X POST https://edge.example.com/_vgate/ui/jit/approve \
  -H "X-VGate-Admin-Token: $SECOPS_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"request_id": "jit_corp-prod_1730486400_1"}'

VGate Token Minter, TagGrant ACL Matrix & JIT Access Workspace


Recipe 3: Tune Multi-Tenant WAF Rules & Auto-Ban Penalty Box

Every tenant network (network_slug) maintains an isolated WAF policy (data/tenants/<slug>/waf.json) supporting block, challenge (stateless HMAC bot PoW), or detect mode, 25 built-in CVE virtual patches, custom ModSecurity SecRule directives, and automatic repeat-attacker quarantine.

1. Enable Blocking Mode, CIDR Allowlists & Penalty Box Auto-Bans

BASH
curl -sS -X POST https://edge.example.com/_vgate/ui/waf/policy \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_slug": "corp-prod",
    "mode": "block",
    "update_ip_lists": true,
    "ip_allowlist": ["10.20.0.0/16", "192.168.10.50/32"],
    "ip_blocklist": ["198.51.100.0/24"],
    "update_auto_ban": true,
    "auto_ban_enabled": true,
    "auto_ban_threshold": 5,
    "auto_ban_duration_secs": 900
  }'

2. Import Custom ModSecurity SecRule Directives

BASH
curl -sS -X POST https://edge.example.com/_vgate/ui/waf/modsec \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_slug": "corp-prod",
    "secrules_text": "SecRule REQUEST_URI \"@rx /internal/debug\" \"id:900101,phase:1,block,status:403,msg:Block internal debug endpoint\""
  }'

3. Unban a Quarantined Client IP Immediately

BASH
curl -sS -X POST https://edge.example.com/_vgate/ui/waf/unban \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_slug": "corp-prod",
    "ip": "203.0.113.77"
  }'

vgate up connects machines across distinct clouds, NAT routers, or unprivileged containers over an encrypted VNet overlay (100.64.0.0/10) mapped onto user-space 127.64.x.y loopback VIPs.

1. Publish a Private Database on Host A (db-01)

BASH
# Bind PostgreSQL locally to 127.0.0.1:5432, then publish it onto corp-prod mesh
vgate up --daemon \
  --hub https://edge.example.com \
  --net corp-prod \
  --name db-01 \
  --token "$DB_NODE_TOKEN" \
  --publish "pg=127.0.0.1:5432"

2. Authorize Port 5432 Between tag:app and tag:db

BASH
curl -sS -X POST https://edge.example.com/_vgate/ui/acl/grant \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "allow-app-to-postgres",
    "network_slug": "corp-prod",
    "src_tags": ["tag:app"],
    "dst_tags": ["tag:db"],
    "allowed_ports": [5432]
  }'

3. Connect from Host B (app-01) via Loopback VIP or vgate exec

BASH
# Option A: Bind db-01 onto local loopback VIP 127.64.0.11:5432 (Linux & Windows without root)
vgate up --daemon \
  --hub https://edge.example.com \
  --net corp-prod \
  --name app-01 \
  --token "$APP_NODE_TOKEN" \
  --bind "127.64.0.11:5432=db-01:pg" \
  --socks-addr 127.0.0.1:1080

psql -h 127.64.0.11 -p 5432 -U app_user -d orders

# Option B: Zero-config process wrapper (injects PGHOST/PGPORT automatically; works on Linux, Windows & macOS)
vgate exec \
  --net corp-prod \
  --bind "127.0.0.1:15432=db-01:pg" \
  -- psql -U app_user -d orders -c "SELECT now();"

VGate P2P Overlay Mesh, ChaCha20-Poly1305 Telemetry & Clientless Probes


Recipe 5: Inspect, Verify & Replay Webhooks

When developing or triaging Stripe, GitHub, or Slack integrations, enable edge webhook HMAC verification and use 1-click editable replay to re-deliver captured payloads to local or staging targets.

1. Start Tunnel or Hub with Webhook Verification

BASH
vgate serve \
  --config vgate.json \
  --inspect true \
  --inspect-bodies true \
  --webhook-provider stripe \
  --webhook-secret "$STRIPE_WEBHOOK_SECRET"

2. Query Captured Exchanges & Replay with Optional Target Override

BASH
# List recent redacted HTTP/webhook captures for corp-prod
curl -sS -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  "https://edge.example.com/_vgate/ui/state?net=corp-prod"

# Replay captured exchange #42 to a local staging listener
curl -sS -X POST https://edge.example.com/_vgate/ui/replay \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": 42,
    "override_to": "http://127.0.0.1:3001/webhooks/stripe"
  }'

VGate Editable Webhook Replay Studio & Live Syslog Stream


Part III: VGate — End-User & Developer Portal Guide


1. Signing In to Protected Applications (Edge Identity-Aware Proxy)

When an administrator protects a public tunnel or route with an access policy (--require-auth), opening the URL in your browser presents the VGate Zero-Trust Edge Sign-In Portal (/_vgate/auth/login).

VGate Edge Identity-Aware Proxy Sign-In Portal

Supported Sign-In Methods

  1. Single Sign-On (OIDC / OAuth 2.1 PKCE):
    • Click Continue with Single Sign-On to authenticate with your organization's identity provider (vwarden, Okta, Google, Entra ID, or Keycloak).
    • Upon callback to /_vgate/auth/callback, vgate verifies the S256 PKCE verifier, evaluates your roles, scopes, and email domain against the route policy, and issues an HttpOnly; SameSite=Lax session cookie (vgate_iap_session).
  2. Scoped Access Token (vnet_tok_...):
    • For CLI scripts, API automation, or temporary contractor access, paste a vnet_tok_... token directly into the login form or send it as an HTTP header:
BASH
     curl -sS https://staging-app.edge.example.com/api/status \
       -H "Authorization: Bearer $VGATE_ACCESS_TOKEN"

2. Navigating the Web Dashboard (/_vgate/ui)

The built-in Web Console at /_vgate/ui adapts automatically to your credential scope:

  • Tenant Self-Service Portal: When signing in with a tenant-scoped token (--net acme-app + role tenant-admin), you see only your own tenant's peers, public subdomains, custom CNAME aliases, WAF rules, JIT requests, and captured webhooks.
  • Global Super-Admin Studio: Hub operators see fleet-wide telemetry, multi-hub synchronization, SNI certificates, and cross-tenant governance across all 8 workspaces.

VGate 8-Workspace Web Console Overview

Overview of the 8 Interactive Workspaces

Workspace Primary Day-to-Day Tasks
1. Command Center Inspect live SVG network topology, active stream throughput, rate-limiter health, and SHA-256 log chain status.
2. SaaS & CNAME Tunnels View automatic <node>.<tenant>.<base-domain> URLs, bind custom CNAME domains, and provision on-demand ACME certificates.
3. Routes & Upstreams Inspect HTTP/WebSocket routing rules, backend load-balancing policies (round_robin, least_conn, ip_hash), and circuit-breaker state.
4. P2P Mesh & Probes View enrolled VNet peers, 100.64.x.y / 127.64.x.y VIPs, active transport tier (direct_udp, turn_channel, tls_mux), and run clientless probes.
5. Security, ACLs & JIT Mint scoped vnet_tok_... tokens, submit or approve time-bounded JIT access requests, and review passive L7 protocol audit events.
6. WAF & SecRule Studio Toggle block / challenge / detect modes, test CVE virtual patches, author ModSecurity SecRule policies, and manage the Penalty Box.
7. Config, Cluster & SNI Validate 4-layer configuration, inspect active-active hub sync peers, and review registered TLS SNI domains.
8. Webhook Inspector & Logs Filter live captured HTTP/webhook requests, edit headers or payloads for 1-click replay, and query RFC 5424 logs.

3. Desktop Control Center (vgate gui) & Terminal Dashboard (vgate tui)

Developers working on laptops or headless SSH workstations can monitor and control local tunnels, port bindings, and mesh status without manually managing URLs or tokens.

Launching the Native Desktop Control Center

BASH
# Opens a chromeless local desktop window pre-authenticated over loopback (127.0.0.1)
vgate gui

VGate Desktop Control Center

Launching the Terminal UI Dashboard

BASH
# Displays live peer latency, active tunnels, mux stream windows, and audit status in the terminal
vgate tui --config vgate.json

4. Connecting Local Applications, Browsers & CLI Tools

Because vgate runs 100% in user space without installing kernel VPN drivers, you have four frictionless ways to reach private mesh services from your workstation:

Workflow Command / Setting Best Use Case
1. Zero-Root Process Wrapper (vgate exec) vgate exec --bind 127.0.0.1:15432=db-01:pg -- psql -d app Running psql, redis-cli, curl, or migration scripts with automatic PGHOST/PGPORT/ALL_PROXY injection.
2. Loopback VIP Port Bind (--bind) vgate up --bind 127.64.0.11:5432=db-01:pg Keeping native ports (:5432, :22, :6379) across multiple remote hosts on Linux and Windows without port collisions.
3. Local SOCKS5h Proxy + .vgate Magic DNS vgate up --socks-addr 127.0.0.1:1080 Browsing private http://<node>.<tenant>.vgate:8080 web apps in Firefox/Chrome/Edge or connecting via ssh -o ProxyCommand.
4. Public Reverse Tunnel (vgate tunnel) vgate tunnel --expose demo.edge.example.com=127.0.0.1:3000 Sharing a local dev server with teammates or receiving external Stripe/GitHub webhooks over HTTPS.

Browser Setup for .vgate Magic DNS (127.0.0.1:1080)

  1. Start vgate up with the local SOCKS5h proxy enabled:
BASH
   vgate up --hub https://edge.example.com --net corp-prod --name dev-laptop --token "$DEV_TOKEN" --socks-addr 127.0.0.1:1080 --daemon
  1. In Firefox, open Settings -> Network Settings -> Manual proxy configuration, set SOCKS Host to 127.0.0.1, Port to 1080, select SOCKS v5, and check Proxy DNS when using SOCKS v5.
  2. Open any authorized mesh service directly by its .vgate name, such as http://staging-web.corp-prod.vgate:8080.

5. Requesting Just-In-Time (JIT) Access Sessions

When Zero Standing Privilege policies are active, sensitive servers (tag:prod-ssh, tag:pci-db) are hidden from your peer map until a time-bounded JIT lease is approved.

  1. Submit a Request: Open Workspace 5 (Security, ACLs & JIT) in /_vgate/ui (or call POST /_vgate/ui/jit), select the target tag (tag:prod-db), specify the required port (5432), choose a lease duration (such as 30m), and enter your incident or change ticket ID.
  2. Automatic Activation: As soon as an authorized approver clicks Approve, the target service appears in your vgate status peer map and accepts end-to-end encrypted connections.
  3. Automatic Expiration: When expires_at is reached, vgate revokes the temporary grant automatically—no manual cleanup required.

6. Using the Request Inspector & Editable Webhook Replay

During local development or production webhook troubleshooting, open Workspace 8 (Webhook Inspector & Syslog):

VGate Webhook Inspector & Editable Replay

  1. Inspect Redacted Traffic: Select any captured HTTP request to view status code, upstream latency, W3C traceparent ID, request/response headers (with Authorization, Cookie, and *-Token values masked as [REDACTED]), and body preview.
  2. 1-Click or Edited Replay: Click Replay to re-send the exact captured webhook to your tunnel target, or customize the target URL (override_to), HTTP method, headers, or JSON payload in the Replay Studio to test edge-case error handling.

Part IV: VGate — Gateway & Cluster Administrator Guide


1. Four-Layer Configuration Governance & Secret Sealing

vgate resolves runtime configuration deterministically across four layers (highest priority last) and fails closed if an explicit configuration file is missing or any encrypted field fails authentication:

  1. Layer 1 — Built-In Hardened Defaults: Loopback-only listeners (127.0.0.1:8088, 127.0.0.1:8443, 127.0.0.1:3478), 32 KB header cap, 10 MB body cap, 10s header read deadline, and production secret enforcement (default ephemeral secrets are rejected unless --dev is explicitly passed).
  2. Layer 2 — JSON Configuration (vgate.json): Comment-tolerant (# and //) Schema v2 JSON loaded via --config <path> or VGATE_CONFIG_FILE.
  3. Layer 3 — Environment File & OS Environment (vgate.env / VGATE_*): Loaded via --env-file <path> (VGATE_ENV_FILE) and process environment variables.
  4. Layer 4 — Command-Line Flags: Explicit CLI arguments (--http-addr, --https-addr, --upstream, --net, etc.).

VGate Visual Configuration Studio, Cluster Sync & Multi-SNI TLS

Sealing Plaintext Secrets (vgate config seal) & Master Key Lifecycle

Administrators never need to store cleartext passwords or shared keys in vgate.json or .env backups. Sensitive fields (mesh_secret, mesh_secret_prev, turn_password, oidc_client_secret, vnet_token, vnet_socks_auth, and webhook_secret) are encrypted into authenticated ENC[vgate-v2:...] envelopes bound to their specific field name (contextual AAD) using an owner-only (0600) 256-bit master key (data/vnet/config.master.key).

BASH
# 1. Generate CSPRNG secrets and write a sealed 0600 vgate.json + 0600 config.master.key
vgate init --config ./config/vgate.json

# 2. If you edit vgate.json to paste a new OIDC or webhook secret in plaintext, seal it in-place:
vgate config seal --config ./config/vgate.json

# 3. Validate syntax, port ranges, TLS paths, and secret decryption without starting listeners:
vgate config check --config ./config/vgate.json

# 4. Rotate the 256-bit master key atomically (archives .prev key and re-seals all ENC[...] fields):
vgate config rotate-key --config ./config/vgate.json

2. Multi-Tenant Isolation & Governance (data/tenants/<slug>/)

When operating vgate for multiple business units or external SaaS customers, each tenant (network_slug) is isolated on disk (0700 directories, 0600 files) and in memory:

TEXT
data/tenants/
  acme-prod/
    tenant.json        # Per-tenant node/tunnel quotas, CNAME ownership & metadata
    acl.json           # Scoped TagGrant rules & bilateral cross-tenant peering approvals
    waf.json           # Isolated WAF mode, CVE toggles, custom SecRules & Penalty Box state
    tokens_meta.json   # Non-secret token ledger (sig32 token_id, claims, revocation status)

Administrative Role Separation

  • Global Super-Admin: Authenticated on the primary control network with admin privileges; governs global listeners, upstream pools, cluster peers, and cross-tenant quotas.
  • Tenant Self-Service Admin: Authenticated with a token scoped to --net <tenant-slug> and role tenant-admin. Tenant admins cannot mint global superadmin tokens, cannot overwrite another tenant's node_id or WAF rules, cannot claim unowned ACME domains, and cannot view or replay another tenant's webhooks.

3. Active-Active Multi-Hub State Synchronization

Multiple vgate serve hubs deployed across availability zones or geographic regions synchronize enrolled peers, public tunnel leases, token revocations, and per-tenant policy shards (tenant.json, acl.json, waf.json) over authenticated HTTPS gossip (/_vgate/cluster/sync) without requiring external Redis, etcd, or PostgreSQL clusters.

BASH
# Hub A (US-East)
vgate serve \
  --config ./config/vgate.json \
  --node-id hub-us-east \
  --cluster-peers "https://hub-eu-west.example.com:8443,https://hub-ap-south.example.com:8443"

# Hub B (EU-West)
vgate serve \
  --config ./config/vgate.json \
  --node-id hub-eu-west \
  --cluster-peers "https://hub-us-east.example.com:8443,https://hub-ap-south.example.com:8443"
  • Conflict Resolution: Last-Write-Wins (LWW) timestamps paired with explicit deletion tombstones ensure revoked tokens and deleted grants never resurrect across split-brain recoveries.
  • Zero-Downtime Cluster Secret Rotation: Populate mesh_secret_prev (VGATE_MESH_SECRET_PREV) during rolling secret upgrades so existing peers remain authenticated while transitioning to the new mesh_secret.

4. TLS Certificate Lifecycle & Mutual TLS (mTLS)

vgate supports four complementary TLS deployment patterns on --https-addr:

TLS Mode Configuration Operational Behavior
1. Static / Wildcard PEM + Hot-Reload --tls-cert certs/fullchain.pem --tls-key certs/privkey.pem Polls certificate mtimes every cert_reload_check_secs (10s), verifies complete PEM markers to avoid half-written reloads, and swaps keys with zero downtime.
2. Automated RFC 8555 ACME HTTP-01 acme_enabled: true, tls_certs_dir: "certs/domains" Provisions per-domain ECDSA P-256 certificates via POST /_vgate/ui/acme/provision and matches exact or *.domain SNI hostnames per handshake.
3. Edge Mutual TLS (mTLS) --tls-client-ca certs/client-ca.pem --mtls true Requires and verifies client X.509 certificates signed by your enterprise CA before accepting HTTP or control-plane requests.
4. Blind TLS ClientHello SNI Pass-Through Customer tunnel holds TLS key locally Peeks only at RFC 6066 SNI (0x0000) on port :443 and splices raw encrypted TLS bytes end-to-end to the peer tunnel without terminating TLS on the Hub.

5. Two-Tier Rate Limiting, Load Balancing & Circuit Breakers

To protect both backend services and /_vgate/* control endpoints against volumetric floods and cascading upstream outages, vgate enforces independent per-IP token buckets and 3-state upstream circuit breakers:

JSON
{
  "rate_limit_enabled": true,
  "rate_limit_rps": 120,
  "rate_limit_burst": 240,
  "control_rate_rps": 20,
  "control_rate_burst": 40,
  "pool_enabled": true,
  "lb_policy": "least_conn",
  "pool_max_idle_per_host": 32,
  "pool_idle_timeout_secs": 30,
  "cb_failure_threshold": 3,
  "cb_cooldown_secs": 10,
  "active_probe_interval_secs": 15
}
  • Two-Tier Token Bucket: Public ingress defaults to 120 req/s (burst 240), while /_vgate/* control routes are strictly capped at 20 req/s (burst 40) with bounded IP table eviction (16,384 max IPs, 180s idle TTL).
  • Fast-Fail Circuit Breaker: After 3 consecutive dial failures to a backend target, the target enters Open state for 10s, failing over immediately (< 1 ms) to healthy pool members (round_robin, least_conn, or ip_hash) until a Half-Open probe succeeds.

6. Tamper-Evident SHA-256 SIEM Logging & Prometheus Telemetry

Every operational event (logs/vgate.log) and security event (logs/vgate-security.log) is formatted as sanitized RFC 5424 structured syslog (stripping CR/LF injection characters) and linked into a rolling SHA-256 hash chain (chain = SHA256(prev_hash + entry)).

Streaming to External SIEM Collectors & Scraping Metrics

BASH
# Forward structured RFC 5424 security events over UDP to Splunk, Elastic, or vsight SIEM
export VGATE_SYSLOG_UDP="10.10.0.50:514"

# Query security audit logs via authenticated API (verifies SHA-256 chain integrity)
curl -sS -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  "https://edge.example.com/_vgate/logs?level=SECURITY&limit=50"

# Scrape Prometheus telemetry (connections, WAF blocks, CVE hits, TURN allocations, mux windows)
curl -sS -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  https://edge.example.com/_vgate/metrics

Part V: VGate — Production Operations & Use-Case Runbooks


Use Case 1: Zero-Root Edge Ingress on Linux systemd, Docker & Kubernetes

Because vgate requires zero kernel modules (kernel tun device) and zero root privileges (uid=1000), it deploys cleanly under strict container security profiles (PodSecurityStandard: restricted, cap_drop: ["ALL"], no-new-privileges: true).

Generate OS Service, Compose & Kubernetes Manifests Automatically

BASH
# Generates hardened systemd unit (LimitSTACK=512K), compose.yaml, and Kubernetes StatefulSet manifests
vgate service install --config ./config/vgate.json

Hardened systemd Unit (deploy/systemd/vgate.service)

To bind privileged ports :80 and :443 on Linux while running strictly as an unprivileged vgate system user (UID 1000), grant CAP_NET_BIND_SERVICE only:

INI
[Unit]
Description=VGate Zero-Trust Edge Gateway & VNet Mesh Coordinator
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=vgate
Group=vgate
WorkingDirectory=.
ExecStart=./bin/vgate serve --config ./config/vgate.json
Restart=always
RestartSec=2
LimitNOFILE=131072
LimitSTACK=512K
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=./data ./logs

[Install]
WantedBy=multi-user.target

Kubernetes Active-Active Hub & Zero-Root Sidecar Connector

BASH
# Deploy 3-replica Active-Active Hub StatefulSet + unprivileged sidecar connector
kubectl apply -f k8s/01-namespace-secret-configmap.yaml
kubectl apply -f k8s/02-hub-statefulset-service.yaml
kubectl apply -f k8s/03-sidecar-connector-deployment.yaml

Use Case 2: NAT-Traversed Multi-Cloud Private Mesh via 3-Tier Adaptive Transport

When connecting application containers in AWS to a private PostgreSQL cluster in an on-premises data center behind symmetric NAT or UDP-blocking firewalls, vgate up negotiates end-to-end Ed25519-signed X25519 ECDHE + ChaCha20-Poly1305 AEAD across three automatic transport tiers:

Tier Transport Mode Wire Overhead When Selected
Tier 1 direct_udp (STUN Hole-Punched P2P UDP) 36-byte AEAD header + tag Lowest latency when peers achieve direct reflexive UDP reachability.
Tier 2 turn_channel (RFC 5766 ChannelData :3478/udp) +4-byte channel frame (89% smaller than STUN) Symmetric NAT environments where direct UDP hole-punching is blocked.
Tier 3 tls_mux (vgate-mux/1.0 over TCP/TLS :443) 12-byte stream mux + 64 KB flow window Strict corporate networks that block all outbound UDP traffic.

Pure TCP :443 Mode (Zero Exposed UDP Ports)

If organizational firewall policy prohibits exposing UDP :3478, keep --turn-addr 127.0.0.1:3478 bound to loopback. All VNet peers and public tunnels operate seamlessly over outbound TCP/TLS :443 (tls_mux):

BASH
# Hub running in 100% Pure TCP/TLS :443 mode
vgate serve \
  --config ./config/vgate.json \
  --http-addr 0.0.0.0:80 \
  --https-addr 0.0.0.0:443 \
  --turn-addr 127.0.0.1:3478

Use Case 3: Zero-Trust PAM/JIT Bastion Replacement (SSH & PostgreSQL)

Replace public SSH jump hosts (:22) and intrusive database MITM proxies with loopback-bound services, time-bounded JIT grants, and passive Layer-7 wire protocol auditing.

1. Lock Down SSH & PostgreSQL to Loopback on the Target Host

Bind sshd (ListenAddress 127.0.0.1) and PostgreSQL (listen_addresses = '127.0.0.1') strictly to loopback so VPC and internet port scans see zero open ports, then publish them onto VNet:

BASH
vgate up --daemon \
  --hub https://edge.example.com \
  --net corp-prod \
  --name vault-db-01 \
  --token "$VAULT_HOST_TOKEN" \
  --publish "ssh=127.0.0.1:22,pg=127.0.0.1:5432"

2. Request & Approve a 30-Minute Port-Scoped JIT Lease

BASH
# On-call engineer requests 30-minute access strictly to port 5432 (SSH port 22 remains hidden!)
REQ_JSON=$(curl -sS -X POST https://edge.example.com/_vgate/ui/jit \
  -H "X-VGate-Admin-Token: $ONCALL_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_slug": "corp-prod",
    "src_tags": ["tag:oncall"],
    "dst_tags": ["tag:prod-db"],
    "allowed_ports": [5432],
    "ttl_secs": 1800,
    "reason": "INC-4092: Inspect deadlocked settlement row"
  }')

# SecOps approves the JIT request
curl -sS -X POST https://edge.example.com/_vgate/ui/jit/approve \
  -H "X-VGate-Admin-Token: $SECOPS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"request_id": "jit_corp-prod_1730486400_1"}'

3. Connect & Verify Passive Layer-7 Wire Protocol Audit

BASH
vgate exec \
  --net corp-prod \
  --bind "127.0.0.1:15432=vault-db-01:pg" \
  -- psql -U readonly_sre -d ledger_prod -c "SELECT pid, state FROM pg_stat_activity;"

Without requiring custom PostgreSQL CA certificates or Hub TLS decryption, the local bridge inspects the initial PostgreSQL v3.0 StartupMessage (or SSH-2.0-... client banner on port 22) and records principal, jit_grant, db_user="readonly_sre", and db_name="ledger_prod" in the SHA-256 hash-chained security log.


Use Case 4: Bilateral Cross-Tenant Vendor / Partner Peering

Allow an external vendor in isolated tenant vendor-net temporary access to a single diagnostic port in corp-prod without creating accounts inside your corporate tenant:

BASH
# 1. Vendor administrator proposes a 2-hour cross-tenant grant (created with peer_approved: false)
curl -sS -X POST https://edge.example.com/_vgate/ui/acl/grant \
  -H "X-VGate-Admin-Token: $VENDOR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "vendor-diag-ssh-2h",
    "network_slug": "vendor-net",
    "target_network_slug": "corp-prod",
    "src_tags": ["tag:vendor-support"],
    "dst_tags": ["tag:staging-appliance"],
    "allowed_ports": [22],
    "expires_at": 1730493600,
    "reason": "SUP-881: Firmware diagnostics"
  }'

# 2. Corp-Prod administrator bilaterally approves the inbound peering rule
curl -sS -X POST https://edge.example.com/_vgate/ui/acl/approve \
  -H "X-VGate-Admin-Token: $CORP_PROD_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"id": "vendor-diag-ssh-2h"}'

Use Case 5: Automated DDoS, Vulnerability Scanner & Credential Stuffing Mitigation

Combine vgate's two-tier token-bucket rate limiter, stateless HMAC bot challenge, 25 built-in CVE virtual patches, and Auto-Ban Penalty Box to stop automated vulnerability scanners at the edge before they consume backend compute:

BASH
# Enable stateless bot PoW challenge or strict blocking with automatic 30-minute IP quarantine after 3 hits
curl -sS -X POST https://edge.example.com/_vgate/ui/waf/policy \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_slug": "corp-prod",
    "mode": "block",
    "update_auto_ban": true,
    "auto_ban_enabled": true,
    "auto_ban_threshold": 3,
    "auto_ban_duration_secs": 1800
  }'

# Emergency token or node revocation (< 1 ms propagation locally, synced across cluster hubs)
curl -sS -X POST https://edge.example.com/_vgate/vnet/revoke \
  -H "X-VGate-Admin-Token: $VGATE_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"node_id": "compromised-laptop-04"}'

Part VI: VGate — Configuration, CLI & REST API Reference (Appendix A)


Appendix A: Complete vgate CLI Subcommands & Flags

1. Subcommands

TEXT
vgate <subcommand> [action] [flags]
Subcommand Description
serve Start the full Edge Hub: HTTP/HTTPS reverse proxy, ACME responder, Multi-Tenant WAF, STUN/TURN server, and VNet Mesh Coordinator (default).
init Generate CSPRNG production secrets and write an owner-only (0600) sealed vgate.json (ENC[vgate-v2:...]) plus 0600 master key.
up Enroll in a VNet Zero-Root P2P Overlay Mesh (100.64.x.y / 127.64.x.y VIPs, --publish, --bind, and SOCKS5h proxy).
tunnel Expose a local HTTP or TCP service publicly through a VGate Edge Hub (--expose, --cname, --require-auth).
status Display live Hub health, enrolled P2P mesh peers, active transport tiers, and public tunnel leases.
token [mint|list|inspect] Mint HMAC-signed vnet_tok_... credentials (including automatic 68-byte compact reference tokens), list tenant tokens, or inspect claims.
config <init|check|seal|rotate-key> Initialize config, validate schema/TLS/secrets, seal plaintext fields in-place, or rotate config.master.key atomically.
service <install|uninstall|status|macos-lo0-alias> Generate or manage native systemd, Windows sc.exe, Docker Compose, Kubernetes, or macOS launchd / lo0 VIP aliases.
exec -- <cmd> [args...] Zero-root process wrapper that establishes --bind / SOCKS5h tunnels and injects PGHOST, PGPORT, REDIS_URL, and ALL_PROXY.
gui / desktop Launch the pre-authenticated native Desktop Control Center window bound to loopback (127.0.0.1).
tui Launch the interactive terminal telemetry dashboard.

2. Command-Line Flags

CLI Flag Corresponding Env Var Default Description
-h, --help — — Print usage summary and exit.
-v, --version — — Print vgate release version and exit.
--dev VGATE_DEV false Explicit local development mode (permits ephemeral default secrets and loopback UI auto-auth).
--daemon VGATE_DAEMON_MODE false Run vgate up or vgate tunnel client loop continuously in background daemon mode.
--config <path.json> VGATE_CONFIG_FILE vgate.json Load comment-tolerant JSON configuration file (Layer 2).
--save-config <path.json> — — Persist effective merged configuration as 0600 JSON with ENC[vgate-v2:...] sealed secrets.
--env-file <path.env> VGATE_ENV_FILE — Load KEY=VALUE environment overrides file (Layer 3).
--export-env <path.env> — — Export effective configuration as an owner-only (0600) KEY=VALUE .env file with sealed secrets.
--master-key-file <path> VGATE_MASTER_KEY_FILE data/vnet/config.master.key Path to the 0600 256-bit master encryption key.
--http-addr <ip:port> VGATE_HTTP_ADDR 127.0.0.1:8088 HTTP reverse proxy and ACME HTTP-01 listener bind address.
--https-addr <ip:port> VGATE_HTTPS_ADDR 127.0.0.1:8443 HTTPS TLS 1.2/1.3 listener bind address.
--tls-cert <path> VGATE_TLS_CERT certs/server.crt Default PEM certificate chain path.
--tls-key <path> VGATE_TLS_KEY certs/server.key Default PEM private key path.
--tls-client-ca <path> VGATE_TLS_CLIENT_CA — Client CA bundle path for X.509 Mutual TLS (mTLS) verification.
--mtls <bool> VGATE_MTLS_ENABLED false Enforce X.509 client certificate verification on HTTPS connections.
--upstream <targets> VGATE_DEFAULT_UPSTREAM 127.0.0.1:8080 Default upstream target or comma-separated backend pool.
--lb-policy <policy> VGATE_LB_POLICY round_robin Upstream load-balancing policy (round_robin, least_conn, ip_hash).
--turn-addr <ip:port> VGATE_TURN_ADDR 127.0.0.1:3478 Built-in RFC 5389 STUN / RFC 5766 TURN UDP listener address.
--turn-public-ip <ip> VGATE_TURN_PUBLIC_IP 127.0.0.1 Public IPv4 address advertised in TURN XOR-RELAYED-ADDRESS allocations.
--turn-pass <secret> VGATE_TURN_PASS (sealed) Long-term TURN credential secret or TURN REST HMAC secret.
--mesh-hub, --hub <url> VGATE_MESH_HUB_URL — Central VGate Hub URL for outbound peer enrollment and reverse tunnels.
--mesh-secret <secret> VGATE_MESH_SECRET (sealed) Cluster HMAC/enrollment secret (supports VGATE_MESH_SECRET_PREV for zero-downtime rotation).
--node-id, --name <id> VGATE_MESH_NODE_ID edge-gateway-01 Unique identifier for this Hub or VNet peer node.
--net <slug> VGATE_VNET_NETWORK corp-prod Tenant overlay network slug ([a-zA-Z0-9_-]).
--token <tok> VGATE_VNET_TOKEN — Scoped vnet_tok_... enrollment or API bearer token.
--tags <csv> VGATE_VNET_TAGS tag:default Machine ACL tags embedded when minting tokens (tag:web,tag:public-tunnel).
--principal <name> VGATE_VNET_PRINCIPAL admin Human or machine principal embedded in minted tokens.
--roles <csv> VGATE_VNET_ROLES — Subject roles for Edge IAP & UI RBAC (admin, tenant-admin, eng).
--scopes <csv> VGATE_VNET_SCOPES — Fine-grained permission scopes (vnet:enroll, api:read).
--ttl <seconds> VGATE_VNET_TTL_SECS 0 Token expiration TTL in seconds (0 = non-expiring).
--expose <host=target> VGATE_VNET_EXPOSE — Public tunnel mapping (app.example.com=127.0.0.1:3000).
--base-domain <domain> VGATE_BASE_DOMAIN vgate.local Root domain for automatic <node>.<net>.<base-domain> SaaS subdomains.
--auto-subdomain <bool> VGATE_AUTO_SUBDOMAIN false Automatically allocate tenant subdomains upon peer enrollment.
--cname <domain> VGATE_VNET_CNAME — Custom customer DNS CNAME virtual host mapped to a public tunnel.
--require-auth <policy> VGATE_VNET_REQUIRE_AUTH — Zero-Trust Edge IAP policy (role=eng,domain=example.com).
--publish <svc=addr> VGATE_VNET_PUBLISH — Publish local TCP/UDP services to authorized mesh peers (pg=127.0.0.1:5432).
--bind <local=peer:svc> VGATE_VNET_BIND — Bind local loopback port/VIP to a remote peer service (127.64.0.11:5432=db-01:pg).
--vpn-subnets <cidrs> VGATE_VPN_SUBNETS 192.168.0.0/16,... Private CIDR subnets advertised by a subnet-router peer.
--socks-addr <ip:port> VGATE_VNET_SOCKS_ADDR 127.0.0.1:1080 User-space RFC 1928 SOCKS5h + HTTP CONNECT + .vgate Magic DNS listener.
--socks-auth <cred> VGATE_VNET_SOCKS_AUTH — RFC 1929 user:pass or "token" auth (automatically enforced on non-loopback LAN binds).
--ui-addr <ip:port> VGATE_UI_ADDR — Optional dedicated bind address for the Web Console.
--inspect <bool> VGATE_INSPECT_ALL_ROUTES false Capture live HTTP inspector entries across general proxy routes.
--inspect-bodies <bool> VGATE_INSPECT_BODIES true Capture 4 KB body previews (false enforces strict Zero-Body HIPAA/PCI mode).
--webhook-provider <name> VGATE_WEBHOOK_PROVIDER — Edge HMAC webhook verifier (stripe, github, slack).
--webhook-secret <secret> VGATE_WEBHOOK_SECRET (sealed) Shared webhook signing secret for edge verification.
--max-nodes <count> VGATE_QUOTA_MAX_NODES 64 Maximum enrolled nodes per tenant network.
--max-tunnels <count> VGATE_QUOTA_MAX_TUNNELS 16 Maximum public tunnels per tenant network.
--state-file <path> VGATE_RUNTIME_STATE_FILE data/vnet/runtime_state.json Atomic 0600 JSON Coordinator persistence path.
--cluster-peers <urls> VGATE_CLUSTER_PEERS — Comma-separated peer Hub URLs for active-active state gossip.
--rekey-secs <sec> VGATE_REKEY_INTERVAL_SECS 900 P2P Signed-X25519 session key rotation time threshold (15 minutes).
--rekey-bytes <bytes> VGATE_REKEY_MAX_BYTES 1400000000 P2P session key rotation volume threshold (1.4 GB).
--rekey-packets <count> VGATE_REKEY_MAX_PACKETS 1000000 P2P session key rotation packet count threshold.
--rekey-grace-secs <sec> VGATE_REKEY_GRACE_SECS 15 Dual-epoch key overlap window preventing packet drops during rotation.
--trusted-proxies <csv> VGATE_TRUSTED_PROXIES — Trusted upstream L4/CDN proxy CIDRs permitted to supply X-Forwarded-For.
--max-header-bytes <n> VGATE_MAX_HEADER_BYTES 32768 Maximum inbound HTTP request header block size (32 KB).
--max-body-bytes <n> VGATE_MAX_BODY_BYTES 10485760 Maximum buffered HTTP body size (10 MB).

Exporting & Sealing Configuration via --save-config and --export-env

BASH
# Merge vgate.json + environment + CLI overrides and save sealed 0600 JSON + 0600 .env
vgate config check \
  --config vgate.json \
  --http-addr 0.0.0.0:8088 \
  --https-addr 0.0.0.0:8443 \
  --save-config ./config/vgate.sealed.json \
  --export-env ./config/vgate.env

3. vgate.json Schema v2 Example

Comments (// and #) are permitted inside vgate.json for operator annotations:

JSON
{
  // Schema v2 hierarchical & flat-compatible VGate configuration
  "schema_version": 2,
  "http_listen_addr": "0.0.0.0:8088",
  "https_enabled": true,
  "https_listen_addr": "0.0.0.0:8443",
  "tls_cert_path": "certs/fullchain.pem",
  "tls_key_path": "certs/privkey.pem",
  "tls_certs_dir": "certs/domains",
  "default_upstream": "127.0.0.1:8080",
  "lb_policy": "least_conn",
  "turn_enabled": true,
  "turn_listen_addr": "0.0.0.0:3478",
  "turn_public_ip": "203.0.113.10",
  "turn_realm": "edge.example.com",
  "turn_username": "vgate-turn",
  "turn_password": "ENC[vgate-v2:9f31...:c48a...:71b2...]",
  "rate_limit_enabled": true,
  "rate_limit_rps": 120,
  "rate_limit_burst": 240,
  "control_rate_rps": 20,
  "control_rate_burst": 40,
  "mesh_node_id": "hub-us-east-01",
  "mesh_secret": "ENC[vgate-v2:4a10...:88e1...:02d9...]",
  "vnet_network": "corp-prod",
  "vnet_cidr": "100.64.0.0/16",
  "base_domain": "edge.example.com",
  "auto_subdomain": true,
  "oidc_enabled": true,
  "oidc_issuer": "https://idp.example.com",
  "oidc_client_id": "vgate-edge",
  "oidc_client_secret": "ENC[vgate-v2:11b4...:55f0...:e93a...]",
  "quota_max_nodes_per_net": 64,
  "quota_max_tunnels_per_net": 16,
  "rekey_interval_secs": 900,
  "rekey_max_bytes": 1400000000,
  "rekey_grace_secs": 15,
  "max_header_bytes": 32768,
  "max_request_body_bytes": 10485760,
  "metrics_allow_local": true,
  "metrics_alias_root": false,
  "wasm_plugins_file": "data/vnet/wasm_plugins.json"
}

4. Admin, Mesh & VNet REST API Reference (/_vgate/*)

All /_vgate/* endpoints (except /_vgate/health and /_vgate/auth/* login pages) are protected by the dedicated Control-Plane Rate Limiter (20 rps) and require either X-VGate-Admin-Token: <vnet_tok_...>, Authorization: Bearer <vnet_tok_...>, or cluster HMAC headers (X-VGate-Timestamp + X-VGate-Signature).

Method & Endpoint Auth Scope Purpose
GET /_vgate/health Public Liveness and readiness JSON check (status: "ok").
GET /_vgate/metrics (and GET /metrics when VGATE_METRICS_ALIAS_ROOT=true) Admin / Local Prometheus text-format metrics for connections, WAF blocks, Wasm edge filters (vgate_wasm_filter_*), TURN relays, and mux streams.
GET /_vgate/wasm/plugins Admin List active WebAssembly 3.0 edge filter plugins (vvm B1+B3 IR + 4 KiB CoW).
POST /_vgate/wasm/plugins Admin Register and atomically persist (0600) a .wat or .wasm edge filter plugin with max_fuel, max_memory_pages, pool_size (1..32), and route scope.
DELETE /_vgate/wasm/plugins?id=... Admin Unregister an active WebAssembly 3.0 edge filter plugin.
GET /_vgate/logs Admin Query structured RFC 5424 operational and SECURITY logs (?level=SECURITY&limit=100).
GET /_vgate/auth/login Public Zero-Trust Edge IAP login portal (OIDC PKCE redirect or token sign-in).
GET /_vgate/auth/callback Public OIDC Authorization Code + PKCE (S256) callback verifier and HttpOnly cookie issuer.
POST /_vgate/vnet/enroll Node Token Enroll a VNet peer, allocate 100.64.x.y / 127.64.x.y VIP, and return ACL-filtered PeerMap.
GET /_vgate/vnet/map Node Token Poll updated ACL-filtered peer map, pinned Ed25519 keys, and active JIT grants.
POST /_vgate/vnet/expose Node Token Register a public SaaS subdomain or custom CNAME tunnel lease (PublicTunnelExposeRequest).
POST /_vgate/vnet/revoke Super / Tenant Admin Immediately revoke a vnet_tok_... credential or evict an enrolled node_id.
GET /_vgate/mesh/peers Cluster HMAC / Admin List registered mesh gateway peers and health status.
POST /_vgate/mesh/heartbeat Cluster HMAC Update peer latency, subnets, and STUN reflexive endpoint.
POST /_vgate/mesh/connect Node Token / HMAC Upgrade outbound TCP/TLS :443 connection into a persistent vgate-mux/1.0 reverse tunnel.
GET,POST /_vgate/cluster/sync Cluster HMAC Exchange Last-Write-Wins (LWW) CoordinatorSnapshot state and tombstones across active-active Hubs.
POST /_vgate/acme/challenge Admin Register or clear an RFC 8555 HTTP-01 key authorization token.
GET,POST /_vgate/acme/domains Admin List SNI domain certificates or register a validated PEM certificate/key pair.
GET /_vgate/ui Browser Session Render the 8-Workspace Web Console (Super-Admin or scoped Tenant Admin).
GET /_vgate/ui/state Super / Tenant Admin Fetch scoped JSON snapshot of routes, peers, tunnels, WAF counters, and inspector captures.
POST /_vgate/ui/waf/policy Super / Tenant Admin Update tenant WAF mode (block/challenge/detect), IP CIDRs, and Auto-Ban Penalty Box settings.
POST /_vgate/ui/waf/modsec Super / Tenant Admin Parse and activate custom ModSecurity SecRule directives (<= 8 KB line, <= 16 chain depth).
POST /_vgate/ui/waf/unban Super / Tenant Admin Remove a quarantined IP from the tenant Penalty Box.
GET,POST /_vgate/ui/jit Principal / Admin List pending/active JIT PAM requests or submit a new JitAccessRequest.
POST /_vgate/ui/jit/approve Super / Tenant Admin Approve a pending JIT request and mint an auto-expiring TagGrant (expires_at).
POST,DELETE /_vgate/ui/acl/grant Super / Tenant Admin Create or delete an intra-tenant or cross-tenant TagGrant rule.
POST /_vgate/ui/acl/approve Target Tenant Admin Bilaterally approve an inbound cross-tenant TagGrant (peer_approved = true).
POST /_vgate/ui/replay Super / Tenant Admin Re-send a captured HTTP/webhook exchange with optional override_to URL and edited headers/body.
POST /_vgate/ui/acme/provision Super / Tenant Admin Provision an on-demand ACME certificate for an owned domain.
POST /_vgate/ui/config Super-Admin Validate and atomically save updated configuration while preserving [REDACTED] secrets.

Part VII: VGate — Empirical Performance, Memory Profile & Sizing Guide


1. Concurrency & Low-Memory Data-Plane Mechanics

To sustain tens of thousands of simultaneous connections without GC spikes, head-of-line blocking, or thread exhaustion, vgate combines five architectural techniques:

  1. Hybrid Pre-Warmed Worker Dispatcher:
    • Keeps 16 (VGATE_WORKER_THREADS) persistent worker threads warm for sub-millisecond HTTP request handling.
    • If all warm workers are occupied by long-lived WebSocket, Server-Sent Events (text/event-stream), or database streams, additional connections overflow onto lightweight dedicated threads up to VGATE_MAX_CONNS (4,096), preventing worker-pool starvation.
  2. Kernel Readiness Polling Before Buffer Allocation (KernelReactor):
    • Uses native OS event readiness (epoll on Linux, kqueue on macOS/BSD, WSAPoll on Windows) requiring only ~64 bytes of slab state per tracked socket descriptor.
    • Idle keep-alive or Slowloris sockets consume 0 bytes of 32 KB buffer-pool RAM until the kernel signals readable bytes (POLLIN).
  3. Single-Thread Bidirectional TCP Splicing:
    • Once HTTP headers are rewritten or a VNet local bridge stream opens, a single thread multiplexes bidirectional socket forwarding over 1 shared 32 KB buffer instead of spawning two pump threads with two 32 KB buffers—cutting active thread and buffer RAM usage by 50% while enforcing mid-stream JIT TTL expiration deadlines.
  4. Keep-Alive Connection Pooling & Fast-Fail Circuit Breakers:
    • Reuses up to 32 (VGATE_POOL_MAX_IDLE) warm upstream TCP sockets per backend host and trips open in < 1 ms after 3 consecutive backend failures (10s cooldown).
  5. Compact 4-Byte TURN ChannelData Framing & 512 KB Thread Stacks:
    • Replaces 36-byte STUN headers with 4-byte ChannelData (0x4000..0x7FFF) frames on bound TURN relays (89% header reduction) and configures LimitSTACK=512K under Linux systemd (16x lower virtual stack reservation than the 8 MB OS default).

2. Empirical Subsystem Benchmarks (Debug vs. Production -prod)

The table below reports measured single-core rates from vgate's built-in Tier 5 benchmark suite comparing unoptimized debug builds against production -prod (-O3) builds:

Subsystem & Measured Operation Single-Core Rate (Debug) Single-Core Rate (-prod -O3) Speedup & Architectural Notes
KernelReactor C100K Slab Lifecycle
(register + phase transition + unregister)
266,439 ops/sec
(~3.75 us / cycle)
554,323 ops/sec
(~1.80 us / cycle)
2.08x — ~64 B per tracked FD; idle connections hold 0 B of buffer-pool memory.
Single-Thread TCP Stream Splicing
(bidirectional socket pump + JIT TTL check)
1 thread + 1 x 32 KB
(vs. 2 threads + 64 KB)
2x Concurrent Streams
(50% RAM reduction)
Halves active thread count and buffer checkouts across HTTP proxy, reverse tunnels, and VNet binds.
Two-Tier Per-IP Token Bucket
(ingress rate-limiter check)
2,004,409 ops/sec
(~0.50 us / check)
2,004,409+ ops/sec
(68,702 ops/s full sweep)
O(1) hash lookup guarded by 16,384-IP cap and automatic 180s stale-bucket eviction.
Multi-Tenant WAF Deep Inspection
(6-stage deobfuscation + 25 CVEs + OWASP CRS)
757 req/sec
(single-core debug)
4,305 req/sec / core
(~34,400+ req/s on 8 cores)
5.69x — Inspects URI, query, headers, and payload with CIDR allowlist fast-path bypass.
ChaCha20-Poly1305 Encrypted Mesh AEAD
(1,400-byte MTU seal + open + anti-replay)
830 pkt/sec
(2,800 B/iter debug)
2,594 pkt/sec / core
(~29.1 Mbps/core; ~232 Mbps/8c)
3.13x — Pure-V RFC 8439 20-round ChaCha20 + Poly1305 MAC + 64-packet sliding replay window.
RFC 5389 STUN Binding Responder
(XOR-MAPPED-ADDRESS packet builder)
845,966 pkt/sec
(~1.18 us / packet)
3,192,440 pkt/sec
(~0.31 us / packet)
3.77x — Zero-allocation 32-byte STUN response builder on UDP :3478.

3. Runtime Memory Footprint Breakdown

Runtime Component Measured Memory Allocation Operational Notes
Base Process & Static Arenas ~14 – 22 MB RSS Includes 16 warm worker threads, 64 pre-allocated 32 KB buffers (2 MB), WAF CVE ruleset, and SNI table.
Per Idle Keep-Alive Socket ~64 Bytes Tracked inside KernelReactor slab with zero 32 KB buffer checkout until readable data arrives.
Per Active Spliced Stream 1 x 32 KB Buffer + 1 Worker Applies uniformly to HTTP/WebSocket streams, vgate-mux/1.0 reverse tunnels, and VNet local binds.
4,000 Active Concurrent Connections ~32 – 38 MB RSS Sustained under mixed HTTP, SSE, and reverse-tunnel load with LimitSTACK=512K.

4. Production Hardware Sizing Matrix

Hardware / VPS Tier Concurrent Active Streams (SSE, WS, Binds, Tunnels) Idle Keep-Alive Sockets (C100K Reactor Slab) Short-Lived HTTP Throughput (Keep-Alive Pool) HTTPS Throughput (TLS 1.2/1.3) STUN / TURN Relay Capacity
Nano / Edge Appliance
(1 vCPU, 512 MB – 1 GB RAM)
~1,500 – 2,800 ~10,000 – 25,000 ~2,500 – 4,200 req/s ~300 – 600 req/s ~10,000+ STUN pkt/s
~20 – 35 TURN media streams
Standard Cloud VPS
(2 vCPU, 2 GB – 4 GB RAM)
~5,000 – 9,000 ~40,000 – 65,000 ~7,000 – 12,000 req/s ~1,000 – 1,800 req/s ~25,000+ STUN pkt/s
~65 – 120 TURN media streams
Performance Dedicated Edge
(4–8 vCPU, 8 GB – 16 GB RAM)
~12,000 – 24,000 ~100,000+ (C100K) ~18,000 – 30,000 req/s ~3,000 – 5,500 req/s ~50,000+ STUN pkt/s
~250 – 500 TURN media streams

Part VIII: VNet Developer Guide — Programmatic P2P Overlay Mesh, Cryptography, ACLs & Zero-Root Bridges


1. Module Architecture & Capabilities

The vnet module implements VGate's software-defined private overlay network entirely in user space—requiring no kernel tun/tap drivers, no CAP_NET_ADMIN, and no root privileges. Developers import vnet alongside vgconfig, vgvpn, and vgjson to build custom mesh coordinators, embedded service sidecars, automated token minters, or encrypted P2P transports.

MESH & P2P CRYPTO

Zero-Root VNet LocalBridge, Signed-X25519 2D Key Ratchet & 3-Tier Adaptive Transport

Click any stage to inspect user-space VIP binding, forward-secret AEAD encryption, and Tier 1/2/3 path selection.

Interactive SVG • Click any node (4 components)
1. USER-SPACE BRIDGE & FORWARD-SECRET AEAD 127.64.x.y VIP -> Signed-X25519 + ChaCha20 2. 3-TIER ADAPTIVE NAT & FIREWALL PATHING Tier 1 Direct UDP -> Tier 2 TURN -> Tier 3 TLS :443 Plain Stream Tier 1 / 2 AEAD Tier 3 Fallback Zero-Root Client 1. Loopback VIP & SOCKS5h 127.64.x.y + .vgate DNS Crypto Ratchet 2. Signed-X25519 2D Ratchet VHP2 ECDHE + ChaCha20-Poly1305 UDP Tiers 1-2 3. Tier 1/2 UDP & TURN Direct UDP -> 4B ChannelData TCP Tier 3 4. Tier 3 vgate-mux/1.0 TCP/TLS :443 + 64KB Window
Components:
Zero-Root Client
1. Loopback VIP & SOCKS5h
User-Space LocalBridge L7 Audit
Component 1 of 4
Architectural Role & Purpose

Exposes authorized mesh services locally via 127.64.x.y VIPs, --bind ports, vgate exec, and SOCKS5h.

Contextual Description & System Interaction

Lets unmodified CLI tools and browsers access private mesh services safely.

Core Functionality & Security Mechanics
  • Operates 100% as uid=1000 with zero kernel tun device or CAP_NET_ADMIN
  • Enforces RFC 1929 auth and cloud-metadata SSRF guards on SOCKS5h
  • Passively extracts SSH-2.0 banners and PostgreSQL db_user/db_name
Crypto Ratchet
2. Signed-X25519 2D Ratchet
Signed-X25519 PFS 64-Pkt Replay
Component 2 of 4
Architectural Role & Purpose

Establishes pairwise forward-secret AEAD session keys with dual-epoch overlap and anti-replay windows.

Contextual Description & System Interaction

Ensures central TURN or TCP relays remain 100% blind to peer-to-peer payloads.

Core Functionality & Security Mechanics
  • Signs ephemeral X25519 keys with pinned Ed25519 identities and wipes scalars
  • Rotates keys every 900s or 1.4 GB (1M packets) with 15s grace window
  • Seals 1400B MTU frames with RFC 8439 ChaCha20-Poly1305 + 64-bit replay bitmap
UDP Tiers 1-2
3. Tier 1/2 UDP & TURN
Hole-Punch Prober TURN Relay
Component 3 of 4
Architectural Role & Purpose

Prioritizes direct STUN hole-punched UDP and falls back to 4-byte RFC 5766 ChannelData UDP relays.

Contextual Description & System Interaction

Sustains real-time low-jitter P2P transport across home, LTE/5G, and cloud NATs.

Core Functionality & Security Mechanics
  • Continuously probes direct reflexive UDP latency for lowest-RTT pathing
  • Switches seamlessly to bound TURN channels (0x4000..0x7FFF) behind CGNAT
  • Validates >=52-byte AEAD ChannelData payloads before unwrapping
TCP Tier 3
4. Tier 3 vgate-mux/1.0
Reverse Tunnel Mux Flow Control
Component 4 of 4
Architectural Role & Purpose

Multiplexes concurrent L4 streams over a single outbound TCP/TLS :443 connection when UDP is blocked.

Contextual Description & System Interaction

Guarantees resilient connectivity across the strictest corporate egress firewalls.

Core Functionality & Security Mechanics
  • Slices streams into 16 KB frames with 12-byte vgate-mux/1.0 headers
  • Enforces per-stream 64 KB receive windows via WINDOW_UPDATE (0x0A)
  • Supports pure TCP :443 deployments with zero exposed UDP ports

Subsystem Responsibilities

Subsystem Key Types & Entry Points Developer Responsibility
Mesh Coordinator Coordinator, new_coordinator, enroll_node, build_filtered_peer_map Manages IPAM (100.64.0.0/10 to 127.64.x.y), tenant isolation, TagGrant ACL filtering, public tunnel leases, and atomic 0600 JSON snapshots.
Identity & Tokens NodeIdentity, mint_subject_token, verify_token_to_subject, inspect_vnet_token Generates Ed25519 node keypairs and mints/verifies HMAC-SHA256 scoped vnet_tok_... credentials (including 68-byte SOCKS5-ready compact tokens).
PFS & AEAD Dataplane VNetDataPlane, new_dataplane, establish_pfs_pair, seal_peer_mux_frame, open_peer_mux_frame Executes Ed25519-signed RFC 7748 X25519 (VHP2) ephemeral key exchanges, directional HKDF subkeys, and RFC 8439 ChaCha20-Poly1305 packet sealing.
2D Key Ratchet SessionKeyRing, new_directional_keyring, ratchet_session_keyring_x25519, needs_rekey Rotates session epochs automatically by time (900s default) or volume (1.4 GB / 1,000,000 packets) with a 15s dual-epoch grace window.
3-Tier Path & NAT PeerPathState, wrap_vnet_packet_for_tier, encode_hole_punch_probe, select_optimal_path Encapsulates packets for direct_udp (Tier 1), turn_channel (Tier 2, 0x4000..0x7FFF), or tls_mux (Tier 3, vgvpn.MuxFrame).
Zero-Root Bridge LocalBridge, start_local_bridge, resolve_magic_dns, negotiate_socks5_handshake_with_auth Exposes local 127.64.x.y loopback VIPs, --bind TCP/UDP port forwarders, .vgate Magic DNS, and an RFC 1928/1929 SOCKS5h proxy.
Service & Ops generate_service_bundle, generate_k8s_and_compose_manifests Emits production systemd, Windows sc.exe, macOS launchd, Docker Compose, and Kubernetes manifests from a vgconfig.Config.

2. Core Data Structures & API Reference

Control Plane & Enrollment Types

Symbol Purpose Key Fields / Parameters
Coordinator Thread-safe mesh state & policy engine Initialized via vnet.new_coordinator(cfg). Holds peers, tunnels, revocations, TagGrants, JIT requests, and L7 audit events.
EnrollRequest Node registration payload node_id, network_slug, token, public_key_hex, tags, lan_endpoints, stun_endpoint, published_services, auto_expose_target, cname_host.
PeerMapResponse Filtered peer map returned on enroll/sync ok, self_peer, authorized_peers, public_tunnels, cluster_hubs, negotiated_transport, mux_window_bytes, hub_stun_addr.
EnrolledPeer Authenticated peer descriptor node_id, network_slug, overlay_ip (100.64.x.y), loopback_vip (127.64.x.y), magic_dns (<node>.<net>.vgate), public_key_hex, tags, transport_tier, published_services.
PublishedService Local service advertised to mesh peers name (e.g. 'pg'), proto ('tcp' or 'udp'), local_addr, port.
TagGrant Identity-based ACL rule id, network_slug, target_network_slug, peer_approved, src_tags, dst_tags, allowed_ports, allow_public_expose, allowed_domains, expires_at.
JitAccessRequest Temporary privileged access request request_id, network_slug, principal, src_tags, dst_tags, allowed_ports, ttl_secs, reason, status.

Cryptography & Data-Plane Types

Symbol Purpose Key Constants / Methods
NodeIdentity Persistent Ed25519 node identity generate_node_identity(node_id) or load_or_create_identity(data_dir, node_id).
VNetPacket Wire-format encrypted packet (VN magic) vnet_header_len = 20, vnet_tag_len = 16, vnet_pkt_data_chacha20 = 0x11, vnet_pkt_handshake = 0x02, vnet_pkt_probe = 0x03.
ReplayWindow 64-packet sliding anti-replay bitmask rw.check_and_accept(seq) rejects duplicate or stale sequence numbers.
VNetDataPlane High-level P2P session & frame manager initiate_peer_handshake, process_peer_handshake, establish_pfs_pair, seal_peer_mux_frame, open_peer_mux_frame.
SessionKeyRing Directional epoch keys + grace window new_directional_keyring, ratchet_session_keyring_x25519, seal_with_keyring, open_with_keyring, purge_expired_grace_key.

3. Developer Examples

All examples below use the vnet module directly and can be compiled inside a V project that has access to the vgate modules (v run .).

Example 1: Initialize a Coordinator, Mint Scoped Tokens & Enroll Peers

This example bootstraps an in-memory Coordinator, mints HMAC-signed subject tokens for two nodes (api-01 and db-01), generates their Ed25519 identities, and enrolls both into the corp-prod overlay namespace.

V
module main

import time
import vgconfig
import vnet

fn main() {
	cfg := vgconfig.Config{
		mesh_secret:  'replace-with-32-byte-hex-or-random-secret'
		vnet_network: 'corp-prod'
		vnet_cidr:    '100.64.0.0/16'
	}

	mut coord := vnet.new_coordinator(cfg)
	now := time.now().unix()

	// 1. Mint scoped enrollment tokens (ttl=3600s)
	api_tok := vnet.mint_subject_token(
		cfg.mesh_secret,
		'svc:api-01',
		'corp-prod',
		['node'],
		['vnet:enroll'],
		['tag:api'],
		3600,
	)
	db_tok := vnet.mint_subject_token(
		cfg.mesh_secret,
		'svc:db-01',
		'corp-prod',
		['node'],
		['vnet:enroll'],
		['tag:db'],
		3600,
	)

	// Verify token claims programmatically
	net_slug, subj := vnet.verify_token_to_subject(cfg.mesh_secret, api_tok, now) or {
		panic(err)
	}
	println('Verified token for ${subj.principal} in network ${net_slug}')

	// 2. Generate Ed25519 node identities
	ident_api := vnet.generate_node_identity('api-01') or { panic(err) }
	ident_db := vnet.generate_node_identity('db-01') or { panic(err) }

	// 3. Enroll peers into the Coordinator
	_ = coord.enroll_node(vnet.EnrollRequest{
		node_id:            'db-01'
		network_slug:       'corp-prod'
		token:              db_tok
		public_key_hex:     ident_db.public_key_hex
		tags:               ['tag:db']
		published_services: [
			vnet.PublishedService{
				name:       'pg'
				proto:      'tcp'
				local_addr: '127.0.0.1'
				port:       5432
			},
		]
	}) or { panic(err) }

	api_map := coord.enroll_node(vnet.EnrollRequest{
		node_id:        'api-01'
		network_slug:   'corp-prod'
		token:          api_tok
		public_key_hex: ident_api.public_key_hex
		tags:           ['tag:api']
	}) or { panic(err) }

	println('api-01 overlay IP   : ${api_map.self_peer.overlay_ip}')
	println('api-01 loopback VIP : ${api_map.self_peer.loopback_vip}')
	println('api-01 magic DNS    : ${api_map.self_peer.magic_dns}')
	println('Authorized peers    : ${api_map.authorized_peers.len}')
}

Example 2: Tag-Based ACLs (TagGrant) & Just-In-Time (JIT) Access

VNet enforces default-deny isolation between tags. You can grant standing tag-to-tag port access with upsert_tag_grant, or issue temporary, auto-expiring leases via the JIT workflow (request_jit_access -> approve_jit_access).

V
module main

import time
import vgconfig
import vnet

fn main() {
	cfg := vgconfig.Config{
		mesh_secret: 'replace-with-32-byte-hex-or-random-secret'
	}
	mut coord := vnet.new_coordinator(cfg)
	now := time.now().unix()

	// 1. Standing ACL: allow tag:api -> tag:db on PostgreSQL (5432) only
	coord.upsert_tag_grant(vnet.TagGrant{
		id:            'grant-api-to-db'
		network_slug:  'corp-prod'
		src_tags:      ['tag:api']
		dst_tags:      ['tag:db']
		allowed_ports: [5432]
		reason:        'Production API database access'
	})

	// Evaluate ACL policy directly
	can_pg := vnet.check_scoped_tag_grant(
		coord.list_grants_for_tenant('corp-prod', false),
		'corp-prod', ['tag:api'],
		'corp-prod', ['tag:db'],
		5432,
	)
	can_ssh := vnet.check_scoped_tag_grant(
		coord.list_grants_for_tenant('corp-prod', false),
		'corp-prod', ['tag:api'],
		'corp-prod', ['tag:db'],
		22,
	)
	println('api -> db:5432 allowed=${can_pg}, api -> db:22 allowed=${can_ssh}')

	// 2. Request a 15-minute (900s) Just-In-Time SSH break-glass grant
	jit_req := coord.request_jit_access(vnet.JitAccessRequest{
		request_id:    'jit-inc-4042'
		network_slug:  'corp-prod'
		principal:     'oncall@example.com'
		src_tags:      ['tag:oncall']
		dst_tags:      ['tag:db']
		allowed_ports: [22]
		ttl_secs:      900
		reason:        'INC-4042: Inspect PostgreSQL WAL replication lag'
	}, now) or { panic(err) }

	// 3. Approve the JIT request to mint an auto-expiring TagGrant
	jit_grant := coord.approve_jit_access(
		jit_req.request_id,
		'sec-lead@example.com',
		'corp-prod',
		false,
		now,
	) or { panic(err) }

	ttl_ms := vnet.resolve_grant_remaining_ttl_ms(
		[jit_grant],
		'corp-prod', ['tag:oncall'],
		'corp-prod', ['tag:db'],
		22,
		now,
	)
	println('Approved JIT grant ${jit_grant.id}, remaining TTL=${ttl_ms}ms')
}

Example 3: Forward-Secret P2P Session (VNetDataPlane + X25519 VHP2)

VNetDataPlane automates the Ed25519-signed X25519 VHP2 ephemeral handshake, derives directional tx_key/rx_key subkeys via HKDF-SHA256, and seals vgvpn.MuxFrame payloads inside ChaCha20-Poly1305 VNetPackets.

V
module main

import time
import vgconfig
import vgvpn
import vnet

fn main() {
	cfg := vgconfig.Config{
		mesh_secret: 'replace-with-32-byte-hex-or-random-secret'
	}
	now := time.now().unix()

	ident_a := vnet.generate_node_identity('node-a') or { panic(err) }
	ident_b := vnet.generate_node_identity('node-b') or { panic(err) }

	peer_a := vnet.EnrolledPeer{
		node_id:        'node-a'
		network_slug:   'corp-prod'
		overlay_ip:     '100.64.0.10'
		public_key_hex: ident_a.public_key_hex
		transport_tier: 'direct_udp'
	}
	peer_b := vnet.EnrolledPeer{
		node_id:        'node-b'
		network_slug:   'corp-prod'
		overlay_ip:     '100.64.0.11'
		public_key_hex: ident_b.public_key_hex
		transport_tier: 'direct_udp'
	}

	mut dp_a := vnet.new_dataplane(cfg, ident_a, peer_a.overlay_ip)
	mut dp_b := vnet.new_dataplane(cfg, ident_b, peer_b.overlay_ip)

	// Execute bidirectional X25519 VHP2 handshake (or pass syn_wire/ack_wire over network)
	dp_a.establish_pfs_pair(mut dp_b, peer_a, peer_b, now) or { panic(err) }
	println('PFS established on A=${dp_a.has_pfs_session("node-b")}')

	// Seal a MuxFrame from node-a -> node-b
	outbound := vgvpn.MuxFrame{
		frame_type: vgvpn.frame_stream_data
		flags:      0
		stream_id:  42
		payload:    'SELECT 1;'.bytes()
	}
	tier, wire_bytes := dp_a.seal_peer_mux_frame(peer_b, outbound) or { panic(err) }
	println('Sealed ${wire_bytes.len} bytes for transport tier=${tier}')

	// Open and verify on node-b (enforces Poly1305 tag + 64-packet ReplayWindow)
	decoded := dp_b.open_peer_mux_frame(peer_a, wire_bytes) or { panic(err) }
	println('Decoded stream=${decoded.stream_id} payload="${decoded.payload.bytestr()}"')
}

Example 4: Low-Level Packet Sealing, Anti-Replay & 2D Key Ratchet

When building custom transports or testing epoch rotation directly, use seal_packet_chacha20, open_packet_chacha20, ReplayWindow, and SessionKeyRing.

V
module main

import time
import vgconfig
import vgvpn
import vnet

fn main() {
	cfg := vgconfig.Config{
		mesh_secret:         'replace-with-32-byte-hex-or-random-secret'
		rekey_interval_secs: 900
		rekey_max_bytes:     1_400_000_000
	}
	now := time.now().unix()

	// 1. Direct pairwise session key & ChaCha20-Poly1305 packet sealing
	skey := vnet.derive_pairwise_session_key(cfg.mesh_secret, 'pubA', 'pubB', 1)
	src_ip := vgvpn.parse_ipv4_u32('100.64.0.10') or { u32(0) }
	dst_ip := vgvpn.parse_ipv4_u32('100.64.0.11') or { u32(0) }

	pkt := vnet.VNetPacket{
		pkt_type:  vnet.vnet_pkt_data_chacha20
		key_epoch: 1
		src_ip:    src_ip
		dst_ip:    dst_ip
		seq:       1
		payload:   'heartbeat-ok'.bytes()
	}
	wire := vnet.seal_packet_chacha20(skey, pkt) or { panic(err) }

	mut rw := vnet.ReplayWindow{}
	opened := vnet.open_packet_chacha20(skey, wire, mut rw) or { panic(err) }
	println('Opened seq=${opened.seq} payload="${opened.payload.bytestr()}"')

	// Replaying the exact same wire packet is rejected by ReplayWindow
	if _ := vnet.open_packet_chacha20(skey, wire, mut rw) {
		panic('Replay should have been rejected')
	} else {
		println('Duplicate packet correctly rejected: ${err}')
	}

	// 2. Directional SessionKeyRing & X25519 epoch ratchet
	mut ring := vnet.new_directional_keyring(cfg, 'node-a', 'node-b', skey, now)
	mut kp_a := vnet.generate_x25519_keypair() or { panic(err) }
	kp_b := vnet.generate_x25519_keypair() or { panic(err) }

	// Ratchet to epoch 2 (retains epoch 1 for rekey_grace_secs=15s)
	vnet.ratchet_session_keyring_x25519(mut ring, mut kp_a, kp_b.public_point_hex, cfg.mesh_secret, 2, now + 901) or {
		panic(err)
	}
	println('Ratcheted keyring to epoch=${ring.current_epoch}, needs_rekey=${vnet.needs_rekey(ring, now + 901)}')
}

Example 5: Zero-Root Local Bridge, Magic DNS, Port Binds & L7 Inspection

LocalBridge translates user-space --publish, --bind, and .vgate Magic DNS lookups into vgvpn.StreamOpenRequest frames without touching OS routing tables.

V
module main

import vgconfig
import vnet

fn main() {
	cfg := vgconfig.Config{
		mesh_node_id:    'workstation-01'
		vnet_network:    'corp-prod'
		vnet_socks_addr: '127.0.0.1:1080'
		vnet_bind:       '127.64.0.11:5432=db-01:pg,udp://127.0.0.1:15353=dns-01:53'
	}

	// Parse published services and local port binds
	published := vnet.parse_published_services('pg=127.0.0.1:5432,metrics=127.0.0.1:9090')
	binds := vnet.parse_local_binds(cfg.vnet_bind)
	println('Parsed ${published.len} published services and ${binds.len} local binds')

	peers := [
		vnet.EnrolledPeer{
			node_id:            'db-01'
			network_slug:       'corp-prod'
			overlay_ip:         '100.64.0.11'
			loopback_vip:       '127.64.0.11'
			magic_dns:          'db-01.corp-prod.vgate'
			published_services: published
		},
	]

	// Resolve .vgate Magic DNS hostname or 127.64.x.y VIP
	if peer := vnet.resolve_magic_dns('db-01.corp-prod.vgate', peers) {
		println('Resolved ${peer.magic_dns} -> overlay=${peer.overlay_ip} vip=${peer.loopback_vip}')
	}

	// Resolve a LocalPortBind into a target peer + Mux StreamOpenRequest
	target_peer, open_req := vnet.resolve_bind_stream_open(binds[0], peers) or { panic(err) }
	println('Bind ${binds[0].bind_addr} -> ${target_peer.node_id} (${open_req.target_host}:${open_req.target_port})')

	// Passive L7 wire protocol detection (PostgreSQL, SSH, Redis, HTTP, TLS)
	ssh_banner := 'SSH-2.0-OpenSSH_9.6\r\n'.bytes()
	l7 := vnet.inspect_l7_wire_protocol(ssh_banner, 22)
	println('Detected L7 protocol=${l7.protocol} detail=${l7.summary}')
}

Example 6: Public Tunnel Leases, Atomic State Persistence & Deployment Bundles

You can register ngrok-style public ingress tunnels with OIDC/role policies, persist the Coordinator state atomically (0600), and generate Docker Compose, Kubernetes, systemd, Windows, and macOS service manifests.

V
module main

import vgconfig
import vnet

fn main() {
	cfg := vgconfig.Config{
		mesh_node_id:       'edge-hub-01'
		vnet_network:       'corp-prod'
		base_domain:        'edge.example.com'
		runtime_state_file: 'data/vnet/runtime_state.json'
	}

	mut coord := vnet.new_coordinator(cfg)

	// 1. Register a public reverse tunnel protected by Edge IAP policy
	lease := coord.register_public_tunnel_with_policy(
		'app-01',
		'portal.edge.example.com',
		'127.0.0.1:3000',
		'role=eng,domain=example.com',
	) or { panic(err) }
	println('Registered tunnel ${lease.public_host} -> ${lease.local_target} (auth=${lease.require_auth})')

	// 2. Persist Coordinator state atomically (0600) and reload
	coord.save_state() or { panic(err) }
	loaded_peers := coord.load_state() or { panic(err) }
	println('Reloaded coordinator state (${loaded_peers} peers)')

	// 3. Generate deployment manifests (compose.yaml + vgate-k8s.yaml + OS daemons)
	bundle := vnet.generate_service_bundle(cfg) or { panic(err) }
	println('Generated systemd unit: ${bundle.systemd_unit_path}')
	println('Generated compose file: ${bundle.compose_path}')
	println('Generated K8s manifest: ${bundle.k8s_manifest_path}')
}

4. HTTP Control-Plane & Mesh API Integration (/_vgate/*)

External services, CI/CD pipelines, and non-V clients can manage vnet over HTTPS/HTTP against a running vgate serve hub using a scoped vnet_tok_... bearer token (Authorization: Bearer <token> or X-VGate-Admin-Token: <token>).

BASH
# 1. Check hub readiness (unauthenticated)
curl -sS http://127.0.0.1:8088/_vgate/health

# 2. Enroll a peer or fetch the ACL-filtered peer map
curl -sS -X POST http://127.0.0.1:8088/_vgate/vnet/enroll \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $VNET_TOKEN" \
  -d '{
    "node_id": "worker-01",
    "network_slug": "corp-prod",
    "token": "'"$VNET_TOKEN"'",
    "tags": ["tag:worker"],
    "published_services": [{"name": "metrics", "proto": "tcp", "local_addr": "127.0.0.1", "port": 9090}]
  }'

# 3. List enrolled peers visible to this tenant
curl -sS http://127.0.0.1:8088/_vgate/vnet/peers \
  -H "Authorization: Bearer $ADMIN_TOKEN"

# 4. Revoke a compromised token or node immediately
curl -sS -X POST http://127.0.0.1:8088/_vgate/vnet/tokens/revoke \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -d '{"token": "'"$COMPROMISED_TOKEN"'"}'

5. Security & Operational Best Practices

  1. Always Bind Loopback VIPs (127.64.x.y) in User Space: Use overlay_ip_to_loopback_vip when exposing remote mesh services locally so processes run as non-root (uid=1000, cap_drop: ALL) without kernel tun devices.
  2. Enforce SOCKS5 Authentication on Non-Loopback Binds: requires_socks5_auth(cfg) automatically requires RFC 1929 username/password or vnet_tok_... authentication whenever --socks-addr binds outside 127.0.0.1 / ::1. Use mint_compact_subject_token when tokens must fit within the 255-byte RFC 1929 password limit.
  3. Never Skip ReplayWindow or Reuse Nonces: Always pass a mutable ReplayWindow to open_packet_chacha20 / unwrap_mux_from_vnet_packet and use VNetDataPlane.next_sequence() for monotonic 64-bit sequence numbers.
  4. Keep SessionKeyRing Rotation Enabled: Retain the default rekey_interval_secs = 900 and rekey_max_bytes = 1_400_000_000 with rekey_grace_secs = 15 so in-flight packets survive epoch transitions without dropping streams.
  5. Seal Secrets at Rest: Store mesh_secret and vnet_token encrypted inside vgate.json (ENC[vgate-v2:...]) protected by data/vnet/config.master.key (0600), and rotate the master key periodically via vgate config rotate-key.