Skip to main content

How L402 Works

This guide explains the technical details of the L402 protocol implementation in Lightning Enable.

Protocol Flow​

┌──────────┐                    ┌─────────────────┐                    ┌─────────────┐
│ Client │ │ Lightning Enable│ │ Provider │
└────┬─────┘ └────────┬────────┘ └──────┬──────┘
│ │ │
│ 1. GET /api/premium/data │ │
│──────────────────────────────────>│ │
│ │ │
│ │ 2. Create Lightning Invoice │
│ │───────────────────────────────────>│
│ │ │
│ │ 3. Invoice + Payment Hash │
│ │<───────────────────────────────────│
│ │ │
│ 4. HTTP 402 Payment Required │ │
│ WWW-Authenticate: L402 │ │
│ macaroon="...", invoice="..." │ │
│<──────────────────────────────────│ │
│ │ │
│ 5. Pay invoice (via any wallet) │ │
│─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─>│
│ │ │
│ 6. Preimage (proof of payment) │ │
│<─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─│
│ │ │
│ 7. GET /api/premium/data │ │
│ Authorization: L402 mac:preim │ │
│──────────────────────────────────>│ │
│ │ │
│ │ 8. Verify SHA256(preimage)==hash │
│ │ Verify macaroon signature │
│ │ │
│ 9. HTTP 200 OK (response) │ │
│<──────────────────────────────────│ │

Provider is the merchant's configured payment provider: Strike (the default), OpenNode, or the merchant's own wallet over Nostr Wallet Connect. The L402 flow is identical either way. Lightning Enable does not hold funds; the payment provider facilitates custody and settlement.

Key Concepts​

1. Lightning Invoice (BOLT11)​

When a client requests a protected endpoint, Lightning Enable creates a Lightning invoice:

lnbc100n1pnxyzabc... (encoded invoice)

The invoice contains:

  • Amount in satoshis
  • Payment hash (SHA256 of a secret preimage)
  • Expiry time
  • Destination (the payment provider's node, or the merchant's wallet on NWC)

2. Payment Hash & Preimage​

The payment hash is the key to L402:

preimage (32 bytes, secret) → SHA256 → payment_hash (32 bytes, public)
  • The payment hash is included in the invoice
  • The preimage is revealed when the invoice is paid
  • Knowing the preimage proves payment was made

3. Macaroon​

A macaroon is a cryptographic bearer token signed with HMAC-SHA256. Lightning Enable embeds a set of caveats (restrictions) into every macaroon at issuance time. These caveats bind the token to the exact context it was created for:

{
"identifier": "lightning-enable:payment_hash:expires",
"caveats": [
"services = lightning-enable:0",
"path = /api/premium/data",
"merchant_id = 42",
"charge_id = abc123-def456",
"amount_sats = 100",
"expires = 1704067200"
],
"signature": "hmac-sha256-signature"
}

Each caveat enforces a specific security constraint:

CaveatPurpose
pathBinds the token to the API path it was issued for. Supports exact match or wildcard prefix (e.g., /l402/proxy/my-api/*).
merchant_idBinds the token to the issuing merchant, preventing cross-tenant token reuse.
amount_satsBinds the token to the price at issuance, preventing reuse at a different price tier.
expiresSets the token expiration as a Unix timestamp (default: 1 hour).
charge_idRecords the payment provider's charge ID for the associated payment.
servicesIdentifies the service name and tier.
methodProxy only, when present: binds the token to one HTTP method.

All caveats are verified on every request. Any unrecognized caveat causes verification to fail (closed-world), so a token can never carry a restriction the server silently ignores.

4. L402 Credential​

The client combines macaroon and preimage:

Authorization: L402 <base64-macaroon>:<hex-preimage>

Lightning Enable also accepts the Payment (MPP) authorization scheme for the same invoice. See Payment (MPP) credentials.

Verification Process​

When Lightning Enable receives an L402 credential, it:

  1. Splits the credential into macaroon and preimage.
  2. Checks that SHA256(preimage) equals the payment hash in the macaroon.
  3. Verifies the macaroon's HMAC signature against the root key.
  4. Checks every caveat: not expired, path matches, merchant matches, price matches, and method matches when bound.

Any failure produces a fresh 402 (see Failed verification below).

Multi-Use Tokens​

A single L402 payment can be used for multiple requests during the token validity period:

  1. Client pays once
  2. Receives preimage
  3. Uses same macaroon:preimage for subsequent requests
  4. Token valid until expiration — configurable per proxy (10 minutes to 24 hours), 1 hour by default

Security Considerations​

Caveat-Based Token Binding​

Macaroon caveats are the primary defense against token misuse. Lightning Enable enforces caveats that prevent three categories of attack:

Path binding (path caveat) -- A token issued for /api/premium/v1 cannot be used to access /api/premium/v2. This prevents clients from paying for a cheap endpoint and reusing the token against an expensive one. Wildcard paths (e.g., /l402/proxy/my-api/*) allow sub-path access when appropriate.

Merchant isolation (merchant_id caveat) -- In Lightning Enable's multi-tenant architecture, each merchant operates independently. The merchant_id caveat prevents a token issued by Merchant A from being replayed against Merchant B's endpoints. This is enforced bidirectionally: if a request carries a merchant context, the token must contain a matching merchant_id, and if a token contains a merchant_id, the request must have a matching merchant context.

Price tier enforcement (amount_sats caveat) -- A token purchased at 10 sats for a demo endpoint cannot be reused against a 100-sat premium endpoint, even if both endpoints share a wildcard path pattern. The server compares the token's amount_sats caveat against the current endpoint's configured price and rejects mismatches.

Unknown caveat rejection -- Any caveat the server does not recognize causes verification to fail. This closed-world approach ensures that if new caveat types are added in the future, older verification logic will not silently skip them.

Preimage Security​

  • Treat preimages like passwords
  • Don't log full preimages
  • Use HTTPS to prevent interception

Macaroon Tampering​

  • Macaroons are signed with HMAC-SHA256
  • Root key must be kept secret (L402_ROOT_KEY environment variable)
  • Any modification invalidates the signature

Token Expiration​

  • Configure appropriate validity periods
  • Shorter = more secure, but more payments needed
  • Longer = better UX, but higher risk if compromised

Rate Limiting​

A paid token is reusable until it expires. If an endpoint is expensive to serve, rate-limit per payment hash in your own API (native mode), or keep the token validity short.

Defaults​

SettingDefaultWho sets it
Invoice expiry10 minutesLightning Enable
Token validity1 hourYou, per proxy (10 minutes to 24 hours)
PricePer proxy, endpoint rule, or challengeYou, in the dashboard or the proxy API

Error Responses​

402 Payment Required (initial challenge)​

{
"error": "Payment Required",
"message": "Pay the Lightning invoice to access this resource",
"l402": {
"macaroon": "AgEL...",
"invoice": "lnbc100n1p3...",
"amount_sats": 100,
"payment_hash": "abc123...",
"expires_at": "2026-07-03T13:00:00Z"
}
}

Failed verification → a fresh 402, never 401/403​

When a presented L402 credential fails verification — malformed credential, preimage/payment-hash mismatch, invalid macaroon signature, expired token, or a caveat violation (wrong path, merchant, or price tier) — Lightning Enable does not return 401 Unauthorized or 403 Forbidden. It re-issues a fresh 402 challenge with a new invoice and macaroon. The failure reason is carried in:

  • the X-L402-Error response header, and
  • the body's message field.
HTTP/1.1 402 Payment Required
WWW-Authenticate: L402 macaroon="AgEL...", invoice="lnbc100n1p3..."
X-L402-Error: Macaroon has expired
{
"error": "Payment Required",
"message": "Macaroon has expired",
"l402": {
"macaroon": "AgEL... (new macaroon)",
"invoice": "lnbc100n1p3... (new invoice)",
"amount_sats": 100,
"payment_hash": "def456...",
"expires_at": "2026-07-03T13:10:00Z"
}
}

Clients should treat every 402 as a (re-)challenge: check X-L402-Error to learn why the previous credential was rejected, then pay the new invoice from the current response. Code that branches on 401/403 for L402 failures will never execute those branches.

Next Steps​