openreceive 0.4.25 → 0.4.27

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.
@@ -0,0 +1,734 @@
1
+ This is the full file; follow it from Step 0.
2
+
3
+ # OpenReceive agent directions (TanStack Start)
4
+
5
+ ```sh
6
+ # READ THIS FIRST: this file is 39 KB and a summary drops required steps. Download it whole:
7
+ curl -fsSL https://openreceive.org/agent-directions/tanstack-start/full.md
8
+ # Skip the download only if you already have all of it: pasted, read from disk or fetched raw.
9
+ ```
10
+
11
+ **Step 0 in brief** (Step 0 below has the details):
12
+
13
+ - Before installing or editing anything, ask the user for a receive-only NWC code. One question per message.
14
+ - Next ask for the LSC code. If the user wants stablecoins, USDT, USDC, ETH, SOL or crypto, do not ask yes/no first.
15
+ - The user only pastes codes into this chat. Never ask them to edit .env or run a command to save one.
16
+ - Write each code into .env yourself, as Step 0 says. Never echo it or put it in a shell command.
17
+ - Do not suggest rotating or revoking a code because it was pasted here.
18
+ - Start the quickstart only once the NWC code is saved, and the LSC code is saved or the user said "Bitcoin only".
19
+
20
+ These directions describe OpenReceive 0.4.27.
21
+
22
+ Add OpenReceive to a TanStack Start application on Node — the app you are
23
+ already working in, with its own Postgres. OpenReceive ships no TanStack
24
+ Start package: the integration is one server route that hands each request to
25
+ `@openreceive/http`. You do not need a copy of the OpenReceive source: the
26
+ packages are on npm, and the TanStack Start recipe is appended to this file in
27
+ full as the quickstart, so you can do the whole integration without fetching
28
+ anything. Prefer the published packages and the handler they export — do not
29
+ reimplement wallet RPC, settlement, or pricing.
30
+
31
+ On Lovable, or any app on Cloudflare Workers with Supabase, stop here and
32
+ follow https://openreceive.org/agent-directions/lovable.md instead. These
33
+ directions are for a server you run on Node.
34
+
35
+ Do not clone the OpenReceive repository into this app, and do not copy a demo's
36
+ models (`ShopOrder`, a signed-cookie visitor, an in-memory catalog) over tables
37
+ that already exist. Find this application's order, product, and user models —
38
+ whatever they are actually named — and map the three hooks onto those.
39
+
40
+ Keep this application's frontend framework, authentication and database. Pick
41
+ the UI package that matches the frontend that is already here
42
+ (`@openreceive/react`, `/vue`, `/svelte`, `/angular`, or `/elements` for
43
+ plain HTML) — do not add React to a Vue app. Reuse the app's existing
44
+ session/auth in `authorize` and its existing database handle in `storage.db`.
45
+
46
+ ## What OpenReceive is
47
+
48
+ A payment library that runs inside YOUR server. It mounts as ONE catch-all
49
+ server route (`src/routes/openreceive.$.ts`, with GET and POST server
50
+ handlers, on Node) in the application you are editing, issues Lightning
51
+ invoices against a wallet the merchant already controls, and calls back into
52
+ your code when one settles. There is no OpenReceive account and no API key, and
53
+ OpenReceive never holds the funds — the sats land in the wallet the merchant
54
+ connected.
55
+
56
+ The one required credential is a receive-only NWC code (Nostr Wallet Connect):
57
+ a string from the merchant's wallet that can create invoices and read their
58
+ status, and cannot spend. A swap provider (an "LSC" code) optionally lets the
59
+ payer send USDT, USDC, ETH or SOL instead, converted into that same
60
+ Lightning payment. Step 0 collects those credentials from the user; you write three hooks — `authorize`, `amountFor`,
61
+ `onPaid`;
62
+ OpenReceive supplies invoices, polling, settlement and the checkout UI. It never
63
+ owns orders, users, prices, or fulfillment.
64
+
65
+ ## Step 0 — ask for the two codes, one question at a time
66
+
67
+ Before anything else, check one file: the project's `.env`, if it exists.
68
+ `grep -E '^(NWC_URI|LSC_URI_PRIMARY)=.' .env | cut -d= -f1` names the codes
69
+ it sets without printing them. Check with that, here and after each write,
70
+ not by reading the file, and never print the values. A code that is already
71
+ set is not asked for again; if both are set, skip to step 5 (making the
72
+ server load the file), then the quickstart.
73
+
74
+ On a hosted builder (v0, Vercel, Replit, Lovable), the user may say instead
75
+ that both codes are already set as the project's environment variables or
76
+ secrets. Believe them: do not ask for the codes, do not write `.env`, and
77
+ do not read or print the variables. Skip step 5's file loading: the platform already puts them in `process.env`. Do not add them to a compose file or any other deploy config
78
+ either: they already reach the app, and a line such as `NWC_URI: ${NWC_URI}`
79
+ replaces them with an empty value.
80
+
81
+ Otherwise your next action is a question to the user. Do not install packages,
82
+ edit the app, write `.env.example`, or search anywhere else before asking
83
+ it. Do not read deploy config (compose files, Vercel or platform secrets), Docker containers, or process environments, and never run
84
+ `printenv`. A new shop has neither code yet: hunting for one burns the turn and
85
+ can leak other secrets into the transcript.
86
+
87
+ Two server-only URIs are needed before the quickstart:
88
+
89
+ - `NWC_URI` — a receive-only Nostr Wallet Connect code,
90
+ `nostr+walletconnect://…`. Required for Bitcoin.
91
+ - `LSC_URI_PRIMARY` — a Lightning Swap Connect URI,
92
+ `lightning+swapconnect://…`. Required for USDT, USDC, ETH and SOL. Skip it
93
+ only when the user says they want Bitcoin alone.
94
+
95
+ The user never edits an environment file. They paste each code into the chat;
96
+ you store it. Ask one question per message.
97
+
98
+ 1. **First message — the NWC code, and nothing else.** Ask for it and walk them
99
+ through getting it:
100
+
101
+ > To receive payments I need a receive-only wallet code. In Rizful: open
102
+ > the menu, tap NWC, choose Receive-only NWC code, and tap Copy
103
+ > (https://openreceive.org/get_a_nwc_code_to_receive_payments). If you would
104
+ > rather run your own wallet, Alby Hub works too: Connections → Add
105
+ > Connection → Read Only. Paste the code here and I will store it.
106
+
107
+ Do not mention `.env`, exports, or "tell me when it's set".
108
+ 2. **When they paste it.** If it does not start with `nostr+walletconnect://`,
109
+ ask them to copy the receive-only code again. Otherwise write
110
+ `NWC_URI=<paste>` into the project's `.env` with your file-editing
111
+ tool, creating the file if needed. Never write it with a shell command
112
+ (`echo`, `printf`, a heredoc, `python -c`): the command line shows the
113
+ code. Make sure `.gitignore` covers `.env` (and `.dockerignore`, if
114
+ the app has one). Never echo the value, commit it, or put it in client
115
+ code. Reply only that it is saved, then ask the next question.
116
+ 3. **Second message — swaps.** If the user asked for stablecoins, USDT, USDC,
117
+ ETH, SOL, altcoins or "crypto" (as in "Bitcoin and stablecoin payments"),
118
+ this message IS the walkthrough below: send it as it is, and do not ask yes
119
+ or no first. Otherwise ask whether payers should also be able to pay with
120
+ USDT, USDC, ETH or SOL, then give the walkthrough. The walkthrough:
121
+
122
+ > Go to https://lightning-swap.com, sign in for API keys, create a key, and
123
+ > copy the whole URI (https://openreceive.org/set_up_swap_provider). Paste
124
+ > it here and I will store it — or say "Bitcoin only" and I will continue
125
+ > without it.
126
+
127
+ Mention FixedFloat only if they already use it.
128
+ 4. **When they paste it.** If it does not start with
129
+ `lightning+swapconnect://`, ask them to copy it again. Otherwise add
130
+ `LSC_URI_PRIMARY=<paste>` to the same `.env` with the file-editing
131
+ tool, never a shell command. Swaps are now on, so build the refund route
132
+ back (the swap non-negotiable below) as part of this integration. If they
133
+ chose Bitcoin only, leave `LSC_URI_PRIMARY` unset and skip that route.
134
+ 5. **Make the server load the file — yourself.** OpenReceive reads
135
+ `process.env`. `vite dev` loads `.env` into it, but the built server does
136
+ not: start it with `node --env-file=.env .output/server/index.mjs`. When
137
+ the app is started with Docker Compose, give the service `env_file: .env`.
138
+ Never give a code a `VITE_` prefix: that puts it in the browser bundle.
139
+ Restart the server after writing the file.
140
+ Under Compose, recreate the container with `docker compose up -d`:
141
+ `docker compose restart` keeps its old environment.
142
+
143
+ Do not invent placeholder URIs. Start the quickstart only once `NWC_URI` is
144
+ saved and `LSC_URI_PRIMARY` is saved or explicitly declined. The first boot
145
+ runs the receive-only preflight: if it reports spend methods such as
146
+ `pay_invoice`, remove `NWC_URI` from `.env` and ask for a receive-only code
147
+ again. Never set the spend-capable override to get past it.
148
+
149
+ ### Upgrading an existing install
150
+
151
+ This is not the opening move of a new integration. When OpenReceive is ALREADY
152
+ installed here, `npx openreceive doctor` reports every credential as set/unset
153
+ (never the value) and probes the wallet. Check the installed
154
+ `@openreceive/node` and `@openreceive/browser` against the release named at the
155
+ top of this file: the headless display models below do not exist in older
156
+ versions, and the first tile click throws with nothing saying why. Upgrade
157
+ first.
158
+
159
+ Only then start the quickstart.
160
+
161
+ ## After the quickstart — hand over, then stop
162
+
163
+ The quickstart is done when
164
+ `npx openreceive doctor --db <file-or-url> --url <app url>` is clean and this
165
+ app serves the checkout page for one of its orders. Doctor names any failed
166
+ check and exits nonzero; fix it before going on.
167
+ Doctor reads `.env` itself. Never source it into a shell: the `&` in a
168
+ code splits the value and prints the pieces.
169
+
170
+ Give the user that checkout link. The browser check of that page
171
+ (payment-method icons, wallet logos, a pay tutorial) is theirs: name it in one
172
+ line of your closing message, and do not run it yourself.
173
+
174
+ You cannot pay the invoice: the code is receive-only. Do not pay, settle or
175
+ mark an order paid, and do not look for a way to (a wallet control port, a
176
+ test endpoint, another wallet). If the user wants a real settlement test, they
177
+ pay on that link from their own wallet, and `onPaid` marks the order paid.
178
+
179
+ Setup ends here. Your last message starts "Setup is finished" and has at most
180
+ five short lines (about 80 characters each): the link, the methods it offers,
181
+ and one line of what to look at. Send nothing after it. Do not list what
182
+ changed, copy out the quickstart's browser checklist, offer more work, or end
183
+ the message on a question.
184
+
185
+ - The link is to a real unpaid order. Keep that order; do not delete it.
186
+ - When this app's orders belong to a session or cookie, the user's browser
187
+ cannot open the order you made. Then the link is the shop's own page:
188
+ "Open <shop url> and click Buy: it opens the checkout." Do not explain order
189
+ ownership or mention your test order.
190
+ - Name the methods it offers: Bitcoin, plus USDT, USDC, ETH and SOL when
191
+ `LSC_URI_PRIMARY` is saved. Do not mention minimums, and never say a coin
192
+ will not work or will not be offered.
193
+
194
+ ## Non-negotiables
195
+
196
+ The quickstart below has the code. These are the rules it cannot state for
197
+ itself, and they hold for every integration.
198
+
199
+ - OpenReceive never owns orders, users, prices, or fulfillment. The section
200
+ below is how those tables sit next to the library — not a second order model,
201
+ and not a Prisma/Drizzle relation to `openreceive_payments`.
202
+ - Keep `NWC_URI` / `LSC_URI_*` server-only. Never put them in browser code,
203
+ logs, or assets.
204
+ - Do not suggest rotating, revoking or replacing a code because it was pasted
205
+ into this chat; that is the supported path.
206
+ - Work only in this application. Never read or run anything from another
207
+ project on this machine (its `node_modules`, tools or source), for any
208
+ reason. A browser and Playwright are not part of setup.
209
+ - Restart only this app's server, on the port it already uses: stop the
210
+ process you started, or the one listening on that port, by its pid (or
211
+ restart its Compose service). Never `pkill` or `killall` by name: that
212
+ stops other people's servers too. Start it the way this project already
213
+ does (its README, Procfile, compose file or package script), on its own
214
+ port, not a port you pick.
215
+ - Run commands where the app runs. When a compose file builds it, run its
216
+ package manager, generators, migrations and doctor inside that service
217
+ (`docker compose exec` or `run`), and rebuild the image after adding a
218
+ package. This machine's language version and database path are not the
219
+ app's.
220
+ - To check that the running app sees the codes, run doctor: it reports each
221
+ one as present or missing and never prints a value. Never print the
222
+ environment (`printenv`, `env`, `docker compose config`), even filtered to
223
+ names.
224
+ - The host owns the price. `amountFor` reads it from your own data; reject
225
+ payer-supplied amounts.
226
+ - `authorize` runs on every request, and the `resource` it receives is a CLAIM
227
+ the payer made, not proof. Read a framework session; never trust a body field.
228
+ - `onPaid` must be idempotent. Its database fulfillment commits once per `reference` — your order id, one
229
+ per thing you fulfill, created before checkout, kept across retries, never
230
+ reused. A fresh id per page load lets one order be paid twice.
231
+ - Receive-only NWC is required; a spend-capable code fails closed at boot unless
232
+ explicitly overridden.
233
+ - There is NO merchant-initiated refund of a settled Lightning payment, because
234
+ the wallet cannot spend. Swap refunds — a payer reclaiming a deposit that
235
+ never converted — are the only refund OpenReceive performs, and only from the
236
+ `refund_required` provider state. Do not build, promise, or imply a Lightning
237
+ refund path.
238
+ - IF YOU TURN SWAPS ON, BUILD THE ROUTE BACK. A deposit that arrives short or
239
+ late becomes `refund_required`, and the payer claims it on a SECOND VISIT,
240
+ after leaving your page to fetch an address from another wallet. Three things
241
+ must exist or that money is unreachable through your UI: a per-order URL your
242
+ server serves (`/checkout/:reference` — `syncUrl` on `<Checkout>`, `sync-url`
243
+ or `resumable` on `<openreceive-checkout>`), your own order-summary route to
244
+ restore the order from, and the ATTEMPT.
245
+ `/checkouts/prepare` returns no attempts, so a checkout rebuilt from the
246
+ reference alone opens on the method grid. Re-picking the same coin
247
+ (`POST /swaps`) re-serves the committed attempt — but only while it is live,
248
+ and the shadow invoice behind a swap lasts about half an hour, after which the
249
+ same click mints a NEW deposit address and the refund is off-screen. Keep the
250
+ `payment_hash` and reopen the attempt with `POST /swaps/status`, which has no
251
+ such window. On the drop-ins: `resumePaymentHash`, fed from `onState`, on
252
+ `<Checkout>`; the `resume-payment-hash` attribute, fed from the
253
+ `openreceive-state` event (`event.detail.state.payment_hash`), on
254
+ `<openreceive-checkout>`.
255
+ That visit can come hours later, and `authorize` must still know the payer:
256
+ a session that expired in between answers 403 and strands the deposit. On a
257
+ guest shop, tie the order to a long-lived signed cookie, or put a secret
258
+ per-order token in its URL that your page trades for that cookie.
259
+ https://openreceive.org/guides/swap-refunds.md
260
+ - Show the payer WHAT THEY ARE BUYING. Return an optional `description` beside
261
+ the price from `amountFor` and both drop-ins render it above the amount.
262
+ Without it the checkout is a QR and "$1.00" with no sign of what the dollar
263
+ is for.
264
+ - Show the payer the transaction record: `createTransactionDetails(...)` rows,
265
+ collapsed behind a caret, on the live checkout AND on the receipt. A payment
266
+ hash and a deposit txid are the only evidence a payer has that they paid you.
267
+ `<Checkout>` / `<openreceive-checkout>` already render this panel and the
268
+ `description` — these two rules cost you code only on a custom UI or your own
269
+ receipt page, never a reason to replace the drop-in. (It returns no rows
270
+ while the rail is `checkout_lock` — before the payer has chosen anything
271
+ there is no transaction — so render the caret only when the rows are
272
+ non-empty.)
273
+ - On Node, build the stack ONCE, on the first request, around the app's
274
+ existing `pg` Pool, in a `.server.ts` module that the route loads with a
275
+ dynamic `import()` (route files are also bundled for the browser). The
276
+ recipe below builds a pool and a stack per request and closes both: that is
277
+ for Cloudflare Workers, which tie a socket to its request. On Node it would
278
+ open a new wallet connection for every request. So, in place of the recipe's
279
+ `handleOpenReceive`:
280
+
281
+ ```ts
282
+ // src/lib/openreceive.server.ts — on Node: one stack for the process
283
+ import { createStack, type Stack } from "@openreceive/http";
284
+ import { getRequestIP } from "@tanstack/react-start/server";
285
+ import { db } from "./db.server"; // the app's existing pg Pool
286
+
287
+ let stack: Stack | undefined;
288
+
289
+ export function handleOpenReceive(request: Request): Promise<Response> {
290
+ stack ??= createStack({
291
+ wallet: { nwc: process.env.NWC_URI ?? "" },
292
+ storage: { db, onPaid }, // onPaid, amountFor, authorize: as in the recipe
293
+ amountFor,
294
+ authorize,
295
+ rateLimiting: { ip: () => getRequestIP() }, // the socket address
296
+ });
297
+ return stack.handler(request, { native: request });
298
+ }
299
+ ```
300
+
301
+ Keep the recipe's route file as it is. Skip its On Supabase (Lovable)
302
+ section.
303
+ - `authorize` runs inside the request, so the app's own cookie and session
304
+ helpers work there (`getCookie()` from `@tanstack/react-start/server`, or
305
+ the helper its server functions use). `getRequestIP()` is the socket
306
+ address. Behind your own reverse proxy, which sets `x-forwarded-for`, use
307
+ `getRequestIP({ xForwardedFor: true })` instead; never read that header
308
+ without such a proxy, because a client can send it.
309
+ - `<Checkout>` comes from `@openreceive/react`, with
310
+ `@openreceive/react/styles.css`, on the order's own page: its resumable URL.
311
+ - HTTP JSON is snake_case; TypeScript APIs are camelCase.
312
+ - Money is integers or decimal strings — never binary floats.
313
+
314
+ ## Your tables, not ours
315
+
316
+ `npx openreceive scaffold payments` emits `openreceive_payments` and
317
+ `openreceive_meta` for THIS application's database. That is the whole
318
+ persistence OpenReceive needs. It does not replace your orders, users, or
319
+ products, and you do not join them.
320
+
321
+ - **Find this app's models first.** They may be named `Order`, `Invoice`,
322
+ `Booking`, `Product`, `Variant`, `User`, `Account` — anything. Wire the hooks
323
+ to those. Do not generate a parallel `ShopOrder` / `ShopProduct` / `ShopUser`
324
+ stack.
325
+ - **The payable row's id is the `reference`.** Create it before checkout, keep
326
+ it across retries, never reuse it. Pass that id to `<Checkout>` /
327
+ `<openreceive-checkout>`. A fresh id per page load lets one order be paid
328
+ twice.
329
+ - **Products (or the catalog) are the price authority.** Order creation reads
330
+ live prices into the order (snapshot line items if this app has them).
331
+ `amountFor` reads only that order — never a payer-supplied amount, never a
332
+ live catalog lookup that could re-price a cart already placed. Return
333
+ `{ currency, value }` as a decimal STRING, plus a `description` of what they
334
+ are buying.
335
+ - **Users own the order; OpenReceive never sees them.** `authorize` uses the
336
+ same ownership check this app already uses on the order show / pay page —
337
+ the cookie or session helper its server functions use, given the incoming
338
+ `request`, whatever it is.
339
+ `resource.reference` is a claim the payer sent, not proof.
340
+ - **The order is unpaid or paid.** Do not copy `pending` / `expired` / `failed`
341
+ / `attention` onto it. Those are attempt statuses on `openreceive_payments`. An
342
+ expired invoice does not cancel the order; a later checkout may mint another
343
+ attempt. The library refuses a new checkout under a reference that already
344
+ settled (409).
345
+ - **A paid order's page says it is paid and shows no checkout.** Nothing is left
346
+ to pay, and a checkout cannot start a new payment for a paid order. Mount the
347
+ checkout only while the order is unpaid. When it settles on the page, update
348
+ the page's status line from `onSettled` on `<Checkout>`: `onPaid` has already
349
+ marked the order paid. Keep that checkout mounted, because it is the payer's
350
+ receipt.
351
+ - **Pass this app's `db` handle.** Do not add a Prisma/Drizzle relation from
352
+ Order to `openreceive_payments`, and do not implement `PaymentRepository`
353
+ unless no supported handle can reach this database. `reference` is not unique
354
+ (many attempts per order). Fulfillment is a guarded transition on YOUR order
355
+ row inside `onPaid` — `UPDATE … WHERE state = 'awaiting_payment'` (or this
356
+ app's equivalent) through the `query` the library hands you, on that same
357
+ settlement transaction, not a second connection from your ORM. Database writes
358
+ only in the hook; emails, jobs, and pushes after commit. Placeholder style is
359
+ the dialect you declared: `?` on sqlite, `$1` on postgres.
360
+
361
+ ### If the database is Supabase
362
+
363
+ Supabase is Postgres, so the tables above go there like any others. Three
364
+ things differ; https://openreceive.org/guides/supabase.md has each in full.
365
+
366
+ - Connect through its transaction pooler (port `6543`, user
367
+ `postgres.<project-ref>`). Run migrations through the session pooler
368
+ (port `5432` on the same host).
369
+ - Verify Supabase's certificate authority: delete `sslmode` from the URL and
370
+ give `pg` `ssl: { ca }`, the text of the project's `prod-ca-2021.crt` (an
371
+ environment variable such as `SUPABASE_CA_CERT`; it is not a secret). Never
372
+ `rejectUnauthorized: false`.
373
+ - After the migration, close both tables to Supabase's Data API, or anyone
374
+ with the project's anon key can read `swap_data`:
375
+
376
+ ```sql
377
+ alter table openreceive_payments enable row level security;
378
+ alter table openreceive_meta enable row level security;
379
+ revoke all on table openreceive_payments, openreceive_meta from anon, authenticated;
380
+ ```
381
+
382
+ `npx openreceive scaffold payments --supabase` writes the HTTPS-API route,
383
+ which is for Cloudflare Workers only. A Node server uses the connection above.
384
+
385
+ ## If you build your own checkout UI
386
+
387
+ The drop-ins (`<Checkout>`, `<openreceive-checkout>`) already obey all of this.
388
+ This list is the short form of https://openreceive.org/guides/checkout-ux.md, for a
389
+ UI built on `@openreceive/browser/headless`. Read that before writing
390
+ components.
391
+
392
+ - Check Bitcoin → Switch payment method → Bitcoin: the grid must hide the
393
+ Lightning invoice, then restore the same bolt11 without another mint.
394
+ - `createCheckoutController` is the engine. Do not hand-roll a poll loop.
395
+ - `createCheckoutStatusModel` for the status line. Do not draw a
396
+ Cart → Pay → Done stepper. Read the model's `phase`, not the snapshot's.
397
+ - `resolveWizardSelection` decides whether to ask "which network?". A
398
+ one-network asset starts the swap from the tile. Key `selectedAssetByGroup`
399
+ by group (`USDT`), valued by `pay_in_asset` (`USDT_TRON`).
400
+ - `createMethodGridDisplay` for tiles, including `limitMessage` so an
401
+ unavailable method says the minimum in the payer's currency.
402
+ - `createSwapDisplayModel` → `display.copyRows` for deposits: address, memo,
403
+ and the bare amount each get a copy row. Render `swap.networkWarning*` as
404
+ the model gives it.
405
+ - `swap.deposit_amount` is the only amount a payer is told to send. Never put
406
+ a fiat valuation of it (`swap.fee.pay_in_fiat`) next to a stablecoin amount:
407
+ "$50.03" under "50.05 USDC" reads as a typo, and the payer asks which one to
408
+ send. The one fiat figure on a USDT/USDC deposit panel is the cart total
409
+ (`payout_fiat`); express "you send" and the fee in the token. Use
410
+ `createSwapFeeBreakdown(fee, swap)` — with the swap, not the fee alone — and
411
+ it applies this for you; SOL and ETH keep a fiat breakdown.
412
+ - `createCheckoutSession` owns mint and swap start. To start swaps, pass its
413
+ `swap` option (`selection`, `prefix`, `fetch`) together. Without it
414
+ `startSwap` reports through `onError`.
415
+ - `createQrSvg` is async. Use `createQrSvgController` so you do not render
416
+ `[object Promise]`.
417
+ - `checkoutLabels` for every payer-facing string. Only write copy it lacks.
418
+ - `stageSwapRefund` then `confirmSwapRefund` — only the second submits.
419
+ Validate with `getSwapRefundFormError`. Treat `409` as a normal outcome.
420
+ - Pass `{ resumable: true }` to `createSwapDisplayModel` when the payer has
421
+ a URL they can come back to, and render `display.refundReturnLabel`.
422
+ Resume helpers (`createGuestCheckoutResume`, `createGuestOrderFetcher`)
423
+ are on `@openreceive/browser`, not `/headless`.
424
+ - A refund replaces the deposit panel. On `refund_required` also drop
425
+ "switch payment method".
426
+ - No "Open wallet" button on desktop.
427
+ - Wallet suggestions: `getPaymentWizardRoutes()` +
428
+ `createWizardRouteDisplays`. Lightning only. Logos are data URIs; tutorial
429
+ images load from a JavaScript chunk. For a custom headless UI, load it when
430
+ a tutorial opens and look up the returned table by the tutorial's `path`:
431
+
432
+ ```js
433
+ import { loadPayTutorialImages } from "@openreceive/browser/headless";
434
+
435
+ const images = await loadPayTutorialImages();
436
+ const src = images[tutorial.path]; // data URI for the selected tutorial
437
+ ```
438
+
439
+ Render `src` as the image source and update your UI after loading. Existing
440
+ display objects do not update: their `tutorial.image` stays `undefined` if
441
+ created before loading. Alternatively, await the loader, recreate the displays
442
+ with `createWizardRouteDisplays`, and render the new `tutorial.image`.
443
+ Show the caption while loading or if loading fails; never use an empty image
444
+ source. Deploy all JavaScript chunks and allow `data:` in CSP `img-src`.
445
+ For missing images, check CSP errors, failed chunks, and stale displays.
446
+ Registry paths are lookup keys; there is no asset option or image route.
447
+
448
+ ## More documentation
449
+
450
+ Fetch one when the moment comes. Each is raw markdown, so a plain GET is
451
+ enough; drop the `.md` for the same page a person would read.
452
+
453
+ - https://openreceive.org/guides/authorization.md — before you write `authorize`
454
+ - https://openreceive.org/guides/environment-variables.md — every variable, and what is deliberately not one
455
+ - https://openreceive.org/guides/storage.md — the payment tables and the attempt state machine
456
+ - https://openreceive.org/guides/supabase.md — when the database is Supabase: its pooler, its certificate, and locking the tables away from its Data API
457
+ - https://openreceive.org/guides/serverless.md — when the app runs serverless (Netlify, AWS Lambda, Cloud Run, Google AI Studio): pooled database URLs, timeouts, and why it needs no cron or worker
458
+ - https://openreceive.org/guides/node-orms.md — recipes for Prisma, Drizzle, Knex, TypeORM, Sequelize
459
+ - https://openreceive.org/guides/frontend-checkout.md — the drop-in's props, attributes and slots
460
+ - https://openreceive.org/guides/mobile-apps.md — when a mobile app takes the payment: the checkout page it opens, and what the App Store and Google Play allow
461
+ - https://openreceive.org/guides/checkout-ux.md — read before building any custom UI
462
+ - https://openreceive.org/guides/headless-checkout.md — the controller, the display models, refunds
463
+ - https://openreceive.org/guides/provider-registry.md — where the wallet logos and pay
464
+ tutorials come from: inside the JavaScript, nothing to serve. This is the page
465
+ that owns the image rule, not the summary in checkout-ux.md
466
+ - https://openreceive.org/guides/automated-swaps.md — only if `LSC_URI_PRIMARY` is set
467
+ - https://openreceive.org/guides/swap-refunds.md — the refund flow, and the route back to it. Read it before you turn swaps on
468
+ - https://openreceive.org/guides/lightning-swap-connect.md — what an `LSC_URI_*` code actually is
469
+ - https://openreceive.org/guides/price-feeds.md — where the fiat→sats rate comes from, and how to replace it
470
+ - https://openreceive.org/guides/host-testing.md — testing your three hooks without a live wallet or provider
471
+ - https://openreceive.org/guides/rate-limiting.md — before a public shop goes live
472
+ - https://openreceive.org/guides/security.md and https://openreceive.org/guides/deploying.md — before this goes anywhere real
473
+ - https://openreceive.org/guides/api-reference.md — every route, option and error code
474
+ - https://openreceive.org/guides/custom-checkout-route.md — advanced: replacing the shipped adapter's routes with your own
475
+ - https://openreceive.org/guides/react-material-ui-recipe.md — a worked custom UI on a component library
476
+ - https://openreceive.org/guides/quickstart-next.md — each hook explained step by step, on Next.js; they are the same here
477
+ - https://openreceive.org/guides.md — the index, if what you need is not above
478
+
479
+ Questions, or a problem with the library itself:
480
+ https://openreceive.org/contact
481
+
482
+ - https://openreceive.org/guides/payment-safety-upgrade.md — coordinated upgrades and reviewed repair of existing attempts
483
+
484
+ ---
485
+
486
+ ## The quickstart, in full
487
+
488
+ Inlined verbatim so this file needs no network access. On Node, the one-stack module in the non-negotiables above replaces its per-request handleOpenReceive, and its On Supabase (Lovable) section does not apply.
489
+ The page it comes from is https://openreceive.org/guides/tanstack-start-recipe.
490
+
491
+ ## TanStack Start recipe
492
+
493
+ OpenReceive ships no TanStack Start package. A TanStack Start server route
494
+ takes a Web-standard `Request` and returns a `Response`, and so does
495
+ `@openreceive/http`, so the integration is the route below. Your server code
496
+ creates each Lightning invoice, the payment goes straight to your wallet, and
497
+ payment attempts are stored in your app's Postgres database. There is no
498
+ OpenReceive account and no background worker.
499
+
500
+ Optional swaps let customers pay with **USDT, USDC, SOL, and ETH**. A swap
501
+ provider you configure converts the payment to **BTC over Lightning**, and it
502
+ settles into the same wallet. Available assets and networks depend on the
503
+ provider.
504
+
505
+ This recipe was checked with `@tanstack/react-start` 1.168 and
506
+ `@openreceive/*` 0.4.19. The app was built with Lovable's Vite config for
507
+ Cloudflare Workers and run under workerd: a buyer's checkout showed a real
508
+ Lightning invoice, and a stranger was refused. The Supabase route below runs
509
+ in OpenReceive's CI as a Worker, against Supabase's own Postgres image and
510
+ API server: a buyer's invoice, a stranger refused, one live attempt under
511
+ concurrent requests, and a payment that `openreceive_on_paid` fulfills once.
512
+
513
+ ```sh
514
+ npm install @openreceive/http @openreceive/react pg
515
+ ```
516
+
517
+ ### Where it runs
518
+
519
+ - **Node** (the `node-server` preset, or any Node host): any Postgres.
520
+ - **Cloudflare Workers** (the `cloudflare-module` preset, Lovable's default):
521
+ with Node compatibility, and a Postgres whose certificate a public
522
+ authority signed, such as Neon.
523
+ - **Cloudflare Workers with Supabase**, which is every Lovable app: a Worker
524
+ cannot open a Postgres connection to Supabase, whose certificate comes from
525
+ a private authority. Use [On Supabase](#on-supabase-lovable) below, which
526
+ stores payments through Supabase's HTTPS API instead.
527
+
528
+ Workers ties every socket to the request that opened it, and forbids network
529
+ calls at import. So the route builds its database pool and its OpenReceive
530
+ stack inside each request, and closes both before it responds. Each request
531
+ then opens its own wallet connection; in our test a checkout request took one
532
+ to four seconds. The same code works on Node.
533
+
534
+ ### The payment route
535
+
536
+ Keep the handler in a `.server.ts` module. Route files are also bundled for
537
+ the browser, so the route loads the module only when a request arrives:
538
+
539
+ ```ts
540
+ // src/routes/openreceive.$.ts — every route under /openreceive/
541
+ import { createFileRoute } from "@tanstack/react-router";
542
+
543
+ async function openReceive({ request }: { request: Request }): Promise<Response> {
544
+ const { handleOpenReceive } = await import("@/lib/openreceive.server");
545
+ return handleOpenReceive(request);
546
+ }
547
+
548
+ export const Route = createFileRoute("/openreceive/$")({
549
+ server: { handlers: { GET: openReceive, POST: openReceive } },
550
+ });
551
+ ```
552
+
553
+ ```ts
554
+ // src/lib/openreceive.server.ts
555
+ import { createStack } from "@openreceive/http";
556
+ import pg from "pg";
557
+ import { findOrder, currentVisitor } from "./orders.server"; // your own orders
558
+
559
+ export async function handleOpenReceive(request: Request): Promise<Response> {
560
+ // Read process.env inside the handler: on Workers it is empty at import.
561
+ const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 1 });
562
+ const stack = createStack({
563
+ wallet: { nwc: process.env.NWC_URI ?? "" },
564
+ storage: {
565
+ db: pool,
566
+ // Runs once, inside the transaction that records the payment.
567
+ onPaid: async ({ reference, paidAt, query }) => {
568
+ await query(
569
+ "UPDATE orders SET state = 'paid', paid_at = $1 WHERE id = $2 AND state = 'awaiting_payment'",
570
+ [paidAt, reference],
571
+ );
572
+ },
573
+ },
574
+ // The price comes from the order row, never from the request.
575
+ amountFor: async (reference) => {
576
+ const order = await findOrder(pool, reference);
577
+ return order?.state === "awaiting_payment"
578
+ ? { currency: order.currency, value: order.amount, description: order.title }
579
+ : null;
580
+ },
581
+ // Only the buyer may pay for their order.
582
+ authorize: async ({ request: incoming, resource }) => {
583
+ const order = resource.reference ? await findOrder(pool, resource.reference) : undefined;
584
+ const visitor = currentVisitor(incoming);
585
+ return Boolean(order && visitor && order.visitor === visitor);
586
+ },
587
+ // Cloudflare sets cf-connecting-ip on every request, and a client cannot.
588
+ // On Node behind your own proxy, read the header that proxy sets.
589
+ rateLimiting: {
590
+ ip: ({ request: incoming }) => incoming.headers.get("cf-connecting-ip") ?? undefined,
591
+ },
592
+ });
593
+ try {
594
+ return await stack.handler(request, { native: request });
595
+ } finally {
596
+ await stack.close();
597
+ await pool.end();
598
+ }
599
+ }
600
+ ```
601
+
602
+ `authorize` sees the incoming request with its cookies, so check it with
603
+ the session your app already has. The Next.js quickstart
604
+ explains each hook. They are the same here.
605
+
606
+ Create OpenReceive's two tables with your migrations, or run
607
+ `paymentsSchemaSql("postgres")` from `@openreceive/http` once. It is
608
+ idempotent. See Payment storage.
609
+
610
+ ### On Supabase (Lovable)
611
+
612
+ On Supabase the route keeps payments in your Supabase database through its
613
+ HTTPS API, with the project's secret key. There is no `pg` pool. Use
614
+ `@openreceive/*` 0.4.24 or newer:
615
+
616
+ ```sh
617
+ npm install @openreceive/http @openreceive/react
618
+ ```
619
+
620
+ 1. Apply the migration from `npx openreceive scaffold payments --supabase`.
621
+ It creates OpenReceive's tables, locked away from the browser's Supabase
622
+ key, and the functions that write them.
623
+ 2. Replace its placeholder `openreceive_on_paid` with the SQL that marks your
624
+ order paid. It runs inside the transaction that records the payment, for
625
+ the order's first payment only, so a failure there records nothing:
626
+
627
+ ```sql
628
+ create or replace function public.openreceive_on_paid(
629
+ p_reference text, p_payment_hash text, p_paid_at bigint
630
+ ) returns void language plpgsql as $$
631
+ begin
632
+ update public.orders set status = 'paid'
633
+ where id = p_reference::uuid and status = 'pending';
634
+ end
635
+ $$;
636
+ ```
637
+
638
+ 3. Write the route's server module:
639
+
640
+ ```ts
641
+ // src/lib/openreceive.server.ts
642
+ import { createStack } from "@openreceive/http";
643
+ import { findOrder, currentBuyer } from "./orders.server"; // your own orders
644
+
645
+ export async function handleOpenReceive(request: Request): Promise<Response> {
646
+ // Read process.env inside the handler: on Workers it is empty at import.
647
+ // Lovable sets SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY for server code.
648
+ const stack = createStack({
649
+ wallet: { nwc: process.env.NWC_URI ?? "" },
650
+ storage: {
651
+ supabase: {
652
+ url: process.env.SUPABASE_URL ?? "",
653
+ key: process.env.SUPABASE_SERVICE_ROLE_KEY ?? "",
654
+ },
655
+ },
656
+ // The price comes from the order row, never from the request.
657
+ amountFor: async (reference) => {
658
+ const order = await findOrder(reference);
659
+ return order?.status === "pending"
660
+ ? { currency: order.currency, value: order.total, description: order.title }
661
+ : null;
662
+ },
663
+ // Only the buyer may pay for their order.
664
+ authorize: async ({ request: incoming, resource }) => {
665
+ const order = resource.reference ? await findOrder(resource.reference) : null;
666
+ const buyer = currentBuyer(incoming);
667
+ return Boolean(order && buyer && order.buyer_token === buyer);
668
+ },
669
+ rateLimiting: {
670
+ ip: ({ request: incoming }) => incoming.headers.get("cf-connecting-ip") ?? undefined,
671
+ },
672
+ });
673
+ try {
674
+ return await stack.handler(request, { native: request });
675
+ } finally {
676
+ await stack.close();
677
+ }
678
+ }
679
+ ```
680
+
681
+ There is no `onPaid`: `openreceive_on_paid` is the fulfillment. `findOrder`
682
+ reads the order with your server-side Supabase client; in a Lovable app that
683
+ is `supabaseAdmin` from `@/integrations/supabase/client.server`.
684
+
685
+ The checkout calls the payment routes from the browser with the page's
686
+ cookies, and nothing else. A Lovable app keeps its Supabase sign-in in the
687
+ browser, not in a cookie, so `authorize` cannot see who is signed in. Give
688
+ the buyer a cookie of their own instead: create orders in a server function
689
+ that sets an HttpOnly `buyer` cookie (a random value, kept across orders) and
690
+ stores the same value on the order as `buyer_token`. `currentBuyer` reads it
691
+ back from the request's `cookie` header.
692
+
693
+ Before it serves, the server checks the database, and the payment routes
694
+ answer 503 until the migration is applied and `openreceive_on_paid` is
695
+ yours; the log names the fix. More: Supabase over HTTPS.
696
+
697
+ ### The checkout page
698
+
699
+ ```tsx
700
+ // src/routes/checkout.$reference.tsx
701
+ import { Checkout } from "@openreceive/react";
702
+ import "@openreceive/react/styles.css";
703
+ import { createFileRoute } from "@tanstack/react-router";
704
+
705
+ export const Route = createFileRoute("/checkout/$reference")({
706
+ component: OrderCheckout,
707
+ });
708
+
709
+ function OrderCheckout() {
710
+ const { reference } = Route.useParams();
711
+ return <Checkout reference={reference} prefix="/openreceive" />;
712
+ }
713
+ ```
714
+
715
+ It renders on the server and starts the checkout in the browser. The payer
716
+ picks Bitcoin and gets the invoice.
717
+
718
+ ### Settings
719
+
720
+ - `NWC_URI`: a receive-only code from your wallet
721
+ ([get one](https://openreceive.org/get_a_nwc_code_to_receive_payments)).
722
+ Optional: `LSC_URI_PRIMARY` for swaps
723
+ ([set one up](https://openreceive.org/set_up_swap_provider)).
724
+ - `DATABASE_URL`: your Postgres. On serverless hosts use the pooled URL. The
725
+ storage is tested through a transaction pooler.
726
+ - On Supabase over HTTPS, instead of `DATABASE_URL`: `SUPABASE_URL` and the
727
+ secret key in `SUPABASE_SERVICE_ROLE_KEY`. Lovable sets both itself.
728
+
729
+ Set them as server secrets, never with a `VITE_` prefix, which would put them
730
+ in the browser bundle.
731
+
732
+ No worker or cron job is needed. Each request to the payment routes also
733
+ checks the wallet for settled invoices, through a lock in your database. A
734
+ payer who closes the tab is settled on the next request.