{"id":47963007,"url":"https://github.com/forgesworn/toll-booth-rs","last_synced_at":"2026-04-04T10:03:49.531Z","repository":{"id":347384260,"uuid":"1193903271","full_name":"forgesworn/toll-booth-rs","owner":"forgesworn","description":"L402 payment middleware for Rust. Gates any HTTP API behind Lightning payments.","archived":false,"fork":false,"pushed_at":"2026-03-27T21:20:21.000Z","size":67,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-03-28T01:48:32.908Z","etag":null,"topics":["axum","bitcoin","http-402","l402","lightning","macaroons","middleware","payments","paywall","rust"],"latest_commit_sha":null,"homepage":"https://github.com/forgesworn/toll-booth-rs","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/forgesworn.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-27T17:46:44.000Z","updated_at":"2026-03-27T21:20:24.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/forgesworn/toll-booth-rs","commit_stats":null,"previous_names":["forgesworn/toll-booth-rs"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/forgesworn/toll-booth-rs","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/forgesworn%2Ftoll-booth-rs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/forgesworn%2Ftoll-booth-rs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/forgesworn%2Ftoll-booth-rs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/forgesworn%2Ftoll-booth-rs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/forgesworn","download_url":"https://codeload.github.com/forgesworn/toll-booth-rs/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/forgesworn%2Ftoll-booth-rs/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31395450,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-04T09:13:02.600Z","status":"ssl_error","status_checked_at":"2026-04-04T09:13:01.683Z","response_time":60,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["axum","bitcoin","http-402","l402","lightning","macaroons","middleware","payments","paywall","rust"],"created_at":"2026-04-04T10:03:48.789Z","updated_at":"2026-04-04T10:03:49.520Z","avatar_url":"https://github.com/forgesworn.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# toll-booth\n\nL402 payment middleware for Rust. Gates any HTTP API behind Lightning payments using a bring-your-own-backend, bring-your-own-storage model. Works as a Tower `Layer`, so it drops straight into axum.\n\nOne Lightning payment funds multiple API calls. The engine tracks credit balances, debits per request, and re-challenges when the balance runs out. Supports free tiers, tiered pricing, cost reconciliation, and custom macaroon caveats.\n\n## Why toll-booth?\n\n- **Credit-balance model** -- one payment buys N requests, not one. Clients top up and keep calling.\n- **Cost reconciliation** -- adjust credits after the upstream responds if actual cost differed from estimate.\n- **Free tier** -- configurable free requests or free credits per IP per day, with hashed IPs and daily rotation.\n- **Tiered pricing** -- different prices per route per tier, selected by `X-Toll-Tier` header.\n- **Pluggable everything** -- bring your own Lightning backend, storage backend, and payment rails.\n- **Security defaults** -- constant-time HMAC and preimage verification, overflow-checked arithmetic, daily-salted IP hashing.\n\n## Quick start\n\n```toml\n[dependencies]\ntoll-booth = { version = \"0.1\", features = [\"l402\", \"axum-middleware\"] }\n```\n\n```rust\nuse std::sync::Arc;\nuse toll_booth::{\n    TollBoothEngine, TollBoothConfig,\n    L402Rail, L402RailConfig,\n    MemoryStorage,\n    TollBoothLayer,\n    PricingEntry,\n};\n\nasync fn handler() -\u003e \u0026'static str {\n    \"Hello from the paid API\"\n}\n\n#[tokio::main]\nasync fn main() {\n    let storage = Arc::new(MemoryStorage::new());\n\n    let l402 = L402Rail::new(L402RailConfig {\n        root_key: std::env::var(\"L402_ROOT_KEY\").unwrap(),\n        storage: storage.clone(),\n        default_amount: 100,        // sats, used when no backend is attached\n        backend: None,              // swap in PhoenixdBackend or similar\n        service_name: Some(\"My API\".to_string()),\n    });\n\n    let mut pricing = std::collections::HashMap::new();\n    pricing.insert(\"/v1/chat/completions\".to_string(), PricingEntry::Simple(100));\n\n    let engine = TollBoothEngine::new(TollBoothConfig {\n        storage,\n        pricing,\n        upstream: \"http://127.0.0.1:8080\".into(),\n        root_key: std::env::var(\"L402_ROOT_KEY\").unwrap(),\n        rails: vec![Box::new(l402)],\n        ..Default::default()\n    })\n    .unwrap();\n\n    let app = axum::Router::new()\n        .route(\"/v1/chat/completions\", axum::routing::post(handler))\n        .layer(TollBoothLayer::new(engine));\n\n    let listener = tokio::net::TcpListener::bind(\"0.0.0.0:3000\").await.unwrap();\n    axum::serve(listener, app).await.unwrap();\n}\n```\n\nA request to a priced route without credentials gets a `402 Payment Required` with:\n\n- `WWW-Authenticate: L402 macaroon=\"...\", invoice=\"...\"`\n- JSON body: `{ \"l402\": { \"macaroon\": \"...\", \"payment_hash\": \"...\", \"invoice\": \"...\", \"amount_sats\": 100 } }`\n\nThe client pays the Lightning invoice, then retries with:\n\n```\nAuthorization: L402 \u003cmacaroon\u003e:\u003cpreimage_hex\u003e\n```\n\nThe engine verifies the preimage against the payment hash, credits the account, and debits on each subsequent request until the balance is exhausted.\n\n## Bring Your Own Backend\n\nImplement `LightningBackend` to connect to any Lightning node:\n\n```rust\nuse async_trait::async_trait;\nuse toll_booth::{LightningBackend, Invoice, InvoiceStatus, BackendError};\n\npub struct MyBackend { /* ... */ }\n\n#[async_trait]\nimpl LightningBackend for MyBackend {\n    async fn create_invoice(\n        \u0026self,\n        amount_sats: u64,\n        memo: Option\u003c\u0026str\u003e,\n    ) -\u003e Result\u003cInvoice, BackendError\u003e {\n        // call your node, return Invoice { bolt11, payment_hash }\n        todo!()\n    }\n\n    async fn check_invoice(\n        \u0026self,\n        payment_hash: \u0026str,\n    ) -\u003e Result\u003cInvoiceStatus, BackendError\u003e {\n        // return InvoiceStatus { paid, preimage }\n        todo!()\n    }\n}\n```\n\nPass it to `L402RailConfig::backend`:\n\n```rust\nbackend: Some(Arc::new(MyBackend::new(/* ... */))),\n```\n\nWhen `backend` is `None`, the engine generates a random `payment_hash` and never checks payment status. Useful for development and testing.\n\n## Bring Your Own Storage\n\nImplement `StorageBackend` to persist credit balances to any store:\n\n```rust\nuse toll_booth::{StorageBackend, DebitResult, StorageError, StoredInvoice, Currency};\n\npub struct MyStorage { /* ... */ }\n\nimpl StorageBackend for MyStorage {\n    fn credit(\u0026self, payment_hash: \u0026str, amount: i64, currency: Currency)\n        -\u003e Result\u003c(), StorageError\u003e;\n\n    fn debit(\u0026self, payment_hash: \u0026str, amount: i64, currency: Currency)\n        -\u003e Result\u003cDebitResult, StorageError\u003e;\n\n    fn balance(\u0026self, payment_hash: \u0026str, currency: Currency)\n        -\u003e Result\u003ci64, StorageError\u003e;\n\n    fn settle_with_credit(\n        \u0026self,\n        payment_hash: \u0026str,\n        amount: i64,\n        settlement_secret: Option\u003c\u0026str\u003e,\n        currency: Currency,\n    ) -\u003e Result\u003cbool, StorageError\u003e;\n\n    fn is_settled(\u0026self, payment_hash: \u0026str) -\u003e Result\u003cbool, StorageError\u003e;\n\n    // ... plus invoice store, pruning, and adjust_credits\n}\n```\n\n`MemoryStorage` is provided for tests and quick prototypes. The `sqlite` feature adds a `SqliteStorage` backend (bundled SQLite, no system dependency).\n\n## Credit model\n\nOn first use of a payment credential, the engine calls `settle_with_credit`, which atomically marks the payment settled and credits the `amount_sats` from the macaroon. Subsequent requests debit from that balance. When the balance drops below the route cost, the engine issues a fresh 402.\n\n`TollBoothEngine::reconcile(payment_hash, actual_cost)` adjusts the balance after the upstream responds if the actual cost differed from the estimated cost.\n\n## Free tier\n\n```rust\nuse toll_booth::FreeTierConfig;\n\nTollBoothConfig {\n    free_tier: Some(FreeTierConfig::Requests(10)), // 10 free requests per IP per day\n    // or:\n    free_tier: Some(FreeTierConfig::Credits(500)),  // 500 free sats per IP per day\n    ..Default::default()\n}\n```\n\nFree-tier checks run after all payment rails are exhausted. IPs are hashed with a daily salt before storage.\n\n## Feature flags\n\n| Feature           | Default | Description                                              |\n|-------------------|---------|----------------------------------------------------------|\n| `l402`            | yes     | L402 payment rail (macaroon + Lightning preimage)        |\n| `axum-middleware` | yes     | Tower `Layer` for axum (`TollBoothLayer`)                |\n| `sqlite`          | yes     | SQLite storage backend (bundled, no system dep)          |\n| `phoenixd`        | no      | Phoenixd Lightning node backend                          |\n\n## Licence\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fforgesworn%2Ftoll-booth-rs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fforgesworn%2Ftoll-booth-rs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fforgesworn%2Ftoll-booth-rs/lists"}