From 2cd42f811d33a74c3ca28094176c009c0388da9b Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 23 Nov 2026 09:22:47 -0700 Subject: A coinos name has a public pay page: v3.coinos.io//receive. "The old Coinos I could point this link onto my website give people the ability to Donate/Pay in Bitcoin and Lighting - https://coinos.io/JuryImagePro/receive - I'm not seeing an option to do this thru V3, am I missing something?" (JuryImagePro, relayed by Adam 2026-11-23). v3 had no page a visitor could pay a name from: tapping pay on a profile asks a visitor to sign in. //receive and //pay now open a small page of their own (dist/pay/index.html from src/pay-page.js, 39 KB, not the app): the name's face, a LNURL QR any Lightning wallet can pay with an amount picked there, the address to copy, and a form for a set amount and a note that makes an invoice (QR, copy, open in wallet). When coinos' node minted the invoice the page says Paid once it settles (LUD-21 verify, coinosv3-server e40c5eb); when the recipient's own wallet minted it, the page says to pay it from the wallet. ?amount= fills in the amount. Lightning only: a v3 name publishes no on-chain address. Receive → More options → Payment page shows the link with Copy and Open page. nginx on cs routes the two paths to the page; the service worker leaves them alone. New pay-page-test (set amount + note, Paid, no-verify invoice, minimum, unknown name) and names-pay-page-link-test pass; names-invoice-expiry, features-smoke and feature-registry-check pass. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VMan6Upic5L6MMJzkTn8zg --- build.js | 17 ++++ src/features/names.js | 20 ++++ src/i18n.js | 4 + src/pay-page.html | 67 ++++++++++++++ src/pay-page.js | 190 ++++++++++++++++++++++++++++++++++++++ tools/names-pay-page-link-test.js | 58 ++++++++++++ tools/pay-page-test.js | 84 +++++++++++++++++ 7 files changed, 440 insertions(+) create mode 100644 src/pay-page.html create mode 100644 src/pay-page.js create mode 100644 tools/names-pay-page-link-test.js create mode 100644 tools/pay-page-test.js diff --git a/build.js b/build.js index 8a1b05a..5ed5fd2 100644 --- a/build.js +++ b/build.js @@ -105,6 +105,8 @@ self.addEventListener('fetch', (e) => { if (u.pathname.startsWith('/live/') || u.pathname.startsWith('/vmedia/hls')) return; // The developer docs are their own page, not the app: never the offline shell. if (u.pathname === '/docs' || u.pathname.startsWith('/docs/')) return; + // Nor is a name's pay page (//receive): a visitor's page from the server. + if (/^\\/[^/]+\\/(receive|pay)\\/?$/i.test(u.pathname) || u.pathname.startsWith('/pay/')) return; if (req.mode === 'navigate') { // Opening the app (/, the installed app's and the Android app's start @@ -242,6 +244,19 @@ export async function buildJsQr({ minify = true } = {}) { return iife(await result.outputs[0].text()); } +// The public pay page (v3.coinos.io//receive): its own small +// document with the script inline, not the app. See src/pay-page.js. +export async function buildPayPage({ minify = true } = {}) { + const result = await Bun.build({ entrypoints: ['./src/pay-page.js'], target: 'browser', minify }); + if (!result.success) { + for (const log of result.logs) console.error(log); + throw new Error('pay page bundle failed'); + } + const js = iife(await result.outputs[0].text()).replace(/<\/script/gi, '<\\/script'); + const tpl = await Bun.file('./src/pay-page.html').text(); + return tpl.replace('/*PAY_PAGE_JS*/', () => js); +} + // Standalone bundle for the NIP-46 remote-signer client — loaded on demand by // nostr-login.js the first time a bunker/nostrconnect login happens. export async function buildNip46({ minify = true } = {}) { @@ -623,6 +638,8 @@ if (import.meta.main) { for (const f of readdirSync('static/' + d)) await Bun.write(`dist/${d}/${f}`, Bun.file(`static/${d}/${f}`)); // the developer docs, a plain page at /docs/ for (const f of readdirSync('static/docs')) await Bun.write(`dist/docs/${f}`, Bun.file(`static/docs/${f}`)); + // the public pay page, served by nginx for //receive and //pay + await Bun.write('dist/pay/index.html', await buildPayPage()); const kb = (Buffer.byteLength(html) / 1024).toFixed(0); const jkb = (Buffer.byteLength(rawJs) / 1024).toFixed(0); diff --git a/src/features/names.js b/src/features/names.js index e1f23ce..701b474 100644 --- a/src/features/names.js +++ b/src/features/names.js @@ -889,6 +889,23 @@ export function namesFeature(ctx) { h('p', { class: 'small muted', style: 'margin:0' }, t('namesZapCodeHow'))); } + // The public pay page (v3.coinos.io//receive, src/pay-page.js): the + // link a website puts behind its Donate button, as coinos.io//receive + // was on the old coinos. coinos.io names only: the page pays those. + function payPagePane() { + const st = load(); + const domain = st.domain || DOMAIN(); + if (!st.name || (domain !== 'coinos.io' && domain !== 'staging.coinos.io')) return h('div', { class: 'small muted' }, t('namesNeedArk')); + const host = domain === 'staging.coinos.io' ? location.origin : 'https://v3.coinos.io'; + const link = `${host}/${st.name}/receive`; + return h('div', { class: 'col', style: 'gap:10px;width:100%;align-items:center' }, + h('div', { class: 'addr-box break', style: 'width:100%' }, link), + h('div', { class: 'row gap6' }, + copyBtn(link, t('copy')), + h('button', { class: 'btn-ghost btn-sm', onClick: () => window.open(link, '_blank', 'noopener') }, t('namesPageOpen'))), + h('p', { class: 'small muted', style: 'margin:0' }, t('namesPageHow'))); + } + // ---- more options ------------------------------------------------------- // The address covers almost everyone; behind one link live the other codes // a payer might insist on. @@ -901,6 +918,7 @@ export function namesFeature(ctx) { h('strong', { class: 'small' }, label), h('span', { class: 'small muted' }, how)); return h('div', { class: 'list', style: 'width:100%' }, + opt('page', t('namesMorePage'), t('namesMorePageHow')), opt('bolt11', t('namesMoreBolt11'), t('namesMoreBolt11How')), opt('bolt12', t('namesMoreBolt12'), t('namesMoreBolt12How'), loadOffers), opt('ark', t('namesMoreArk'), t('namesMoreArkHow')), @@ -927,12 +945,14 @@ export function namesFeature(ctx) { ark: t('namesMoreArk'), clink: t('namesMoreClink'), ownnode: t('namesOwnNode'), + page: t('namesMorePage'), }; const body = ui.namesMore === 'bolt11' ? invoicePane() : ui.namesMore === 'bolt12' ? offerPane() : ui.namesMore === 'ark' ? arkPane() : ui.namesMore === 'clink' ? clinkPane() : ui.namesMore === 'ownnode' ? ownNodeSection() + : ui.namesMore === 'page' ? payPagePane() : menuPane(); return h('div', { class: 'col', style: 'gap:10px;width:100%' }, h('div', { class: 'row between', style: 'align-items:baseline' }, diff --git a/src/i18n.js b/src/i18n.js index 76efc72..e3a1ad7 100644 --- a/src/i18n.js +++ b/src/i18n.js @@ -1613,6 +1613,10 @@ const STR = { namesMoreArkHow: 'Get paid directly from any Ark wallet', namesMoreClink: 'Nostr offer (CLINK)', namesMoreClinkHow: 'A static code Nostr wallets can pay', + namesMorePage: 'Payment page', + namesMorePageHow: 'A link for your website: anyone can pay you over Lightning', + namesPageHow: 'Put this link behind a "Donate" or "Pay in Bitcoin" button. Whoever opens it can pay you over Lightning from any wallet, no account needed. Add ?amount=5000 to the link to fill in an amount.', + namesPageOpen: 'Open page', namesMoreOnchain: 'Bitcoin address (on-chain)', namesMoreOnchainHow: 'Switch to Savings for a regular on-chain address', namesInvAmountPh: 'Amount (sats)', diff --git a/src/pay-page.html b/src/pay-page.html new file mode 100644 index 0000000..87c4739 --- /dev/null +++ b/src/pay-page.html @@ -0,0 +1,67 @@ + + + + + + +Pay with Lightning · coinos + + + + + +
+ + +
Pay with Lightning
+
+
+

Loading…

+ +
+ + + diff --git a/src/pay-page.js b/src/pay-page.js new file mode 100644 index 0000000..d34b1a5 --- /dev/null +++ b/src/pay-page.js @@ -0,0 +1,190 @@ +// v3.coinos.io//receive (and //pay): a page anyone can open to +// pay a coinos name over Lightning, no wallet of their own on this site +// needed. The link a shop or a blog puts behind its "Donate / Pay in +// Bitcoin" button, as coinos.io//receive was on the old coinos +// ("The old Coinos I could point this link onto my website ... I'm not +// seeing an option to do this thru V3", JuryImagePro, relayed by Adam +// 2026-11-23). +// +// Its own small page, not the app: a visitor from a website should not +// boot a whole wallet to see a QR code. Everything comes from the names +// registrar's public LNURL-pay endpoints; the invoice is minted by the +// recipient's wallet when it is open, by coinos' node otherwise (forwarded +// on settle). Only the second can be watched (LUD-21 verify), so the page +// says "Paid" when it can and otherwise leaves it to the payer's wallet. +// +// On-chain is not offered: a v3 name publishes no on-chain address. + +import { bech32 } from '@scure/base'; +import { qrSvg } from './qr.js'; + +const REGISTRAR = 'https://names.coinos.io'; +const DOMAIN = /(^|\.)staging\./.test(location.hostname) ? 'staging.coinos.io' : 'coinos.io'; +const PROFILE_RELAYS = ['wss://relay.coinos.io', 'wss://purplepag.es', 'wss://relay.damus.io']; + +const $ = (id) => document.getElementById(id); +const el = (tag, attrs = {}, ...kids) => { + const n = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (v == null || v === false) continue; + if (k.startsWith('on')) n.addEventListener(k.slice(2).toLowerCase(), v); + else if (k === 'html') n.innerHTML = v; + else n.setAttribute(k, v === true ? '' : v); + } + for (const k of kids.flat()) if (k != null && k !== false) n.append(k); + return n; +}; +const fmt = (n) => Number(n).toLocaleString('en-US'); + +const m = location.pathname.match(/^\/([A-Za-z0-9_][A-Za-z0-9._-]{0,29})\/(?:receive|pay)\/?$/); +const name = m ? m[1].toLowerCase() : ''; +const address = `${name}@${DOMAIN}`; +const lnurlpUrl = `${REGISTRAR}/lnurlp/${encodeURIComponent(name)}?domain=${encodeURIComponent(DOMAIN)}`; +const params = new URLSearchParams(location.search); + +let payReq = null; // the name's LNURL-pay answer +let watch = null; // the verify poll for the invoice on screen + +async function getJson(url, ms = 10000) { + const r = await fetch(url, { signal: AbortSignal.timeout(ms) }); + const j = await r.json().catch(() => null); + if (!r.ok || !j || j.status === 'ERROR') throw new Error((j && j.reason) || `HTTP ${r.status}`); + return j; +} + +// The name's face: its nostr profile, best effort. The page works without it. +function fetchProfile(pk) { + return new Promise((resolve) => { + let best = null, left = PROFILE_RELAYS.length; + const socks = []; + const done = () => { for (const s of socks) try { s.close(); } catch {} resolve(best); }; + const timer = setTimeout(done, 2500); + for (const url of PROFILE_RELAYS) { + let ws; + try { ws = new WebSocket(url); } catch { if (!--left) { clearTimeout(timer); done(); } continue; } + socks.push(ws); + ws.onopen = () => ws.send(JSON.stringify(['REQ', 'p', { kinds: [0], authors: [pk], limit: 1 }])); + ws.onmessage = (e) => { + let msg; try { msg = JSON.parse(e.data); } catch { return; } + if (msg[0] === 'EVENT' && msg[2]?.pubkey === pk && (!best || msg[2].created_at > best.created_at)) best = msg[2]; + if (msg[0] === 'EOSE' || msg[0] === 'CLOSED') { ws.close(); if (!--left) { clearTimeout(timer); done(); } } + }; + ws.onerror = () => { if (!--left) { clearTimeout(timer); done(); } }; + } + }); +} + +async function copy(text, btn) { + try { await navigator.clipboard.writeText(text); } catch { + const ta = el('textarea', {}, text); document.body.append(ta); ta.select(); + try { document.execCommand('copy'); } catch {} ta.remove(); + } + const was = btn.textContent; + btn.textContent = 'Copied'; + setTimeout(() => { btn.textContent = was; }, 1500); +} + +function qrBox(data, label) { + return el('a', { class: 'qr', href: data, 'aria-label': label, html: qrSvg(data, { ec: 'L', mode: /^[0-9A-Z $%*+\-./:]+$/.test(data) ? 'Alphanumeric' : undefined }) }); +} + +function stopWatch() { if (watch) { clearInterval(watch); watch = null; } } + +// The start: the name's own QR (any amount, picked in the payer's wallet) +// and a form for a set amount. +function showStart() { + stopWatch(); + const lnurl = bech32.encode('lnurl', bech32.toWords(new TextEncoder().encode(lnurlpUrl)), 2000).toUpperCase(); + const minSat = Math.ceil((payReq.minSendable || 1000) / 1000); + const maxSat = Math.floor((payReq.maxSendable || 1e11) / 1000); + const amount = el('input', { id: 'amount', type: 'text', inputmode: 'numeric', placeholder: 'Amount in sats', autocomplete: 'off', value: params.get('amount') || null }); + const note = payReq.commentAllowed ? el('input', { id: 'note', type: 'text', maxlength: String(payReq.commentAllowed), placeholder: 'Note (optional)', value: params.get('memo') || params.get('note') || null }) : null; + const err = el('div', { class: 'err', id: 'err' }); + const go = el('button', { class: 'primary', type: 'submit' }, 'Create invoice'); + const form = el('form', { + class: 'amount-form', + onSubmit: async (e) => { + e.preventDefault(); + err.textContent = ''; + const sat = Number(String(amount.value).replace(/[\s,_]/g, '')); + if (!Number.isInteger(sat) || sat < minSat) { err.textContent = `Enter at least ${fmt(minSat)} sats.`; amount.focus(); return; } + if (sat > maxSat) { err.textContent = `At most ${fmt(maxSat)} sats.`; amount.focus(); return; } + go.disabled = true; go.textContent = 'Creating invoice…'; + try { await createInvoice(sat, note ? note.value.trim() : ''); } catch (x) { + err.textContent = 'Could not create an invoice: ' + (x.message || x); + } finally { go.disabled = false; go.textContent = 'Create invoice'; } + }, + }, el('label', { for: 'amount' }, 'Pay a set amount'), amount, note, go, err); + const copyBtn = el('button', { class: 'ghost', type: 'button', onClick: (e) => copy(address, e.currentTarget) }, 'Copy address'); + $('body').replaceChildren( + el('div', { class: 'card' }, + qrBox('lightning:' + lnurl, 'Open in a Lightning wallet'), + el('p', { class: 'hint' }, 'Scan with any Lightning wallet and pick the amount there.'), + el('div', { class: 'row' }, el('code', { class: 'addr' }, address), copyBtn)), + el('div', { class: 'card' }, form)); +} + +async function createInvoice(sat, comment) { + const u = new URL(payReq.callback); + u.searchParams.set('amount', String(sat * 1000)); + if (comment) u.searchParams.set('comment', comment); + const j = await getJson(u.toString(), 30000); + if (!j.pr) throw new Error('no invoice came back'); + showInvoice(sat, j.pr, j.verify || null); +} + +function showInvoice(sat, pr, verify) { + stopWatch(); + const status = el('div', { class: 'status', id: 'status' }, verify ? 'Waiting for payment…' : 'Pay it from your Lightning wallet.'); + const copyBtn = el('button', { class: 'ghost', type: 'button', onClick: (e) => copy(pr, e.currentTarget) }, 'Copy invoice'); + const open = el('a', { class: 'button primary', href: 'lightning:' + pr }, 'Open in wallet'); + const back = el('button', { class: 'link', type: 'button', onClick: showStart }, '← Another amount'); + $('body').replaceChildren(el('div', { class: 'card', id: 'invoice' }, + el('div', { class: 'big' }, fmt(sat), el('span', {}, ' sats')), + qrBox('lightning:' + pr.toUpperCase(), 'Open in a Lightning wallet'), + el('div', { class: 'row' }, copyBtn, open), + status, back)); + if (!verify) return; + const started = Date.now(); + watch = setInterval(async () => { + if (Date.now() - started > 15 * 60_000) { stopWatch(); status.textContent = 'This invoice has expired.'; return; } + try { + const v = await getJson(verify, 8000); + if (v.settled) { stopWatch(); paid(sat); } + } catch {} + }, 3000); +} + +function paid(sat) { + $('body').replaceChildren(el('div', { class: 'card done', id: 'paid' }, + el('div', { class: 'tick', 'aria-hidden': 'true' }, '✓'), + el('div', { class: 'big' }, 'Paid'), + el('p', {}, `${fmt(sat)} sats sent to ${address}. Thank you!`), + el('button', { class: 'link', type: 'button', onClick: showStart }, 'Pay again'))); +} + +async function main() { + if (!name) { $('body').replaceChildren(el('div', { class: 'card' }, el('p', {}, 'No such page.'))); return; } + $('who').textContent = address; + document.title = `Pay ${address}`; + let rec = null; + try { + [payReq, rec] = await Promise.all([getJson(lnurlpUrl), getJson(`${REGISTRAR}/name/${encodeURIComponent(name)}?domain=${encodeURIComponent(DOMAIN)}`).catch(() => null)]); + } catch (x) { + $('body').replaceChildren(el('div', { class: 'card' }, el('p', { class: 'err' }, + /unknown address/i.test(x.message) ? `${address} is not a coinos address.` : `Could not reach ${address} right now. Try again in a moment.`))); + return; + } + showStart(); + const pk = rec && /^[0-9a-f]{64}$/.test(rec.pubkey || '') ? rec.pubkey : null; + if (!pk) return; + $('profile-link').href = '/' + name; + const ev = await fetchProfile(pk); + let p = null; try { p = ev && JSON.parse(ev.content); } catch {} + if (!p) return; + const shown = String(p.display_name || p.name || '').trim().slice(0, 60); + if (shown) { $('display').textContent = shown; document.title = `Pay ${shown}`; } + if (/^https:\/\//.test(p.picture || '')) { const img = $('avatar'); img.src = p.picture; img.hidden = false; } +} + +main(); diff --git a/tools/names-pay-page-link-test.js b/tools/names-pay-page-link-test.js new file mode 100644 index 0000000..5e18a43 --- /dev/null +++ b/tools/names-pay-page-link-test.js @@ -0,0 +1,58 @@ +// Receive → More options → Payment page: the link to the name's public pay +// page (v3.coinos.io//receive, see pay-page-test), to copy or open. +// Run: bun tools/names-pay-page-link-test.js +import assert from 'node:assert/strict'; +import puppeteer from './puppeteer.js'; + +const app = await Bun.file('src/app.js').text(); +const domHelper = app.slice(app.indexOf('function h(tag,'), app.indexOf('// ---------------------------------------------------------------- morphing')); +const entry = ` +import { namesFeature } from './src/features/names.js'; +${domHelper} +const state = { names: { byDomain: { 'coinos.io': { name: 'alice', domain: 'coinos.io' } } } }; +const ui = { screen: 'wallet', namesMore: 'menu' }; +const wallet = { loadFeatureState: (k, d) => (k in state ? state[k] : d), saveFeatureState: (k, v) => { state[k] = v; }, nostrSign: async (e) => e, nostrPubkey: () => 'aa'.repeat(32), _cacheKey: () => 'w1' }; +const ctx = { + h, ui, wallet, render, toast: () => {}, copy: () => {}, copyBtn: (x, l) => h('button', { class: 'btn-sm' }, l), brandHeader: () => null, goBack: () => {}, setAccount: () => {}, + hook(name, ...a) { + if (name === 'arkReady') return true; + if (name === 'arkMakeInvoice') return Promise.resolve({ invoice: 'lnbc10u1testinvoice', amountSat: a[0], expiresAt: Date.now() + (window.__life || 3600_000) }); + return null; + }, +}; +const feature = namesFeature(ctx); +function render() { document.querySelector('#app').replaceChildren(feature.receiveModes()[0].render(h('div', { class: 'seg' }))); } +window.test = { render }; +render(); +`; +const bundle = await Bun.build({ + entrypoints: ['names-page-entry'], target: 'browser', + plugins: [{ name: 'names-page', setup(build) { + build.onResolve({ filter: /^names-page-entry$/ }, () => ({ path: 'entry', namespace: 'names-page' })); + build.onLoad({ filter: /.*/, namespace: 'names-page' }, () => ({ contents: entry, loader: 'js', resolveDir: process.cwd() })); + } }], +}); +assert(bundle.success, bundle.logs.join('\n')); +const html = `
`; +const server = Bun.serve({ port: 0, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errors = []; +page.on('pageerror', (e) => errors.push(e.message)); +const pause = (ms) => new Promise((r) => setTimeout(r, ms)); +const check = (name, value, detail = '') => { assert(value, name + (detail ? ' — ' + detail : '')); console.log(' ✓ ' + name); }; +const text = () => page.evaluate(() => document.body.innerText.replace(/\s+/g, ' ')); +try { + await page.goto(server.url.href); + await page.waitForFunction(() => /Payment page/.test(document.body.innerText)); + check('More options lists the payment page', /A link for your website/.test(await text())); + await page.evaluate(() => [...document.querySelectorAll('.item')].find((d) => /Payment page/.test(d.textContent)).click()); + await pause(50); + check('...which shows the link for this name', /https:\/\/v3\.coinos\.io\/alice\/receive/.test(await text()), await text()); + check('...with Copy and Open page', await page.evaluate(() => ['Copy', 'Open page'].every((l) => [...document.querySelectorAll('button')].some((b) => b.textContent.trim() === l)))); + check('no page errors', !errors.length, errors.join(' | ')); + console.log('\n✅ the payment page link is in More options'); +} finally { + await browser.close(); + server.stop(true); +} diff --git a/tools/pay-page-test.js b/tools/pay-page-test.js new file mode 100644 index 0000000..c463959 --- /dev/null +++ b/tools/pay-page-test.js @@ -0,0 +1,84 @@ +// v3.coinos.io//receive: a visitor pays a coinos name over Lightning +// from a page of its own (no wallet on this site). The registrar is faked. +// Run: bun tools/pay-page-test.js +import assert from 'node:assert/strict'; +import puppeteer from './puppeteer.js'; +import { buildPayPage } from '../build.js'; + +const page_ = await buildPayPage({ minify: true }); +const server = Bun.serve({ port: 0, fetch() { return new Response(page_, { headers: { 'Content-Type': 'text/html' } }); } }); +const PR = 'lnbc210n1pjtestinvoiceqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq'; +const PK = 'e21a18f58b31baee9291b295c24cbe7aa1787f141af4c7f513a40b4b80262a20'; +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const check = (name, ok, detail = '') => { assert(ok, name + (detail ? ' — ' + detail : '')); console.log(' ✓ ' + name); }; + +async function open(path, { verify = true } = {}) { + const page = await browser.newPage(); + const seen = { cb: [], verify: 0, errors: [] }; + page.on('pageerror', (e) => seen.errors.push(e.message)); + await page.setRequestInterception(true); + page.on('request', (r) => { + const u = new URL(r.url()); + const json = (o, status = 200) => r.respond({ status, contentType: 'application/json', headers: { 'Access-Control-Allow-Origin': '*' }, body: JSON.stringify(o) }); + if (u.origin === server.url.origin) return r.continue(); + if (u.host !== 'names.coinos.io') return r.abort(); + if (u.pathname === '/lnurlp/shopkeeper') return json({ tag: 'payRequest', callback: 'https://names.coinos.io/lnurlp/shopkeeper/cb?domain=coinos.io', minSendable: 1000, maxSendable: 500000000, metadata: '[]', commentAllowed: 200 }); + if (u.pathname === '/name/shopkeeper') return json({ name: 'shopkeeper', taken: true, pubkey: PK }); + if (u.pathname === '/lnurlp/shopkeeper/cb') { seen.cb.push(Object.fromEntries(u.searchParams)); return json({ pr: PR, routes: [], ...(verify ? { verify: 'https://names.coinos.io/lnurlp/verify/' + 'ab'.repeat(32) } : {}) }); } + if (u.pathname.startsWith('/lnurlp/verify/')) { seen.verify++; return json({ status: 'OK', settled: seen.verify >= 2, preimage: null, pr: PR }); } + if (u.pathname.startsWith('/lnurlp/')) return json({ status: 'ERROR', reason: 'unknown address' }, 404); + return r.abort(); + }); + // no relays in the test: the profile lookup just finds nothing + await page.evaluateOnNewDocument(() => { window.WebSocket = class { constructor() { setTimeout(() => this.onerror?.({}), 0); } send() {} close() {} }; }); + await page.goto(server.url.origin + path); + return { page, seen }; +} + +try { + { + const { page, seen } = await open('/ShopKeeper/receive?amount=2100'); + await page.waitForSelector('#amount', { timeout: 5000 }); + const text = await page.evaluate(() => document.body.innerText); + check('the page names the address', text.includes('shopkeeper@coinos.io'), text); + const qr = await page.$eval('.qr', (a) => a.getAttribute('href')); + check('...with a QR any Lightning wallet can open (LNURL)', /^lightning:LNURL1[0-9A-Z]+$/.test(qr), qr); + check('...and the amount from the link filled in', (await page.$eval('#amount', (i) => i.value)) === '2100'); + await page.$eval('#amount', (i) => { i.value = '21'; }); + await page.type('#note', 'for the prints'); + await page.click('button.primary'); + await page.waitForSelector('#invoice', { timeout: 5000 }); + check('a set amount asks the registrar for that many msat, with the note', seen.cb.length === 1 && seen.cb[0].amount === '21000' && seen.cb[0].comment === 'for the prints', JSON.stringify(seen.cb)); + const inv = await page.$eval('#invoice .qr', (a) => a.getAttribute('href')); + check('...and shows its invoice as a QR', inv === 'lightning:' + PR.toUpperCase(), inv); + check('...with an open-in-wallet link', (await page.$eval('#invoice a.button', (a) => a.getAttribute('href'))) === 'lightning:' + PR); + await page.waitForSelector('#paid', { timeout: 10000 }); + check('it says Paid once the registrar says the invoice settled', (await page.evaluate(() => document.body.innerText)).includes('21 sats sent to shopkeeper@coinos.io')); + check('no page errors', !seen.errors.length, seen.errors.join(' | ')); + await page.close(); + } + { + const { page } = await open('/shopkeeper/pay', { verify: false }); + await page.waitForSelector('#amount', { timeout: 5000 }); + await page.type('#amount', '500'); + await page.click('button.primary'); + await page.waitForSelector('#invoice', { timeout: 5000 }); + check('/pay works too; an invoice nobody can watch says to pay it from the wallet', (await page.$eval('#status', (s) => s.textContent)) === 'Pay it from your Lightning wallet.'); + await page.click('button.link'); + check('...and "another amount" goes back', !!(await page.waitForSelector('#amount', { timeout: 3000 }))); + await page.$eval('#amount', (i) => { i.value = '0'; }); + await page.click('button.primary'); + check('an amount under the minimum is refused on the page', /at least 1 sats/.test(await page.$eval('#err', (e) => e.textContent))); + await page.close(); + } + { + const { page } = await open('/nobody/receive'); + await page.waitForFunction(() => document.querySelector('.err'), { timeout: 5000 }); + check('an unknown name says so', (await page.$eval('.err', (e) => e.textContent)) === 'nobody@coinos.io is not a coinos address.'); + await page.close(); + } + console.log('\n✅ a coinos name has a pay page'); +} finally { + await browser.close(); + server.stop(true); +} -- cgit v1.2.3