1. Cookbook
TunnelSats Public Wireguard API
  • Announcements
    • 👋 About our team
    • 💫 What is TunnelSats?
    • 🚀 Introducing the TunnelSats Public API v1
    • 🧩 How the TunnelSats StartOS Package Uses the Public API
    • How TunnelSats Leverages Public APIs for Confined VPN Management
    • 🤖 Autonomous Agent Payments (L402 & x402) & Level 5 Agent-Native Architecture
  • 📡 Discovery
    • List Available WireGuard Servers & Regions
      GET
    • L402 Agent Payment Gateway Discovery Metadata
      GET
  • ⚡ Purchase
    • Create a New WireGuard Subscription (Invoice Generation)
      POST
    • Check Invoice Status & Polling by Payment Hash
      GET
    • Claim WireGuard Configuration After Payment Settlement
      POST
    • Autonomous Agent HTTP 402 Gateway (L402 Purchase + Claim)
      POST
  • 🔄 Lifecycle
    • Get Subscription & Bandwidth Status by WireGuard Public Key
      POST
    • Sync Subscription (Real-Time Server Refresh)
      POST
    • Renew an Existing VPN Subscription (Anonymous)
      POST
    • Request Bandwidth Top-Up ($1 Usage Reset)
      POST
  • 🔑 Account
    • List Account Subscriptions (Authenticated)
      GET
    • Create Referral Code
      POST
    • Get Referral Code
      GET
    • Referral History
      GET
  • 🔧 Tools
    • Lightning Node Network Address Discovery
    • Universal Connectivity & Latency Probe
  • Cookbook
    • 🛠️ Automation & Code Examples
    • 🐚 Bash One-Liners
    • 🚑 Node Health & Upkeep
    • ⚡ Bandwidth Top-Up ($1 Usage Reset)
    • 🛡️ Security & Authentication
    • 🎁 Referral Program: Earn Bonus Months
    • 🛑 Error Codes & Troubleshooting
    • 🤖 Agent Payments: L402 & x402 Protocol
  • Schemas
    • Server
    • InvoiceOrder
    • SubscriptionStatus
    • NodeLookup
    • ConnectivityResult
    • ApiError
    • ClaimResult
    • BandwidthResetResponse
    • PublicKeyStatusResponse
    • SubscriptionListItem
    • ReferralCode
    • ReferralHistory
    • BandwidthResetPaymentStatus
    • RenewalOrder
    • SyncResult
Tunnelsats Github
Tunnelsats Telegram
  1. Cookbook

🤖 Agent Payments: L402 & x402 Protocol

TunnelSats supports autonomous machine-to-machine payments over the Bitcoin Lightning Network via HTTP 402 Payment Required, combining an interoperable L402 runtime (WWW-Authenticate: L402 binary V2 macaroon + preimage verification), an experimental x402 v2 discovery adapter (PAYMENT-REQUIRED JSON envelope using custom scheme: "l402", CAIP-2 Bitcoin mainnet network: "bip122:000000000019d6689c085ae165831e93", asset: "SAT", and extra.adapterRole: "discovery"), and OpenAPI x-l402-payment-info discovery metadata at https://tunnelsats.com/openapi.json.
This allows AI agents, MCP tools, and automated node scripts to purchase and provision a dedicated port-forwarded WireGuard VPN tunnel on a customer's behalf in a single HTTP 402 challenge-response cycle.

⚡ How the HTTP 402 (L402 + Experimental x402 Discovery Adapter) Flow Works#

1.
Discovery (GET /api/v1) & Challenge (POST /api/v1 -> HTTP 402 Payment Required):
Calling GET https://tunnelsats.com/api/v1 (L402 Agent Payment Gateway Discovery Metadata) returns 200 OK with read-only discovery metadata and step-by-step instructions (never a fake 402 challenge or placeholder invoice).
Your agent generates a local WireGuard X25519 keypair (wg genkey / wg pubkey) so the private key never leaves your host.
Your agent calls POST https://tunnelsats.com/api/v1 (Autonomous Agent HTTP 402 Gateway) with { "serverId": "eu-de", "duration": 1, "wgPublicKey": "<base64_pubkey>" }.
TunnelSats creates a live mainnet (lnbc) BOLT11 Lightning invoice, verifies its secp256k1 recoverable signature, paymentHash, amountSats, and active expiry (expiresAt > now), registers the pending order with a unique encrypted 32-byte L402 root key, and returns HTTP 402 Payment Required with:
WWW-Authenticate: L402 macaroon="<base64_v2_macaroon>", invoice="lnbc..." (zero-dependency libmacaroons / gopkg.in/macaroon.v2 binary format V2 codec with the 66-byte L402 identifier uint16be(0) || paymentHash[32] || tokenId[32] and minted first-party caveats order_id, server_id, duration, amount_sats, tunnelsats_valid_until, and wg_public_key).
PAYMENT-REQUIRED: <base64_encoded_x402_v2_json> (an x402 v2-shaped PaymentRequired discovery envelope with x402Version: 2, resource metadata with 5 tags, and accepts[0] advertising our custom scheme: "l402" over bip122:000000000019d6689c085ae165831e93 / asset: "SAT" with extra.adapterRole: "discovery"). The 402 JSON response body spreads this envelope at the root alongside a top-level l402 convenience object.
Two independent clocks: maxTimeoutSeconds reflects the live BOLT11 quote payment window (~1 hour), while the macaroon's tunnelsats_valid_until caveat grants a 24-hour redemption grace window (invoiceExpiresAt + 86400) after invoice expiry.
2.
Lightning Settlement (Cryptographic Preimage):
Your agent pays the lnbc... BOLT11 invoice using any Lightning wallet or daemon (lncli payinvoice, lightning-cli pay, Alby NWC, LND REST, Strike, or Cashu melt).
Upon settlement, the Lightning Network reveals the 32-byte payment preimage (64-character hex string) where SHA256(preimage) == paymentHash.
3.
Authenticated Claim (POST /api/v1 -> HTTP 200 OK) & Permanent Recovery Fallback:
Your agent replays the same POST https://tunnelsats.com/api/v1 request with header:
(or X-PAYMENT: <base64_json> / PAYMENT-SIGNATURE: <base64_json> carrying the L402 { "macaroon": "...", "preimage": "..." } proof).
Clients may optionally attenuate the binary V2 macaroon with stricter first-party caveats (such as a tighter tunnelsats_valid_until=<unix_ts>, services=tunnelsats:0, tunnelsats_capabilities=claim, or tunnelsats_action=claim); verifyL402Macaroon() groups caveats by condition, enforces SatisfyPrevious subset narrowing, and verifies that the final service/capability still authorizes tunnelsats / claim.
TunnelSats verifies the binary V2 macaroon signature and caveats, verifies SHA256(preimage) === paymentHash, confirms LNbits settlement via executeSubscriptionClaim(), provisions the WireGuard peer, and returns 200 OK with your tunnel parameters (server, peer, vpnPort, subscriptionEnd).
Paid-Order Recovery: If an agent attempts redemption after tunnelsats_valid_until (24 hours past invoice expiry), POST /api/v1 returns 401 Unauthorized ("code": "l402_macaroon_expired") and directs the caller to Claim WireGuard Configuration After Payment Settlement (POST https://tunnelsats.com/api/public/v1/subscription/claim with { "paymentHash": "<64-char-hex>", "wgPublicKey": "<base64_pubkey>" }), where any settled order remains permanently claimable.

🛠️ Autonomous Agent Code Examples#

Python (L402 Agent)
Node.js / TypeScript (L402 & x402)
Bash (cURL + lncli)
Zero Polling Required
With L402, once your Lightning node returns the payment preimage from paying the BOLT11 invoice, your agent immediately exchanges L402 <macaroon>:<preimage> for the provisioned WireGuard tunnel.

🔍 Machine Discovery Endpoints#

Autonomous agents can discover TunnelSats' payment and authentication schemas automatically via standard RFC endpoints:
Discovery ResourceURLStandard
API Cataloghttps://tunnelsats.com/.well-known/api-catalogRFC 9727 (application/linkset+json)
OpenAPI + L402 Spechttps://tunnelsats.com/openapi.jsonOpenAPI 3.0.3 + x-service-info & x-l402-payment-info
Agent Auth Guidehttps://tunnelsats.com/auth.mdAuth.md (Bearer, NIP-98 Nostr, L402/x402)
LLM Documentation Indexhttps://tunnelsats.com/llms.txt & https://api.tunnelsats.com/llms.txtllms.txt
HTTP 402 Agent Gatewayhttps://tunnelsats.com/api/v1L402 + x402 v2 (PAYMENT-REQUIRED)
Modified at 2026-10-16 19:46:25
Previous
🛑 Error Codes & Troubleshooting
Next
Server
Built with