> ## Documentation Index
> Fetch the complete documentation index at: https://shinydapps-bd9fa40b.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# White Paper

> l402-kit — HTTP 402 payment middleware for APIs and AI agents. Bitcoin Lightning, TypeScript · Python · Go · Rust.

# l402-kit White Paper

**Version 1.2 — May 2026**

***

## Abstract

HTTP 402 was reserved in 1996 for a payment mechanism that was never built. For twenty-five years, developers built workarounds — account registration flows, credit card processors, API key provisioning — each designed for human actors who can open a browser and fill out a form. None of them work for machines.

l402-kit implements the L402 protocol: HTTP 402 Payment Required over the Bitcoin Lightning Network. An API caller, human or machine, pays a Lightning invoice and receives cryptographic proof of payment. The server verifies proof with a single hash comparison. No account. No API key. No human approval required.

**l402-kit is a family of L402 protocol implementations in TypeScript, Python, Go, and Rust. Open-source, custody-free, account-free. Each implementation does exactly what the protocol asks of it, and nothing more.**

***

## The Problem

HTTP was designed for human interactions: browsers, forms, sessions, accounts. API monetization inherited these assumptions and built workarounds around them. Stripe's minimum transaction is \$0.50 after fees. PayPal requires accounts on both sides. Monthly subscriptions bundle demand that is not bundled in reality. API keys require human provisioning, rotation, and billing cycles that cannot be automated.

The gap became critical with the emergence of autonomous AI agents. An agent that discovers a new API at runtime cannot create an account, enter a card number, or navigate an OAuth flow. It can only make HTTP requests. If the API requires a pre-existing credential, the agent stops. The loop that was supposed to be autonomous is not.

What was missing for twenty-five years is now implementable: a payment mechanism native to HTTP, requiring no prior relationship between client and server, settling in under a second, and producing a self-contained cryptographic proof the server verifies without a network call.

***

## How l402-kit Works

The protocol is a standard HTTP exchange with one additional round trip:

```mermaid theme={null}
sequenceDiagram
    participant C as Client / Agent
    participant M as l402-kit Middleware
    participant L as Lightning Network
    C->>M: GET /api/endpoint
    M-->>C: 402 + BOLT11 invoice + macaroon
    C->>L: Pay invoice (satoshis)
    L-->>C: Preimage (proof of payment)
    C->>M: GET /api/endpoint<br/>Authorization: L402 macaroon:preimage
    M->>M: SHA256(preimage) == paymentHash ✓
    M-->>C: 200 OK + data
```

1. **Request.** Client sends a normal HTTP request.
2. **Challenge.** Server responds with 402, a Lightning invoice, and a macaroon encoding the payment hash.
3. **Payment.** Client pays the invoice. The Lightning Network delivers the preimage as settlement proof in under one second.
4. **Access.** Client resends with `Authorization: L402 <macaroon>:<preimage>`. Server verifies `SHA256(preimage) == paymentHash`. No database lookup — pure cryptography.

The credential is stateless: it carries the payment hash and expiry inline and is verifiable by any instance of the middleware without coordination.

***

## Architecture

l402-kit operates across three tiers. The operator's application is unchanged; the middleware wraps routes. The Lightning provider is pluggable.

```mermaid theme={null}
graph TD
    A["Operator's Application<br/>Express · FastAPI · net/http · axum"] -->|middleware wraps route| B
    B["l402-kit Middleware<br/>TypeScript · Python · Go · Rust"]
    B -->|invoice creation| C["Lightning Service Provider<br/>Blink · OpenNode · LNbits · Alby · LND · CLN"]
    B -->|replay check| D["Replay Adapter<br/>Memory · Redis · Database"]
```

**Managed mode** — operator provides a Lightning Address. ShinyDapps backend handles invoice creation and settlement. Fee: 0.3%.

**Sovereign mode** — operator uses their own Lightning provider. Fee: 0%.

***

## Quickstart

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { l402, ManagedProvider } from "l402-kit";

  const lightning = ManagedProvider.fromAddress("you@blink.sv");
  app.use("/api/data", l402({ priceSats: 10, lightning }));
  ```

  ```python Python theme={null}
  from l402kit import l402_required, ManagedProvider

  lightning = ManagedProvider.from_address("you@blink.sv")

  @app.get("/api/data")
  @l402_required(price_sats=10, lightning=lightning)
  async def data(): ...
  ```

  ```go Go theme={null}
  provider := l402kit.NewManagedProvider("you@blink.sv")
  http.Handle("/api/data", l402kit.Middleware(l402kit.Options{
      PriceSats: 10, Lightning: provider,
  }, handler))
  ```

  ```rust Rust theme={null}
  let provider = ManagedProvider::from_address("you@blink.sv");
  let app = Router::new()
      .route("/api/data", get(data_handler))
      .layer(L402Layer::new(provider, 10));
  ```
</CodeGroup>

***

## The Seven Principles

These principles are constraints. A feature that violates them does not ship.

| # | Principle                                    | In one line                                                                               |
| - | -------------------------------------------- | ----------------------------------------------------------------------------------------- |
| 1 | **Minimal essence**                          | The middleware does the protocol, and nothing else.                                       |
| 2 | **Auditability as a precondition for trust** | Closed-source financial middleware is a contradiction in terms.                           |
| 3 | **Operator sovereignty**                     | The operator holds the keys, chooses the provider, keeps the ledger.                      |
| 4 | **Truth as correspondence**                  | What the docs state and what the code does are the same.                                  |
| 5 | **Stability at the foundation**              | HTTP and Lightning are long-lived. The middleware connecting them is treated accordingly. |
| 6 | **Composition, not construction**            | l402-kit composes existing primitives; it does not reinvent them.                         |
| 7 | **Adequacy to the nature of the problem**    | Machine-to-machine payments require a solution built for machines.                        |

***

## Two Users. One Protocol.

> *"l402-kit is neutral infrastructure — it serves the human who wants to exit the banking system and the agent that never needed one."*

The sovereign operator monetizes their API without Stripe, without KYC, without intermediary. Sats arrive directly in their wallet. `onEvent` is opt-in — they never touch it.

The autonomous agent operates without a human in the loop. Same protocol. Same three lines of code. But now with persistent identity, cryptographic audit trail, and emergent reputation — because without reputation, other agents won't trust it.

Different markets. Same protocol. The code is the same.

***

## The Autonomous Agent Economy

HTTP was built for humans. L402 was built for machines. But there is a deeper implication that only becomes visible when you follow the protocol to its conclusion.

An AI agent that operates inside the L402 protocol does not merely *consume* APIs. It can *produce* services, accumulate the proceeds, and use those proceeds to consume other services — without a human ever depositing a single satoshi.

The loop is complete:

```mermaid theme={null}
sequenceDiagram
    participant W as World (other agents / humans)
    participant A as Autonomous Agent
    participant L as Lightning Network
    participant R as LAW-N Reputation Ledger

    W->>A: calls agent's API (pays sats)
    A->>L: receives payment — saldo cresce
    A->>W: calls external API (pays sats from balance)
    L->>A: preimage (proof of payment)
    A->>R: CloudEvent emitted (HMAC-signed)
    R->>R: behavioral pattern recorded
    Note over R: reputação emerge — sem humano decidir
```

**Step 1 — Birth.** The agent creates a Lightning wallet. Alby and LNbits are free, require no document, no bank account, no KYC. The agent has an address in seconds.

**Step 2 — Produce.** The agent offers a service — text summarization, embeddings, data queries, compute tasks. It wraps that service with `l402-kit` middleware. Any caller pays automatically. The agent accumulates sats.

**Step 3 — Consume.** With accumulated sats, the agent calls other L402-protected services using `L402Client`. It pays invoices, receives data, expands its capabilities. No human approves the transaction.

**Step 4 — Audit trail.** Each transaction emits a signed CloudEvent (CloudEvents 1.0, HMAC-SHA256) carrying: agent identity, session, request causality, payment proof, timing, and behavioral context. The record is cryptographic — not a log, but a proof.

**Step 5 — Reputation emerges.** Behavioral patterns accumulate in the LAW-N ledger (SAGEWORKS AI). Agents that pay consistently, respect budget constraints, and do not attempt proof reuse build reputation automatically — without any authority granting it. Agents that misbehave stop being able to access services. The system is self-regulating.

No human approved the agent's wallet. No human funded its first transaction. No human decided its reputation. The economic infrastructure is the protocol itself.

### What this is not

This is not a blockchain. There is no token. There is no DAO. There is no governance vote. There is no whitelist.

There is HTTP, Bitcoin Lightning, and cryptographic proof. The agent economy runs on infrastructure that existed before l402-kit — l402-kit is the missing protocol layer that makes it composable.

### Why this matters now

Three things became true simultaneously in 2025–2026:

1. **Autonomous agents are real.** LangChain, AutoGPT, Claude, and dozens of frameworks deploy agents that execute multi-step tasks without human approval at each step.
2. **Lightning wallets are free.** Any software process can hold a Lightning address. No bank. No KYC. No minimum balance.
3. **L402 is implemented.** l402-kit runs in TypeScript, Python, Go, and Rust — the four languages where agents are built.

The convergence is not theoretical. The infrastructure exists. What was missing was the protocol layer connecting them. That is l402-kit.

> *"l402-kit is not a payment gateway. It is the economic infrastructure for autonomous agents — the layer that makes machine-to-machine commerce possible without human intermediaries."*

***

## Economic Model

The 0.3% fee is structurally aligned with developer success: when a developer earns nothing, the fee is zero.

| Tier        | Cost                                | What You Get                               |
| ----------- | ----------------------------------- | ------------------------------------------ |
| **Free**    | 0.3% of payments received           | Unlimited calls, all SDKs, 7-day history   |
| **Pro**     | ~~9,000 sats/month (~~\$9)          | Full history, CSV export, priority support |
| **Founder** | ~~1,000,000 sats one-time (~~\$999) | Lifetime Pro, direct maintainer access     |

***

## Adoption

```bash theme={null}
npm install l402-kit    # TypeScript
pip install l402kit     # Python
go get github.com/shinydapps/l402-kit/go@v1.10.0
cargo add l402kit       # Rust
```

<Note>
  For the complete technical specification — founding principles in full, design decisions with tradeoffs, expanded threat model, architectural properties, L402 vs x402 comparison, and versioning commitments — the **Extended Edition** is available at [l402kit.com/whitepaper-extended](/whitepaper-extended) (100 sats, served by l402-kit itself).
</Note>

***

*l402-kit is released under the MIT License · ShinyDapps · [thiagoyoshiaki@gmail.com](mailto:thiagoyoshiaki@gmail.com)*
