L402 is an open protocol that lets any HTTP server demand a Lightning Network payment in exchange for access to a resource. It joins the long-unused HTTP 402 Payment Required status code with bearer-token authentication, producing a flow that scripts, APIs, and autonomous agents can complete without a human in the loop. If you have wanted an API that bills per request, a paywall with no account, or a way to let a programmatic client buy data on the fly, L402 is the wire format that makes it practical.
This is the pillar reference for L402 on Lightning Faucet. It covers where the protocol came from, how the request/response cycle works, what a server and client each need to ship, and when L402 is the right tool versus when something else fits better. For working code, /build/ hosts an L402 gateway and sample integrations.
A 30-second definition
L402 stands for Lightning HTTP 402. The protocol defines:
- A server response that bundles a Lightning invoice (asking for sats) with a macaroon (an authenticated bearer credential scoped to the request).
- A client flow that pays the invoice off-band through any Lightning wallet, captures the preimage (a 32-byte secret revealed on settlement), and re-sends the original request with
Authorization: L402 <macaroon>:<preimage>. - A server verification step that checks the macaroon's HMAC, hashes the preimage against the invoice's payment hash, and enforces any caveats.
That is the whole protocol. No accounts, no API keys, no chargebacks, no card networks — anyone who can pay a Lightning invoice can authenticate against an L402-protected endpoint.
Why HTTP 402 sat unused for so long
When HTTP/1.1 was drafted, the working group reserved status code 402 Payment Required "for future use." Three decades passed without consensus on what that future should look like. Card rails were not designed for browser-native per-request billing; PayPal-style flows required a redirect; subscription paywalls grew up around session cookies and OAuth. The 402 code stayed in the spec as a placeholder.
Bitcoin's Lightning Network changed the cost surface. Once a payment can clear in under a second and settle for fractions of a cent, sub-dollar pricing per HTTP request becomes economically real. Lightning Labs published the first concrete proposal for an HTTP-402 authentication scheme — originally called LSAT, later renamed L402 — and independent implementations have appeared across multiple languages.
The two halves: macaroons and Lightning preimages
Macaroons
A macaroon is an authenticated credential invented at Google. It looks like an opaque string but carries:
- A root identifier the issuer uses to look up which secret key signed it.
- Zero or more caveats — constraints that narrow the credential's authority. A caveat might say "only valid until timestamp X," "only for endpoint /api/v1/forecast," or "capped at 60 calls."
- A chain of HMACs that bind each caveat to the previous one, so a holder can attenuate the macaroon further but cannot remove constraints.
For L402, the macaroon is the server's way of saying "here is a credential that will work if the matching payment has been made." Caveats let the server scope access without keeping any record of who paid.
Lightning invoices and preimages
A Lightning invoice contains a payment_hash: a SHA-256 digest of a 32-byte secret known only to the recipient. As a payment routes through the network, each hop locks funds on the condition that the next hop reveals the secret. Once the final recipient releases the preimage, the entire path settles atomically.
The preimage is therefore both a settlement proof and a receipt. L402 takes advantage of this: the server embeds the invoice's payment hash inside the macaroon's identifier, the client pays and captures the preimage, and the server hashes the preimage to confirm payment.
The L402 request/response cycle
Here is a complete exchange with an L402-protected endpoint.
Step 1: Unauthenticated request
GET /api/forecast/london HTTP/1.1
Host: weather.example.com
Step 2: Server returns 402 with payment challenge
HTTP/1.1 402 Payment Required
WWW-Authenticate: L402 macaroon="AGIAJEem...", invoice="lnbc100n1p3hk5plpp5ej..."
Content-Type: application/json
{"price_msat": 10000, "currency": "BTC"}
The macaroon and BOLT-11 invoice are base64-encoded in the WWW-Authenticate header. Any wallet can decode and pay the invoice.
Step 3: Client pays the invoice
The client routes the invoice through its Lightning wallet (LND, CLN, Eclair, LDK, or any custodial wallet exposing a "pay invoice" function). On success the wallet returns the 32-byte preimage.
Step 4: Authenticated retry
GET /api/forecast/london HTTP/1.1
Host: weather.example.com
Authorization: L402 AGIAJEem...:1234abcd5678ef...
The format is Authorization: L402 <base64-macaroon>:<hex-preimage>.
Step 5: Server validates and serves
The server decodes the macaroon, verifies the HMAC chain, checks the caveats (expiry, endpoint scope, rate caps), hashes the preimage, and confirms it matches the payment hash embedded in the macaroon. If everything lines up, the resource is served.
The macaroon remains reusable for as long as its caveats permit. A macaroon with no expiry is a permanent credential for the scope it covers; one bound to a nonce can be a single-use token. The server sets the policy.
When L402 is the right fit
Per-request API billing
If you sell access to an API, L402 lets you price each call individually — 10 sats per inference, 1 sat per lookup, 50 sats per generated image. There are no minimum top-ups and no monthly invoices. New customers integrate by reading the 402 response, paying, and retrying.
Programmable agent commerce
Autonomous agents — research assistants, trading bots, scrapers with budgets — need a way to spend money without human approval at every step. L402 gives them one, because the entire transaction is machine-readable. An agent holding a Lightning wallet can encounter a 402, decide whether the price is worth paying, pay, and continue. No browser, no CAPTCHA, no card-on-file.
Anonymous, account-free paywalls
Some publishers want readers to pay per article without signing up. L402 supports this natively: each article is an endpoint, each request is an invoice, and the macaroon is the only "session" required.
Tiered or scoped access tokens
Because macaroons support caveats, you can sell tokens with custom scopes baked in. A single payment can yield a macaroon valid for 24 hours, capped at 1,000 requests, restricted to one subdomain. The buyer cannot widen those caveats; only the issuer can.
When L402 is not the right fit
Skip L402 when:
- Your users are mainstream consumers on phones who trust card networks. A card button outperforms a Lightning invoice for everyday SaaS in most regions. Use L402 alongside cards, not instead.
- Your transactions are above a few dollars. Card refunds, dispute resolution, and chargebacks have real value that a one-way Lightning payment cannot replicate. L402 fits micro and small payments best.
- You need full subscription billing semantics. L402 has no built-in "renew on the 15th." You can build it on top, but dunning, prorations, and tax forms are someone else's problem.
- You have no Lightning component in your stack. L402 servers need to issue real invoices and verify real preimages. A custodian (Voltage, LNbits, Lightning Faucet's gateway) is the fastest on-ramp.
How L402 compares to similar protocols
Plain BOLT-11 invoices
You can charge for an API by returning a bare invoice and trusting the caller to retry after payment. The problem is binding: anyone who sees the invoice can pay it and impersonate the caller. L402 fixes this with the macaroon — the credential is the binding, and the server stores no per-invoice state.
LNURL-pay and Lightning Address
These shine for "tip me" or "deposit to my account" flows where amounts vary and the goal is to receive money. They are not designed to gate a resource behind a specific payment. L402 fills that gap.
Stripe-style API keys with usage billing
Conventional metered APIs need an account, a card on file, and a key. L402 collapses all of that into a single HTTP round trip. If your customers already have accounts, the conventional flow is simpler. If they do not, L402 lets you skip onboarding entirely.
x402
x402 is a more recent proposal, championed by Coinbase, that reuses HTTP 402 but settles in stablecoins (USDC) on EVM-compatible chains. It targets the same machine-to-machine use case as L402 while trading Lightning's sub-second finality and account-free model for stablecoin and EVM tooling. The two are not mutually exclusive — a server can advertise both rails.
What a minimal L402 server needs
A Lightning node or custodial integration
The server must create invoices on demand and detect their settlement (or look them up by payment hash) to confirm payment. Common choices:
- LND with the
lnrpcinterface — the original reference implementation. - Core Lightning (CLN) with the
invoiceandwaitinvoiceRPCs. - Eclair with its HTTP API.
- LDK for embedded builds.
- Custodial APIs (Voltage, Greenlight, LNbits, Lightning Faucet's gateway) for teams that do not run a node.
A macaroon library
Macaroons are not Lightning-specific, and solid libraries exist in Go, Python, Rust, JavaScript, and most languages with cryptographic primitives. You need to mint a macaroon with a payment-hash identifier plus at least one caveat, and to verify presented macaroons against a root key.
An HTTP middleware
The middleware itself is small. Pseudocode:
def l402_protect(handler, price_sats):
def wrapped(request):
auth = request.headers.get("Authorization", "")
if not auth.startswith("L402 "):
return challenge(request, price_sats)
macaroon_b64, preimage_hex = auth[5:].split(":", 1)
macaroon = b64decode(macaroon_b64)
if not verify_macaroon(macaroon, ROOT_KEY): return 401("invalid macaroon")
if not check_caveats(macaroon, request): return 401("caveat violation")
if sha256(unhexlify(preimage_hex)) != payment_hash_of(macaroon):
return 401("preimage mismatch")
return handler(request)
return wrapped
def challenge(request, price_sats):
invoice, payment_hash = lightning.create_invoice(price_sats * 1000)
macaroon = mint_macaroon(ROOT_KEY, payment_hash, caveats=default_caveats(request))
return 402(headers={"WWW-Authenticate": f'L402 macaroon="{b64(macaroon)}", invoice="{invoice}"'})
Everything else is policy: caveat choice, pricing, reuse rules, and node integration.
What a minimal L402 client needs
- The ability to make an HTTP request and parse a
402response withWWW-Authenticate: L402. - A Lightning wallet that can pay a BOLT-11 invoice and return the preimage. For production agents, holding a balance with a custodian and calling its REST API is the simplest path.
- The ability to format
Authorization: L402 <macaroon>:<preimage>and retry.
Open-source clients exist for Go, Python, TypeScript, and Rust. If you are building an agent, wrap the L402 round trip with budget controls so a runaway loop cannot drain your wallet.
Security considerations and common pitfalls
Treat the macaroon as a bearer credential
Anyone who holds the macaroon and matching preimage can authenticate. Transmit over TLS only, and scope the macaroon tightly with caveats so a leaked credential has limited blast radius. Short expiries and per-IP caveats help.
Replay protection
A macaroon-plus-preimage pair is replayable by default — by design, since reuse is often desirable. For one-shot tokens, embed a nonce in the macaroon and reject duplicates. Keep the nonce store small with a short expiry caveat.
Pricing and griefing
Servers that issue too many free invoices can be griefed by clients that request 402s and never pay, holding HTLCs open in the meantime. Use small invoice expiries (60–120 seconds is typical) and cap the rate at which a single source IP can request new challenges.
Privacy
L402 itself reveals little. The server learns that someone paid; the macaroon is opaque; the preimage proves payment but identifies nothing. If you embed identifying caveats — user IDs, IP addresses — you reintroduce the privacy properties of conventional auth. Choose caveats accordingly.
Custody assumptions
Using a custodial wallet on either side inherits that custodian's trust model. A censoring custodian can refuse to pay an invoice or refuse to release a preimage. For high-assurance use cases, run your own node.
How Lightning Faucet uses L402
Lightning Faucet is a Bitcoin and Lightning faucet with games, earn surfaces, prediction markets, and builder tools. L402 shows up in several places:
- The builder hub at /build/ exposes an L402-protected MCP server. Developers building agent tooling can call it with Lightning payments and no signup.
- The earn surfaces at /earn/ run on the same rails. Sats earned by completing tasks can be spent immediately against L402 paywalls elsewhere.
- The faucet's multiplayer poker tables and prediction markets settle in sats — sat-denominated entertainment that pairs naturally with programmatic Lightning payments.
- The free spin and other casino games round out a complete Lightning sandbox: a place to acquire sats, a place to spend them, and an L402-gated API for builders to plug into.
Frequently asked questions
What does L402 stand for?
L402 stands for Lightning HTTP 402. The "L" is Lightning Network and "402" is the HTTP status code for "Payment Required" that the protocol finally puts to use.
Is L402 the same as LSAT?
Yes. LSAT (Lightning Service Authentication Token) was the original name introduced by Lightning Labs. It was renamed L402 to emphasize that the spec is an HTTP-level standard, not tied to a specific service. The wire format is identical.
Do I need to run my own Lightning node to use L402?
No. Custodial Lightning wallets and API providers can issue invoices and verify payments on your behalf. Running your own node gives stronger trust assumptions and lower operating costs at scale, but a custodian is a fine starting point.
Is L402 anonymous?
The protocol itself requires no identifying information. The server learns that someone paid; the preimage and macaroon reveal nothing about who. You can deliberately add identity to caveats, but the default is account-free.
How does L402 compare to x402?
Both use HTTP 402 for machine-to-machine payments. L402 settles in sats on the Lightning Network with sub-second finality and no accounts. x402 settles in stablecoins (USDC) on EVM chains and trades Lightning's properties for stablecoin and EVM tooling familiarity. A server can support both.
Is L402 production-ready?
Yes. Multiple independent implementations have run in production for years, gating paid APIs from research datasets to AI inference services. The protocol layer is stable; the main practical limits are your choice of node software and custodian.
Where to go next
If you want to ship L402 in something you are building, start at /build/ for working code and an L402-gated MCP endpoint you can call directly.
If you want sats to test against, the free spin and earn surfaces fund a small Lightning balance at no cost.
L402 is small enough to fit on a postcard and expressive enough to power a new kind of internet economy. Once you have shipped it once, you will see places for it everywhere.
— Lightning Faucet team