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