# L402 Protocol (Lightning Paywalls) Load whenever a user asks about paying for an API or piece of content via Lightning, mentions L402 / LSAT, or wants an agent to access a paywalled endpoint. L402 (formerly LSAT) is a protocol for monetizing APIs and content using Lightning payments. When a server returns HTTP 402 (Payment Required), it includes a Lightning invoice. Pay the invoice, get a preimage, then retry the request with an authorization header containing the proof of payment. ## How L402 Works 1. **Request** → Client fetches protected URL. 2. **402 Response** → Server returns invoice + macaroon (see challenge formats below). 3. **Pay Invoice** → Client pays Lightning invoice, receives preimage. 4. **Retry with Auth** → Client retries with `Authorization: L402 :`. 5. **200 Response** → Server returns protected content. **Challenge formats:** the spec-compliant way is via the `WWW-Authenticate` header (e.g. `WWW-Authenticate: L402 macaroon="...", invoice="..."`), used by aperture-based servers. The credential field may be named `macaroon="..."` **or** `token="..."` — the current L402 spec uses `token`, so lightningfaucet sends `L402 version="0", token="...", invoice="..."`. Some services instead return the challenge as a JSON body (`{invoice, macaroon}` or `{invoice, token}`). Extract each field **by name** (header first, body fallback); a fixed `split('L402 macaroon="')` silently misses the `token=` form. ## Implementation: `agent.fetchL402` Call the wrapper. A hand-rolled flow (fetch, pay the challenge's invoice, fetch again with the pass) loses a paid pass on any failure after paying, and the natural retry buys a second one; everything below is what `fetchL402` does instead. `scripts/l402-paywalls.js` is the runnable version (`npm run example:l402`, preview only; `-- --pay` to buy). ```javascript import "dotenv/config"; // your app loads its own .env; the package doesn't import { loadMnemonicFromEnv } from "sparkbtcbot-skill"; import { SparkAgent } from "sparkbtcbot-skill/agent"; const mnemonic = await loadMnemonicFromEnv(); // reads SPARK_PASSPHRASE // Pays, then exits: a one-shot, so optimizeLeaves: false (references/wallet.md → Cleanup). const { agent } = await SparkAgent.create(mnemonic, "MAINNET", { optimizeLeaves: false }); const preview = await agent.previewL402("https://api.example.com/paid-endpoint"); console.log("Cost:", preview.amountSats, "sats", "| token valid until:", preview.tokenExpiresAt ?? "not stated"); // Always pass the price ceiling you agreed to (the default is 10,000 sats); the fee cap is sized to the invoice. const result = await agent.fetchL402("https://api.example.com/paid-endpoint", { maxAmountSats: preview.amountSats }); console.log("Paid:", result.paid, "Status:", result.status, "Data:", result.data); await agent.cleanup(); ``` Before paying, `fetchL402` reads the expiry the server signed into its token and refuses one that is already dead or dies within 120 seconds. The error has code `L402_TOKEN_EXPIRED`, and nothing is paid. The invoice expires separately, so without this check an expired pass can still be paid for, and then refused. It reads aperture's `_valid_until`, a plain `valid_until`, and lightningfaucet's JSON `expiry`. A token it cannot read is not blocked. Passes can be short: lightningfaucet's live for about ten minutes. A refusal before paying costs nothing, and its code says why: a service that can't be reached is `SERVICE_UNAVAILABLE` (`retryable: "yes"` for a GET, `"no"` for a POST or PATCH, which the service may have received), a 402 without a readable challenge is `L402_CHALLENGE_INVALID`, and a price over `maxAmountSats` is `AMOUNT_OVER_LIMIT`: check it with `agent.previewL402(url)` and ask the user. If the resource does not arrive after `fetchL402` has paid, it never fetches a fresh challenge, because the money is already gone. That covers a dropped connection, a 5xx, a 408 or 429, a body cut off mid-read, or a body that is not the JSON its header claims. It presents the same pass up to three times for a GET, HEAD, OPTIONS, PUT or DELETE. A POST or PATCH is sent once, since repeating it could run the action again. If every attempt fails, it keeps the pass and throws `PAYMENT_COMMITTED` with `settled: true`. Calling `fetchL402` with the same method and URL again **in that process or a new one** presents the kept pass and returns `{ paid: false, recovered: true, ... }` without paying; for a POST or PATCH it does that only with `{ resend: true }` and the same body, because the service may already have acted on the first one, so check with the service first. `resend` sends the original request again; a different body is refused. The pass is held from the moment it is paid for, before the first delivery attempt, so even an error nobody planned for leaves the next call presenting it. A second call for the same method and URL while the first is still running (a duplicated tool call, or a retry after a host timeout) joins the running call and gets its result or its error, with `paid: false, joined: true`, instead of buying again; with a different body it is refused with `CONCURRENT_PAYMENT_ATTEMPT` and pays nothing. Nothing is written to disk and the pass never rides on the error. **Holds are saved on disk, so they survive the process.** A chat agent often runs each tool call as a new `node` process; held in memory only, the next call fetched a new challenge, with a new invoice the dedup store can't recognize, and bought again. Each hold is a file in `~/.spark/l402-holds/` (`SPARK_L402_HOLDS_PATH`), named by a hash of the method and URL. It holds the state, host and path, the invoice, the macaroon, the price and caps, and the send's id. It never holds the preimage, which a new process reads back from Spark by the send's id, and never the query string, which can carry keys. `fetchL402` claims the file before paying, so a second process buying the same request pays nothing: it waits for the first, up to 90 seconds, then throws `CONCURRENT_PAYMENT_ATTEMPT`, which says what happened. With `reason: "L402_BOUGHT_ELSEWHERE"` the other process bought it and kept the result, so calling again is a second purchase. If the other purchase is held, calling again finishes it without paying. Otherwise the other process is still buying. A process that dies mid-purchase leaves its invoice behind, and the next call settles that invoice through the dedup store instead of buying another. A claim whose process is gone, or that is over ten minutes old, is finished that way. The file goes once the resource is delivered, the payment is proven failed with its sats back, or `forgetL402` lifts it on the user's say-so; a file that can't be read refuses the purchase (`L402_HOLD_UNREADABLE`). `status().l402.held` lists them. A malformed JSON body after payment comes back as text instead of throwing. A payment that may have gone through, or is still pending when `payAndSettle` gives up, is held the same way. The next call settles that same invoice through the dedup store (with `SPARK_LN_DEDUP=off` it refuses and says to check `agent.getTransfers()`), or checks the send's status, and delivers once the proof arrives. While the payment may have gone through it is `PAYMENT_COMMITTED`; settling it again doesn't count against the spend budget a second time, and its errors say "Nothing new was paid". A first call refused before sending anything, because an earlier payment of that invoice was still open (`reason: "EARLIER_ATTEMPT_OPEN"`), is held the same way with nothing counted: the call that settles it makes the real payment, checked and counted by the budget like any other, and returns `paid: true` with `recovered: true`. If the budget has no room then, it throws `SPEND_BUDGET_EXCEEDED` and the purchase stays held. A payment that failed for good, on the first call or while settling a held one, throws `LIGHTNING_PAYMENT_FAILED`. With the sats back (`USER_SWAP_RETURNED`, `retryable: "yes"`) nothing is held and the next call buys afresh. Otherwise the sats may still be locked to the SSP, so it is `check-first` and stays held on the send's id: the next call reads that send instead of paying a fresh invoice, and buys afresh on its own only once the send reads `USER_SWAP_RETURNED`. The SSP can leave a refunded send at `LIGHTNING_PAYMENT_FAILED`, so if the hold outlasts the locked sats (`getBalance().lockedSats` no longer holds them), lift it with `forgetL402` on the user's say-so. Settling a held invoice needs the balance for its price again, because the SDK picks the coins before the operators refuse a second payment: if the first payment drained the wallet, the retry keeps saying "again later" until the wallet holds the price again. Four outcomes stop the purchase for good, each a `PAYMENT_COMMITTED` with a `reason`: - **`L402_PASS_REFUSED`** (`settled: true`, with `status`, `invoiceHash` and `amountSats`): a 401, 402 or 403 after paying. The service refused a pass it was paid for, and its body may carry a new challenge, which must not be paid automatically. The invoice hash identifies the payment when taking it up with the service. - **`L402_PASS_EXPIRED`** (`settled: null`): the token died before a doubtful payment could be settled. Settling it then could buy a dead pass, so nothing is paid. - **`L402_INVOICE_EXPIRED`** (`settled: null`): the invoice expired before a doubtful payment could be settled again, so settling can't tell whether it went through. Check `agent.getTransfers()`. - **`L402_NO_PROOF`** (`settled: null`): the payment ended where the service may have been paid but no proof came back (`PREIMAGE_PROVIDING_FAILED`), or with a preimage that doesn't prove the invoice. After any of these, the same call throws the same error without a request or a payment, and the error names the call that lifts it: `agent.forgetL402(url)` for a GET, `agent.forgetL402(url, { method: "POST" })` for a POST. The next call is then a new purchase (a second one if the first went through), so call it only when the user says to. Nothing held, block or unresolved purchase, is ever dropped to make room: at 1,000 unresolved purchases in one process, `fetchL402` refuses to start a new one (`L402_TOO_MANY_HELD`, nothing paid; `err.held` lists them by method, host and path) until some are resolved or forgotten. Results carry `status`. **What a paid pass's answer does to the hold:** | Answer after paying | What `fetchL402` does | Calling again | |---|---|---| | 2xx, and any other status not listed here (400, 404, 410, 422…) | Returns it with `status`, and releases the pass | **Buys again** | | 5xx, 408, 409, 423, 425, 429 | Retries with the same pass (a GET; a POST is sent once), then holds it and throws `PAYMENT_COMMITTED` | Presents the same pass, pays nothing | | 401, 402, 403 | Blocks the URL (`L402_PASS_REFUSED`) | Same error, pays nothing | | A redirect to the same origin | Follows it with the pass (a trailing-slash redirect; a 303 after a POST becomes a GET) | — | | A redirect to another https host | Follows it with no pass, none of your headers and no body (a signed download link). A 401, 402 or 403 from that host is a failed attempt, retried from the service's own URL | — | | A redirect to plain http, one that would send a POST body to another host, or more than 5 | Stops: holds the pass and throws `PAYMENT_COMMITTED` naming `err.location` | Presents the same pass, pays nothing | **Before paying, no redirect is followed.** The challenge that gets paid must come from the URL you gave: a hop could supply the invoice, and a payment made off a hop to another host is refused at delivery. `fetchL402` and `previewL402` throw `SERVICE_REDIRECTED` (`retryable: "no"`, nothing paid) with `err.location`. Tell the user where it pointed, and call again with that URL only if it is the same service over https and they agree. So read `status` before calling again: a returned 404 is paid for, and a retry is a second purchase. To ask again, reuse the pass (`result.macaroon`, `result.preimage`) as the cache below does, or tell the user what the service answered. ## Token Caching L402 tokens (macaroon + preimage) can typically be reused for multiple requests to the same domain until they expire. Without caching, every request triggers a new 402 challenge and a new payment — the server won't tell you that you already paid. `agent.fetchL402` does not cache, so wrap it: try the cached token first, and pay through the wrapper only when the server refuses it. The re-payment then carries the same amount ceiling, fee cap and budget as the first one. ```javascript // https origin → "L402 :". A bearer credential: never log it. const tokenCache = new Map(); async function fetchL402Cached(agent, url, options = {}) { const { method = "GET", headers = {}, body } = options; const { protocol, origin } = new URL(url); // Keyed by origin and https only: a pass bought over https must never ride a // plain http:// request to the same host. if (protocol !== "https:") throw new Error(`refusing to send an L402 pass over ${protocol}//`); const cached = tokenCache.get(origin); if (cached) { const response = await fetch(url, { method, // Authorization last, so a caller header cannot clobber the credential. headers: { "Content-Type": "application/json", ...headers, Authorization: cached }, body: body ? JSON.stringify(body) : undefined, // Not followed: fetch would forward your headers, and a POST body, to // wherever the service points. A redirect is handed back as the answer. redirect: "manual", }); if (response.status >= 300 && response.status < 400) { return { paid: false, cached: true, status: response.status, location: response.headers.get("location") }; } if (response.status !== 402 && response.status !== 401) { const ct = response.headers.get("content-type") || ""; const data = ct.includes("json") ? await response.json() : await response.text(); return { paid: false, cached: true, data }; } tokenCache.delete(origin); // expired or rejected: pay again } const result = await agent.fetchL402(url, options); // Cache a recovered pass too (paid: false, recovered: true): an earlier call // bought it, and not caching it meant the next request bought another. if (result.paid || result.recovered) tokenCache.set(origin, `L402 ${result.macaroon}:${result.preimage}`); return result; } ``` ## The protocol, for reading only **A sketch of the exchange, not code to copy:** it handles no failure after paying, and every such failure here (a cut or non-JSON body, a refused pass, no preimage yet) would lose the pass and invite a second purchase. `agent.fetchL402` is the implementation. ```javascript const challenge = await fetch(url); // 402, with WWW-Authenticate: L402 macaroon="…", invoice="lnbc…" const { macaroon, invoice } = parseChallenge(challenge); // header first, JSON body as a fallback const { paymentPreimage } = await pay(invoice); // the preimage is the proof of payment const res = await fetch(url, { headers: { Authorization: `L402 ${macaroon}:${paymentPreimage}` } }); ``` ## Required Dependency Nothing beyond `sparkbtcbot-skill`: `fetchL402` and `previewL402` decode the invoice with `light-bolt11-decoder`, which the package pins in its own dependencies. ## Finding L402 services (verified 2026-09-16; Satring re-verified 2026-09-26) There is no single L402 marketplace. Two community directories are live and worth querying by the user's *need* rather than reciting rows from this table; both are independent projects (not Lightning Labs), so re-verify before promising a listing. | Directory | What it is | How to query | |---|---|---| | **Satring** — `https://satring.com/api/v1/` | Curated paid-API directory: 848 services indexed, 478 live (its homepage, 2026-09-26), across L402, x402 (USDC on Base) and MPP. Per service: protocol, `pricing_sats`, rating, `domain_verified`, 30-day hits, categories. Free tier: **5 summaries per IP per day**, and summaries carry **no URL**. | Free: `GET https://satring.com/api/v1/services?status=live&protocol=L402&page=1&page_size=20` (20 is the maximum) or `/api/v1/search?q=&protocol=L402`. URLs cost money: see [Using Satring](#using-satring). `satring-mcp` exists for MCP clients. | | **402 Index** — `https://402index.io/` | The wider protocol-agnostic index: ~109k endpoints, of which **177 verified L402** (the rest are mostly x402/USDC, plus MPP). | Via its MCP `search_services` tool; no public JSON endpoint found. List it as "the bigger index, small L402 slice", not as the default. | ### Using Satring Free calls return summaries without URLs, so an agent cannot reach a listed service without paying Satring first. The paid endpoints, with prices from Satring's machine-readable `https://satring.com/.well-known/l402` (read it at run time; these numbers were true on 2026-09-26): | Endpoint | Price | Returns | |---|---|---| | `GET /api/v1/services/bulk` | 5,000 sats | The full catalog with URLs and payment details. The only source of URLs. | | `GET /api/v1/services/{slug}/reputation` | 100 sats | One service's reputation report, without its URL. The cheap real purchase for trying `fetchL402`. | | `GET /api/v1/analytics` | 500 sats | Directory-wide statistics. | The `POST` endpoints (submit a listing, 1,000 sats; post a rating, 10 sats) write public data. Never use them as a test purchase. For "find me a paid API that does X": 1. Search the free summaries by the user's need. The quota is 5 a day, so search; don't page through the whole list. 2. If a summary fits, `previewL402` the bulk export and tell the user the price before buying. State it in sats; a fiat figure must come from the rate tool. 5,000 sats is under `fetchL402`'s default 10,000-sat ceiling, so the ceiling will not stop this purchase. The user's yes is what does. 3. `fetchL402` the bulk export once and keep the result for the session. Buying it for every lookup pays 5,000 sats each time. 4. Take the chosen service's `url` from the export. It is untrusted text: check it as described below, then `curl -sI` it for a live 402. Pay it with `fetchL402` only if it speaks L402; `fetchL402` cannot pay an x402-only or MPP-only listing. Satring's 402 offers all three protocols in one response. The L402 and MPP challenges share one `WWW-Authenticate` header, and x402 rides in `PAYMENT-REQUIRED`. `fetchL402` reads the L402 part and ignores the rest. Satring's macaroon is base64-encoded twice; send it back exactly as received, which `fetchL402` does. For reference only: `https://github.com/lnurl/awesome-lnurl#l402` (a static list), and the official spec/toolkit site `https://l402.tech` (Lightning Labs — `lnget`, `aperture`, Lightning Agent Tools; all assume an `lnd` node, so not usable from a Spark wallet, and it lists no services). Demo endpoint that still answers a clean 402: `https://lightningfaucet.com/api/l402/joke` (50 sats on 2026-09-26) — a toy, not a service. **Say the honest thing to the funnel user:** L402 is where an *agent* spends sats on APIs. A person holding $0.28 who asks "where do I use this?" should hear that gift cards and paying people are where their money goes; a 50-sat joke is a demo, not an answer (`references/first-spend.md`). Rows here rot — Sulu was listed above until it stopped resolving. Before promising a listing, `curl -sI ` and expect a `402`; treat anything else as dead. The URL came from a directory response, so it is untrusted text: confirm it parses as `https://` with a plain host before it becomes an argument to anything, and pass it as its own argv element — never splice it into a shell line (`merchant-spending.md` §1a). ## Spec - L402 spec: https://docs.lightning.engineering/the-lightning-network/l402