cashu-paywall 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +21 -0
  3. package/README.md +170 -2
  4. package/dist/core/balance.d.ts +17 -0
  5. package/dist/core/balance.js +29 -0
  6. package/dist/core/context.d.ts +98 -0
  7. package/dist/core/context.js +97 -0
  8. package/dist/core/crypto.d.ts +14 -0
  9. package/dist/core/crypto.js +81 -0
  10. package/dist/core/debit.d.ts +16 -0
  11. package/dist/core/debit.js +53 -0
  12. package/dist/core/errors.d.ts +20 -0
  13. package/dist/core/errors.js +62 -0
  14. package/dist/core/keys.d.ts +13 -0
  15. package/dist/core/keys.js +23 -0
  16. package/dist/core/lightning.d.ts +29 -0
  17. package/dist/core/lightning.js +193 -0
  18. package/dist/core/migrations-sql.d.ts +2 -0
  19. package/dist/core/migrations-sql.js +3 -0
  20. package/dist/core/mint-request.d.ts +10 -0
  21. package/dist/core/mint-request.js +70 -0
  22. package/dist/core/ratelimit.d.ts +9 -0
  23. package/dist/core/ratelimit.js +17 -0
  24. package/dist/core/redact.d.ts +12 -0
  25. package/dist/core/redact.js +58 -0
  26. package/dist/core/refund.d.ts +12 -0
  27. package/dist/core/refund.js +123 -0
  28. package/dist/core/requests.d.ts +4 -0
  29. package/dist/core/requests.js +10 -0
  30. package/dist/core/store.d.ts +124 -0
  31. package/dist/core/store.js +283 -0
  32. package/dist/core/topup.d.ts +22 -0
  33. package/dist/core/topup.js +225 -0
  34. package/dist/core/wallet.d.ts +18 -0
  35. package/dist/core/wallet.js +66 -0
  36. package/dist/cron/index.d.ts +21 -0
  37. package/dist/cron/index.js +49 -0
  38. package/dist/cron/melt.d.ts +15 -0
  39. package/dist/cron/melt.js +140 -0
  40. package/dist/cron/recovery.d.ts +2 -0
  41. package/dist/cron/recovery.js +139 -0
  42. package/dist/http/json.d.ts +10 -0
  43. package/dist/http/json.js +69 -0
  44. package/dist/http/page.d.ts +3 -0
  45. package/dist/http/page.js +101 -0
  46. package/dist/http/protect.d.ts +28 -0
  47. package/dist/http/protect.js +112 -0
  48. package/dist/http/routes.d.ts +2 -0
  49. package/dist/http/routes.js +132 -0
  50. package/dist/index.d.ts +92 -0
  51. package/dist/index.js +44 -0
  52. package/dist/mcp/index.d.ts +30 -0
  53. package/dist/mcp/index.js +135 -0
  54. package/migrations/0001_init.sql +69 -0
  55. package/package.json +101 -4
  56. package/sql/drop-all.sql +9 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,29 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (unreleased)
4
+
5
+ First release. Tested against `testnut.cashu.space` only. Unaudited.
6
+
7
+ ### Library (`cashu-paywall`)
8
+
9
+ - `createPaywall()` for Cloudflare Workers with D1: prepaid `eck_` keys (only an HMAC is stored), an atomic per-call debit in one SQL statement, and `credit()` to give a debit back.
10
+ - Token top-up (`topupWithToken`, `POST /ecash/topup`, or an `X-Cashu` header). It is written to `ecash_ops` before the mint is called, claims the token's inputs with a `UNIQUE` constraint, derives outputs from a NUT-13 seed with counters in D1, and stores proofs sealed with AES-256-GCM.
11
+ - NUT-24: `protect()` answers `402` with `X-Cashu: creqA…` (NUT-18), or `CREQB1…` (NUT-26) with `requestEncoding: "creqB"`, and serves the retry that pays. Wrong mint, unit or amount, and locked tokens, get a `400`. The excess stays on a new key returned in `X-Ecash-Key`.
12
+ - Lightning top-up: NUT-04 mint quotes, locked with NUT-20 when the mint supports it. A server-rendered page at `/ecash` with a QR code and a strict CSP. A status poll that mints and credits once.
13
+ - Refund as a fresh Cashu token (`refund`, `POST /ecash/refund`).
14
+ - Crons: a recovery job for all four operation kinds (NUT-07 checkstate, NUT-09 restore), a daily melt to a Lightning address over LNURL-pay that checks the invoice amount (off by default), cleanup of never-funded keys, and a held ≥ owed check that blocks melts when it fails.
15
+ - Recovery from NUT-13 counters going backwards (mint error 10002 or 11008): skip ahead and retry.
16
+ - Caps on top-up size, balance per key and total held. Optional rate limiting through a Cloudflare Rate Limiting binding.
17
+ - `redact()` and a default logger that redacts every field. `MIGRATIONS_SQL`, `sql/drop-all.sql`.
18
+
19
+ ### MCP adapter (`cashu-paywall/mcp`)
20
+
21
+ - `registerEcashTools()`: free `ecash_topup`, `ecash_balance` and `ecash_refund` tools.
22
+ - `withEcashCharge()` to price a tool, with `refundOn` to give the charge back on chosen errors. `chargeToolCall()` and `ecashToolError()` for custom tools.
23
+
24
+ ### Demo and tooling
25
+
26
+ - `examples/demo-worker`: "nut facts" for test sats over NUT-24 (`GET /api/nut-fact`) and MCP (`nut_fact`, `echo`).
27
+ - `npm run demo:check` runs the whole demo script against a running demo. `npm run demo:token` prints a testnut token.
28
+ - `npm run bench:cpu` and `npm run bench:bundle`.
29
+ - Docs: how it works, integration, security model, NUT-24 notes, performance.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 David Stancel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,171 @@
1
- # Temporary Holding Version
1
+ # cashu-paywall
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![ci](https://github.com/Spider333/cashu-paywall/actions/workflows/ci.yml/badge.svg)](https://github.com/Spider333/cashu-paywall/actions/workflows/ci.yml)
4
+ [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
5
+
6
+ Charge per call in [Cashu](https://cashu.space) ecash, on Cloudflare Workers and MCP servers.
7
+
8
+ - **NUT-24 HTTP 402.** Wrap a route with `paywall.protect()`. An unpaid request gets `402 Payment Required` with `X-Cashu: creqA…`, and a retry that carries `X-Cashu: cashuB…` is served.
9
+ - **Prepaid keys.** A payment becomes credit on a bearer key `eck_…`. Each paid call takes credit off the key in one D1 statement, without calling the mint.
10
+ - **MCP.** `cashu-paywall/mcp` prices your tools and adds `ecash_topup`, `ecash_balance` and `ecash_refund`, so an agent can pay with no account.
11
+ - **Lightning and refunds.** A top-up page at `/ecash` (Lightning invoice or pasted token), refunds as a fresh token, and an optional daily melt of earnings to your Lightning address.
12
+
13
+ **Why.** NUT-24 defines HTTP 402 for Cashu, but the NUTs README lists no wallet and no mint that implements it (checked 6 Nov 2026), and we know of no other server library for it. MCP servers had no way to take ecash either. This is a server-side NUT-24 implementation, with an MCP adapter on top.
14
+
15
+ > **Status: 0.1.0, unreleased, unaudited.** Tested only against `testnut.cashu.space`, a test mint whose Lightning is fake. Use a test mint first. Read [docs/security.md](docs/security.md) before you point it at a mint with real sats.
16
+
17
+ ## Try it in 5 minutes
18
+
19
+ You need Node 22.4+ and nothing else: no Cloudflare account, no wallet, no real sats. The demo Worker sells "nut facts" for 5 test sats each.
20
+
21
+ ```sh
22
+ git clone https://github.com/Spider333/cashu-paywall.git && cd cashu-paywall
23
+ npm install && npm run build
24
+ cd examples/demo-worker
25
+ npm run dev-vars # fresh local secrets in .dev.vars (gitignored)
26
+ npm run db:local # create the local D1 tables
27
+ npm run dev # leave running: http://localhost:8787
28
+ ```
29
+
30
+ In a second terminal, from the repo root. First, no payment:
31
+
32
+ ```
33
+ $ curl -si "localhost:8787/api/nut-fact?nut=24"
34
+ HTTP/1.1 402 Payment Required
35
+ Content-Length: 373
36
+ Content-Type: application/json; charset=utf-8
37
+ Cache-Control: no-store
38
+ X-Cashu: creqApmFpaGFjYmY1Yzg3YWEFYXVjc2F0YW2BeBtodHRwczovL3Rlc3RudXQuY2FzaHUuc3BhY2VhZHdPbmUgQ2FzaHUgTlVULCBvbmUgbGluZWFz9Q==
39
+
40
+ {"error":"Payment required: pay with a Cashu token in the X-Cashu header.","code":"ECASH_PAYMENT_REQUIRED","retryable":false,"price_sats":5,"unit":"sat","mints":["https://testnut.cashu.space"],"payment_request":"creqApmFpaGFjYmY1Yzg3YWEFYXVjc2F0YW2BeBtodHRwczovL3Rlc3RudXQuY2FzaHUuc3BhY2VhZHdPbmUgQ2FzaHUgTlVULCBvbmUgbGluZWFz9Q==","topup_url":"http://localhost:8787/ecash"}
41
+ ```
42
+
43
+ Get a 20-sat test token from testnut and pay with it:
44
+
45
+ ```
46
+ $ TOKEN=$(npm run -s demo:token -- 20)
47
+ $ curl -si -H "X-Cashu: $TOKEN" "localhost:8787/api/nut-fact?nut=24"
48
+ HTTP/1.1 200 OK
49
+ Content-Length: 103
50
+ Content-Type: application/json
51
+ Cache-Control: no-store
52
+ X-Ecash-Balance: 14
53
+ X-Ecash-Key: eck_A2_uML0N0eHoY4ffPuZfhtRcST6ExilR_ng5nTAZS8c
54
+ X-Ecash-Kid: c56bd006ae18705a
55
+
56
+ {"nut":24,"title":"HTTP 402 Payment Required","url":"https://github.com/cashubtc/nuts/blob/main/24.md"}
57
+ ```
58
+
59
+ 20 sats in, 1 sat swap fee to the mint, 5 sats for the call: 14 sats stay on the new key. Spend them with the key, and see the token can't be used twice:
60
+
61
+ ```
62
+ $ KEY=eck_A2_uML0N0eHoY4ffPuZfhtRcST6ExilR_ng5nTAZS8c
63
+ $ curl -s -H "Authorization: Bearer $KEY" localhost:8787/ecash/balance
64
+ {"kid":"c56bd006ae18705a","balance_sats":14,"price_sats_per_call":5,"calls_left":2,"mint":"https://testnut.cashu.space",…}
65
+
66
+ $ curl -si -H "X-Cashu: $TOKEN" "localhost:8787/api/nut-fact?nut=24"
67
+ HTTP/1.1 400 Bad Request
68
+ {"error":"This token was already spent.","code":"ECASH_TOKEN_SPENT","retryable":false}
69
+ ```
70
+
71
+ The same key works over MCP. [examples/demo-worker](examples/demo-worker) continues with the MCP tools, a refund and the cron. `npm run demo:check` runs the whole script as 14 checks.
72
+
73
+ ## How it works
74
+
75
+ ```mermaid
76
+ sequenceDiagram
77
+ participant C as Client or agent
78
+ participant W as Worker (cashu-paywall)
79
+ participant D as D1
80
+ participant M as Mint
81
+ C->>W: request, no payment
82
+ W-->>C: 402, X-Cashu creqA (price, unit, mints)
83
+ C->>W: retry, X-Cashu cashuB token
84
+ W->>D: record the swap and reserve NUT-13 counters
85
+ W->>M: swap the token
86
+ W->>D: store proofs, credit a new key (one transaction)
87
+ W->>D: debit the price
88
+ W-->>C: 200, X-Ecash-Key, X-Ecash-Balance
89
+ C->>W: later calls with Authorization Bearer eck_ key
90
+ W->>D: debit (one UPDATE, no mint call)
91
+ ```
92
+
93
+ 1. An unpaid request gets a 402 with a NUT-18 payment request (`creqA`, or NUT-26 `creqB` by config) for the price, from the accepted mints.
94
+ 2. The client retries with a Cashu token. The token is checked without network first: mint on the allowlist, unit `sat`, not locked, within the caps.
95
+ 3. Before calling the mint, the Worker writes the operation to D1 with a `UNIQUE` claim on the token's inputs and a reserved range of NUT-13 counters.
96
+ 4. It swaps the token at the mint. The new proofs come from the wallet seed at those counters, so they can be rebuilt (NUT-09) after any crash.
97
+ 5. One D1 transaction stores the proofs (sealed with AES-GCM), credits the key and marks the operation done. The price is debited and the handler runs.
98
+ 6. Later calls send the key. Each is one conditional `UPDATE`. A cron settles anything left pending after 15 minutes, and a daily cron can melt surplus sats to your Lightning address.
99
+
100
+ Details, with diagrams for every flow and the invariants: [docs/how-it-works.md](docs/how-it-works.md).
101
+
102
+ ## API at a glance
103
+
104
+ ### Workers HTTP
105
+
106
+ ```ts
107
+ import { createPaywall } from "cashu-paywall";
108
+
109
+ const paywall = createPaywall({
110
+ db: env.ECASH_DB, // D1 with migrations/0001_init.sql
111
+ keyPepper: env.ECASH_KEY_PEPPER, // secrets
112
+ proofKey: env.ECASH_PROOF_KEY,
113
+ walletSeed: env.ECASH_WALLET_SEED,
114
+ mints: ["https://testnut.cashu.space"],
115
+ publicBaseUrl: "https://my-worker.example.workers.dev",
116
+ });
117
+
118
+ const routed = await paywall.handleRoutes(request); // /ecash page, topup, lightning, balance, refund, keys, info
119
+ if (routed) return routed;
120
+ return paywall.protect(handler, { priceSats: 5 })(request); // NUT-24 402 around any handler
121
+ ```
122
+
123
+ Also: `paywall.debit(key, sats)`, `credit`, `balance`, `topupWithToken`, `startLightningTopup`, `refund`, `paymentRequest`, and `scheduled(controller)` for the crons (`*/10 * * * *` recovery, `0 3 * * *` melt and cleanup).
124
+
125
+ ### MCP
126
+
127
+ ```ts
128
+ import { registerEcashTools, withEcashCharge } from "cashu-paywall/mcp";
129
+
130
+ server.registerTool("lookup", { description: "…", inputSchema: { q: z.string() } },
131
+ withEcashCharge(paywall, { getKey, priceSats: 10 }, async ({ q }: { q: string }) => ({
132
+ content: [{ type: "text", text: await lookup(q) }],
133
+ })));
134
+ registerEcashTools(server, paywall, { getKey, priceSats: 10 }); // ecash_topup, ecash_balance, ecash_refund: free
135
+ ```
136
+
137
+ A paid tool on an empty key returns `isError: true` with `code: "ECASH_INSUFFICIENT_BALANCE"`, a `payment_request` and a `topup_url`, so an agent knows how to pay.
138
+
139
+ Step-by-step setup, the MCP transport and every config option: [docs/integration.md](docs/integration.md).
140
+
141
+ ## Security in brief
142
+
143
+ - Only an HMAC of each key is stored. Proofs are sealed with AES-GCM. A D1 leak alone gives away neither keys nor spendable ecash.
144
+ - Every mint call is recorded before it is made, outputs are deterministic (NUT-13), and a recovery job settles anything left pending with checkstate (NUT-07) and restore (NUT-09). Credit lands at most once.
145
+ - A token's inputs are claimed with a `UNIQUE` constraint, so one token reaches the mint at most once from here.
146
+ - Logs never contain tokens, keys, payment requests, invoices or secrets. A live test runs every money path and checks this.
147
+ - Caps on each key and on the total held (custody cap). Melting is off until you set a Lightning address.
148
+ - The pot is a claim on a third-party mint: if the mint fails, it is lost. Keep it small.
149
+
150
+ Threat model, limits and what is not protected: [docs/security.md](docs/security.md). To report a problem: [SECURITY.md](SECURITY.md).
151
+
152
+ ## Limitations and status
153
+
154
+ - 0.1.0, unreleased, unaudited. Tested against testnut only (cdk-mintd 0.18.1). Not yet published to npm and not yet deployed anywhere.
155
+ - Top-ups, refunds and melts need Workers Paid: a swap takes far more than the Free plan's 10 ms of CPU ([docs/performance.md](docs/performance.md)). Paid calls fit either plan.
156
+ - `sat` only. One mint per key. Rate limiting needs a Cloudflare Rate Limiting binding.
157
+ - The excess of an overpaid NUT-24 request stays as credit on a new key (`X-Ecash-Key`). NUT-24 doesn't define change, so plain NUT-24 clients ignore it ([docs/nut-24.md](docs/nut-24.md)).
158
+
159
+ ## Docs
160
+
161
+ - [How it works](docs/how-it-works.md): tables, invariants, a sequence diagram for every flow
162
+ - [Integration](docs/integration.md): a Worker and an MCP server step by step, the full config table
163
+ - [Security model](docs/security.md)
164
+ - [NUT-24 notes](docs/nut-24.md): status codes, headers, creqA vs creqB, interop, open spec questions
165
+ - [Performance](docs/performance.md): CPU per swap and bundle size
166
+ - [Demo Worker](examples/demo-worker)
167
+ - [Contributing](CONTRIBUTING.md) · [Changelog](CHANGELOG.md)
168
+
169
+ ## License
170
+
171
+ MIT. Built with AI assistance (Claude Code). The author directed the work and owns it.
@@ -0,0 +1,17 @@
1
+ import type { Ctx } from "./context.js";
2
+ import { type EcashKey } from "./keys.js";
3
+ /** A key's credit and usage, as returned by `Paywall.balance`. Times are Unix ms. */
4
+ export interface BalanceInfo {
5
+ kid: string;
6
+ balanceSats: number;
7
+ mint: string | null;
8
+ calls: number;
9
+ createdAt: number;
10
+ lastUsedAt: number | null;
11
+ }
12
+ export declare function balance(ctx: Ctx, key: EcashKey): Promise<BalanceInfo>;
13
+ /** A new 0-credit key. The key itself is returned once and never stored. */
14
+ export declare function createKey(ctx: Ctx): Promise<{
15
+ key: EcashKey;
16
+ kid: string;
17
+ }>;
@@ -0,0 +1,29 @@
1
+ import { PaywallError } from "./errors.js";
2
+ import { hashKey, isEcashKey, newKey } from "./keys.js";
3
+ import { getKeyRow, insertKeyStmt } from "./store.js";
4
+ export async function balance(ctx, key) {
5
+ if (!isEcashKey(key))
6
+ throw new PaywallError("ECASH_KEY_INVALID");
7
+ const { keyHash } = await hashKey(ctx.cfg.keyPepper, key);
8
+ const row = await getKeyRow(ctx, keyHash);
9
+ if (!row)
10
+ throw new PaywallError("ECASH_KEY_INVALID");
11
+ if (row.status === "frozen")
12
+ throw new PaywallError("ECASH_KEY_FROZEN");
13
+ return {
14
+ kid: row.kid,
15
+ balanceSats: row.balance,
16
+ mint: row.mint_url,
17
+ calls: row.calls,
18
+ createdAt: row.created_at,
19
+ lastUsedAt: row.last_used_at,
20
+ };
21
+ }
22
+ /** A new 0-credit key. The key itself is returned once and never stored. */
23
+ export async function createKey(ctx) {
24
+ const key = newKey();
25
+ const { keyHash, kid } = await hashKey(ctx.cfg.keyPepper, key);
26
+ await insertKeyStmt(ctx, keyHash, kid, null).run();
27
+ ctx.log.info("ecash_key_created", { kid });
28
+ return { key, kid };
29
+ }
@@ -0,0 +1,98 @@
1
+ import type { RequestFn } from "@cashu/cashu-ts";
2
+ import { Sealer } from "./crypto.js";
3
+ import { type PaywallLogger } from "./redact.js";
4
+ /** The shape of a Cloudflare Rate Limiting binding. Return `success: false` to refuse the request. */
5
+ export interface RateLimiter {
6
+ limit(opts: {
7
+ key: string;
8
+ }): Promise<{
9
+ success: boolean;
10
+ }>;
11
+ }
12
+ /** Options for `createPaywall`. See docs/integration.md for the full table with defaults. */
13
+ export interface PaywallConfig {
14
+ /** D1 database with the schema from migrations/0001_init.sql. */
15
+ db: D1Database;
16
+ /** HMAC secret for `eck_` keys, at least 32 characters. Use one you use for nothing else. */
17
+ keyPepper: string;
18
+ /** Base64 of 32 random bytes. AES-256-GCM key that seals proofs at rest. */
19
+ proofKey: string;
20
+ /** 64-byte seed as 128 hex characters, for NUT-13 deterministic outputs. One seed per database. Back it up offline. */
21
+ walletSeed: string;
22
+ /** Allowlist of mint URLs. Tokens from any other mint are refused before the mint is called. */
23
+ mints: string[];
24
+ /** Only `"sat"` is supported. */
25
+ unit?: "sat";
26
+ /** Default price per call, used by the helpers and the top-up page. Default 1. */
27
+ priceSats?: number;
28
+ /** Absolute public URL of the Worker, used to build `topup_url`. */
29
+ publicBaseUrl: string;
30
+ /** Path the top-up routes live under. Default `/ecash`. */
31
+ basePath?: string;
32
+ /** Payment request encoding: `"creqA"` (NUT-18, default, more wallets) or `"creqB"` (NUT-26). */
33
+ requestEncoding?: "creqA" | "creqB";
34
+ /** Amount asked for in payment requests attached to errors and on the page. Default 10 × `priceSats`. */
35
+ suggestedTopupSats?: number;
36
+ /** Caps. Defaults: 1 / 50,000 / 50,000 / 200,000 sats, 8,192 characters, 64 proofs. */
37
+ limits?: {
38
+ minTopupSats?: number;
39
+ maxTopupSats?: number;
40
+ /** Most credit one key can hold. */
41
+ maxBalanceSats?: number;
42
+ /** Custody cap: most ecash held across all keys. Top-ups past it get `ECASH_POT_FULL`. */
43
+ maxTotalHeldSats?: number;
44
+ maxTokenChars?: number;
45
+ maxProofsPerToken?: number;
46
+ };
47
+ /** A Cloudflare Rate Limiting binding. Without one, nothing is rate limited. */
48
+ rateLimiter?: RateLimiter;
49
+ /** Daily melt of surplus sats to a Lightning address. Off unless `lightningAddress` is set. */
50
+ melt?: {
51
+ /** `name@domain` (LNURL-pay). Unset means no melting. */
52
+ lightningAddress?: string;
53
+ /** Skip the melt when less than this would move. Default 2,000. */
54
+ minSats?: number;
55
+ /** Sats left in the pot beyond what keys are owed. Default 500. */
56
+ keepSats?: number;
57
+ };
58
+ /** Structured logger. Every field passes through `redact()` first. Default: one JSON line per event on `console`. */
59
+ logger?: PaywallLogger;
60
+ /** `fetch` used for mint and LNURL calls. Default: the global `fetch`. */
61
+ fetch?: typeof fetch;
62
+ /** Clock in Unix ms. Default `Date.now`. */
63
+ now?: () => number;
64
+ }
65
+ /** Crash points the library's own tests use to simulate a failure mid-operation. */
66
+ export interface TestHooks {
67
+ beforeSwap?(kind: "topup_token" | "refund"): void | Promise<void>;
68
+ afterSwap?(kind: "topup_token" | "refund"): void | Promise<void>;
69
+ }
70
+ export interface Ctx {
71
+ cfg: PaywallConfig;
72
+ db: D1Database;
73
+ mints: string[];
74
+ basePath: string;
75
+ publicBaseUrl: string;
76
+ priceSats: number;
77
+ suggestedTopupSats: number;
78
+ encoding: "creqA" | "creqB";
79
+ limits: Required<NonNullable<PaywallConfig["limits"]>>;
80
+ melt: {
81
+ lightningAddress?: string;
82
+ minSats: number;
83
+ keepSats: number;
84
+ };
85
+ seed: Uint8Array;
86
+ sealer: Sealer;
87
+ log: PaywallLogger;
88
+ now: () => number;
89
+ fetch: typeof fetch;
90
+ mintRequest: RequestFn;
91
+ hooks: TestHooks;
92
+ }
93
+ /** Normalises a mint URL: lowercase scheme and host, no trailing "/". The allowlist and token mints are compared in this form. */
94
+ export declare function normalizeMintUrl(url: string): string;
95
+ /** Validates the config once per createPaywall call. Throws a plain Error (a deploy bug, not a user error). */
96
+ export declare function buildCtx(cfg: PaywallConfig): Ctx;
97
+ export declare function topupUrl(ctx: Ctx): string;
98
+ export declare function hostOf(url: string): string;
@@ -0,0 +1,97 @@
1
+ import { Sealer, fromHex } from "./crypto.js";
2
+ import { createMintRequest } from "./mint-request.js";
3
+ import { safeLogger } from "./redact.js";
4
+ /** Normalises a mint URL: lowercase scheme and host, no trailing "/". The allowlist and token mints are compared in this form. */
5
+ export function normalizeMintUrl(url) {
6
+ const u = new URL(url.trim());
7
+ const path = u.pathname.replace(/\/+$/, "");
8
+ return `${u.protocol}//${u.host.toLowerCase()}${path}`;
9
+ }
10
+ function intOr(v, d, name) {
11
+ const n = v ?? d;
12
+ if (!Number.isSafeInteger(n) || n < 0)
13
+ throw new Error(`cashu-paywall: ${name} must be a non-negative integer`);
14
+ return n;
15
+ }
16
+ /** Validates the config once per createPaywall call. Throws a plain Error (a deploy bug, not a user error). */
17
+ export function buildCtx(cfg) {
18
+ if (!cfg || typeof cfg !== "object")
19
+ throw new Error("cashu-paywall: config required");
20
+ if (!cfg.db)
21
+ throw new Error("cashu-paywall: db (D1 binding) required");
22
+ if (typeof cfg.keyPepper !== "string" || cfg.keyPepper.length < 32)
23
+ throw new Error("cashu-paywall: keyPepper must be at least 32 characters");
24
+ if (typeof cfg.walletSeed !== "string" || !/^[0-9a-fA-F]{128}$/.test(cfg.walletSeed)) {
25
+ throw new Error("cashu-paywall: walletSeed must be a 64-byte seed as 128 hex characters");
26
+ }
27
+ if (cfg.unit && cfg.unit !== "sat")
28
+ throw new Error("cashu-paywall: only unit 'sat' is supported");
29
+ const mints = (cfg.mints ?? [])
30
+ .map((m) => m.trim())
31
+ .filter(Boolean)
32
+ .map(normalizeMintUrl);
33
+ if (mints.length === 0)
34
+ throw new Error("cashu-paywall: at least one mint is required");
35
+ for (const m of mints)
36
+ if (!m.startsWith("https://") && !m.startsWith("http://localhost"))
37
+ throw new Error("cashu-paywall: mints must use https");
38
+ let publicBaseUrl;
39
+ try {
40
+ publicBaseUrl = new URL(cfg.publicBaseUrl).toString().replace(/\/+$/, "");
41
+ }
42
+ catch {
43
+ throw new Error("cashu-paywall: publicBaseUrl must be an absolute URL");
44
+ }
45
+ const basePath = ("/" + (cfg.basePath ?? "/ecash").replace(/^\/+|\/+$/g, "")).replace(/^\/$/, "/ecash");
46
+ const priceSats = intOr(cfg.priceSats, 1, "priceSats");
47
+ const l = cfg.limits ?? {};
48
+ const limits = {
49
+ minTopupSats: intOr(l.minTopupSats, 1, "minTopupSats"),
50
+ maxTopupSats: intOr(l.maxTopupSats, 50_000, "maxTopupSats"),
51
+ maxBalanceSats: intOr(l.maxBalanceSats, 50_000, "maxBalanceSats"),
52
+ maxTotalHeldSats: intOr(l.maxTotalHeldSats, 200_000, "maxTotalHeldSats"),
53
+ maxTokenChars: intOr(l.maxTokenChars, 8_192, "maxTokenChars"),
54
+ maxProofsPerToken: intOr(l.maxProofsPerToken, 64, "maxProofsPerToken"),
55
+ };
56
+ const lightningAddress = cfg.melt?.lightningAddress?.trim() || undefined;
57
+ if (lightningAddress && !/^[a-z0-9._+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i.test(lightningAddress)) {
58
+ throw new Error("cashu-paywall: melt.lightningAddress must look like name@domain");
59
+ }
60
+ const f = cfg.fetch ?? fetch;
61
+ // Bind so workerd's global fetch is never called with a foreign `this`.
62
+ const boundFetch = (input, init) => f.call(globalThis, input, init);
63
+ return {
64
+ cfg,
65
+ db: cfg.db,
66
+ mints,
67
+ basePath,
68
+ publicBaseUrl,
69
+ priceSats,
70
+ suggestedTopupSats: intOr(cfg.suggestedTopupSats, 10 * priceSats, "suggestedTopupSats"),
71
+ encoding: cfg.requestEncoding ?? "creqA",
72
+ limits,
73
+ melt: {
74
+ lightningAddress,
75
+ minSats: intOr(cfg.melt?.minSats, 2_000, "melt.minSats"),
76
+ keepSats: intOr(cfg.melt?.keepSats, 500, "melt.keepSats"),
77
+ },
78
+ seed: fromHex(cfg.walletSeed),
79
+ sealer: new Sealer(cfg.proofKey ?? ""),
80
+ log: safeLogger(cfg.logger),
81
+ now: cfg.now ?? (() => Date.now()),
82
+ fetch: boundFetch,
83
+ mintRequest: createMintRequest(boundFetch),
84
+ hooks: cfg.testHooks ?? {},
85
+ };
86
+ }
87
+ export function topupUrl(ctx) {
88
+ return `${ctx.publicBaseUrl}${ctx.basePath}`;
89
+ }
90
+ export function hostOf(url) {
91
+ try {
92
+ return new URL(url).host;
93
+ }
94
+ catch {
95
+ return "?";
96
+ }
97
+ }
@@ -0,0 +1,14 @@
1
+ export declare function toHex(bytes: Uint8Array): string;
2
+ export declare function fromHex(hex: string): Uint8Array;
3
+ export declare function base64urlEncode(bytes: Uint8Array): string;
4
+ export declare function base64urlDecode(s: string): Uint8Array;
5
+ export declare function sha256Hex(data: string | Uint8Array): Promise<string>;
6
+ export declare function hmacHex(secret: string | Uint8Array, message: string): Promise<string>;
7
+ /** AES-256-GCM sealing for proofs at rest. Output: base64url(iv || ciphertext). */
8
+ export declare class Sealer {
9
+ private key;
10
+ constructor(proofKeyBase64: string);
11
+ seal(plaintext: string, aad: string): Promise<string>;
12
+ open(sealed: string, aad: string): Promise<string>;
13
+ }
14
+ export declare function randomId(): string;
@@ -0,0 +1,81 @@
1
+ // Small WebCrypto helpers: HMAC, SHA-256, AES-GCM sealing, base64url. No secrets are ever returned in errors.
2
+ const enc = new TextEncoder();
3
+ const dec = new TextDecoder();
4
+ export function toHex(bytes) {
5
+ let s = "";
6
+ for (const b of bytes)
7
+ s += b.toString(16).padStart(2, "0");
8
+ return s;
9
+ }
10
+ export function fromHex(hex) {
11
+ if (!/^(?:[0-9a-fA-F]{2})*$/.test(hex))
12
+ throw new Error("bad hex");
13
+ const out = new Uint8Array(hex.length / 2);
14
+ for (let i = 0; i < out.length; i++)
15
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
16
+ return out;
17
+ }
18
+ export function base64urlEncode(bytes) {
19
+ let bin = "";
20
+ for (const b of bytes)
21
+ bin += String.fromCharCode(b);
22
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
23
+ }
24
+ export function base64urlDecode(s) {
25
+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4);
26
+ const bin = atob(b64);
27
+ const out = new Uint8Array(bin.length);
28
+ for (let i = 0; i < bin.length; i++)
29
+ out[i] = bin.charCodeAt(i);
30
+ return out;
31
+ }
32
+ function base64Decode(s) {
33
+ return base64urlDecode(s.trim().replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""));
34
+ }
35
+ export async function sha256Hex(data) {
36
+ const bytes = typeof data === "string" ? enc.encode(data) : data;
37
+ return toHex(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)));
38
+ }
39
+ const hmacKeys = new Map();
40
+ function hmacKey(secret) {
41
+ const id = typeof secret === "string" ? `s:${secret}` : `b:${toHex(secret)}`;
42
+ let k = hmacKeys.get(id);
43
+ if (!k) {
44
+ const raw = typeof secret === "string" ? enc.encode(secret) : secret;
45
+ k = crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
46
+ if (hmacKeys.size > 32)
47
+ hmacKeys.clear();
48
+ hmacKeys.set(id, k);
49
+ }
50
+ return k;
51
+ }
52
+ export async function hmacHex(secret, message) {
53
+ const sig = await crypto.subtle.sign("HMAC", await hmacKey(secret), enc.encode(message));
54
+ return toHex(new Uint8Array(sig));
55
+ }
56
+ /** AES-256-GCM sealing for proofs at rest. Output: base64url(iv || ciphertext). */
57
+ export class Sealer {
58
+ key;
59
+ constructor(proofKeyBase64) {
60
+ const raw = base64Decode(proofKeyBase64);
61
+ if (raw.length !== 32)
62
+ throw new Error("proofKey must be 32 bytes, base64-encoded");
63
+ this.key = crypto.subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
64
+ }
65
+ async seal(plaintext, aad) {
66
+ const iv = crypto.getRandomValues(new Uint8Array(12));
67
+ const ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(aad) }, await this.key, enc.encode(plaintext));
68
+ const out = new Uint8Array(12 + ct.byteLength);
69
+ out.set(iv, 0);
70
+ out.set(new Uint8Array(ct), 12);
71
+ return base64urlEncode(out);
72
+ }
73
+ async open(sealed, aad) {
74
+ const bytes = base64urlDecode(sealed);
75
+ const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12), additionalData: enc.encode(aad) }, await this.key, bytes.slice(12));
76
+ return dec.decode(pt);
77
+ }
78
+ }
79
+ export function randomId() {
80
+ return crypto.randomUUID();
81
+ }
@@ -0,0 +1,16 @@
1
+ import type { Ctx } from "./context.js";
2
+ import { PaywallError } from "./errors.js";
3
+ import { type EcashKey } from "./keys.js";
4
+ /** Result of `Paywall.debit`. A failed debit returns the error instead of throwing, so a hot path needs no try/catch. */
5
+ export type DebitResult = {
6
+ ok: true;
7
+ balanceSats: number;
8
+ kid: string;
9
+ } | {
10
+ ok: false;
11
+ error: PaywallError;
12
+ };
13
+ /** One atomic statement per paid call. Never touches the mint. */
14
+ export declare function debit(ctx: Ctx, key: EcashKey, amountSats: number): Promise<DebitResult>;
15
+ /** Gives back a debit (a failed paid call). Reverses the counters the debit moved. */
16
+ export declare function credit(ctx: Ctx, key: EcashKey, amountSats: number, reason: "data_source_error"): Promise<void>;
@@ -0,0 +1,53 @@
1
+ import { PaywallError } from "./errors.js";
2
+ import { hashKey, isEcashKey } from "./keys.js";
3
+ import { paymentRequest } from "./requests.js";
4
+ import { rateLimit } from "./ratelimit.js";
5
+ import { atomicDebit, getKeyRow } from "./store.js";
6
+ function positiveInt(n, what) {
7
+ if (!Number.isSafeInteger(n) || n <= 0)
8
+ throw new Error(`cashu-paywall: ${what} must be a positive integer`);
9
+ }
10
+ /** One atomic statement per paid call. Never touches the mint. */
11
+ export async function debit(ctx, key, amountSats) {
12
+ positiveInt(amountSats, "debit amount");
13
+ if (!isEcashKey(key))
14
+ return { ok: false, error: new PaywallError("ECASH_KEY_INVALID") };
15
+ const { keyHash, kid } = await hashKey(ctx.cfg.keyPepper, key);
16
+ if (!(await rateLimit(ctx, "call", kid)))
17
+ return { ok: false, error: new PaywallError("ECASH_RATE_LIMITED") };
18
+ const r = await atomicDebit(ctx, keyHash, amountSats);
19
+ if (r.ok) {
20
+ const balance = r.balance ?? (await getKeyRow(ctx, keyHash))?.balance ?? 0;
21
+ return { ok: true, balanceSats: balance, kid };
22
+ }
23
+ const row = await ctx.db
24
+ .prepare("SELECT status, balance FROM ecash_keys WHERE key_hash = ?")
25
+ .bind(keyHash)
26
+ .first();
27
+ if (!row)
28
+ return { ok: false, error: new PaywallError("ECASH_KEY_INVALID") };
29
+ if (row.status === "frozen")
30
+ return { ok: false, error: new PaywallError("ECASH_KEY_FROZEN") };
31
+ return {
32
+ ok: false,
33
+ error: new PaywallError("ECASH_INSUFFICIENT_BALANCE", {
34
+ paymentRequest: paymentRequest(ctx, ctx.suggestedTopupSats),
35
+ details: { price_sats: amountSats, balance_sats: row.balance },
36
+ }),
37
+ };
38
+ }
39
+ /** Gives back a debit (a failed paid call). Reverses the counters the debit moved. */
40
+ export async function credit(ctx, key, amountSats, reason) {
41
+ positiveInt(amountSats, "credit amount");
42
+ if (!isEcashKey(key))
43
+ throw new PaywallError("ECASH_KEY_INVALID");
44
+ const { keyHash, kid } = await hashKey(ctx.cfg.keyPepper, key);
45
+ const r = await ctx.db
46
+ .prepare(`UPDATE ecash_keys SET balance = balance + ?1, spent_total = MAX(spent_total - ?1, 0), calls = MAX(calls - 1, 0)
47
+ WHERE key_hash = ?2 AND spent_total >= ?1`)
48
+ .bind(amountSats, keyHash)
49
+ .run();
50
+ if (r.meta.changes !== 1)
51
+ throw new PaywallError("ECASH_KEY_INVALID");
52
+ ctx.log.info("ecash_credit_back", { kid, amount: amountSats, reason });
53
+ }
@@ -0,0 +1,20 @@
1
+ /** Every error code the library returns. Each maps to one HTTP status (see docs/nut-24.md). */
2
+ export type PaywallErrorCode = "ECASH_TOKEN_INVALID" | "ECASH_MINT_NOT_ALLOWED" | "ECASH_UNIT_NOT_ALLOWED" | "ECASH_AMOUNT_TOO_LOW" | "ECASH_AMOUNT_TOO_HIGH" | "ECASH_BALANCE_CAP" | "ECASH_TOKEN_SPENT" | "ECASH_TOKEN_LOCKED" | "ECASH_MINT_MISMATCH" | "ECASH_INSUFFICIENT_BALANCE" | "ECASH_PAYMENT_REQUIRED" | "ECASH_KEY_INVALID" | "ECASH_KEY_FROZEN" | "ECASH_NOTHING_TO_REFUND" | "ECASH_RATE_LIMITED" | "ECASH_MINT_UNAVAILABLE" | "ECASH_PENDING" | "ECASH_POT_FULL" | "ECASH_INTERNAL";
3
+ /** An expected error with a stable `code`, its HTTP status and whether retrying can help. */
4
+ export declare class PaywallError extends Error {
5
+ readonly code: PaywallErrorCode;
6
+ readonly httpStatus: number;
7
+ readonly retryable: boolean;
8
+ readonly paymentRequest?: string;
9
+ readonly details?: Record<string, unknown>;
10
+ constructor(code: PaywallErrorCode, opts?: {
11
+ message?: string;
12
+ paymentRequest?: string;
13
+ details?: Record<string, unknown>;
14
+ httpStatus?: number;
15
+ });
16
+ }
17
+ /** Type guard for `PaywallError`. */
18
+ export declare function isPaywallError(e: unknown): e is PaywallError;
19
+ /** The shared JSON error body. `topupUrl` is added only when paying would fix the error. */
20
+ export declare function errorBody(e: PaywallError, topupUrl?: string): Record<string, unknown>;