diff options
Diffstat (limited to 'tools')
48 files changed, 3049 insertions, 143 deletions
diff --git a/tools/account-delete-test.js b/tools/account-delete-test.js new file mode 100644 index 0000000..d06bcb8 --- /dev/null +++ b/tools/account-delete-test.js @@ -0,0 +1,115 @@ +// Settings → Wallet → Delete account: asks the registrar what stands in the +// way, says what goes and what stays (and how many sats are still here), +// and on a ticked box + tap has the registrar forget the account (a NIP-98 +// request signed by the wallet's key) and removes the wallet from the device. +// The registrar here is a stand-in inside the test; relays are the stand-ins. +// +// Run: bun tools/account-delete-test.js +import puppeteer from './puppeteer.js'; +import { generateMnemonic } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; +import { verifyEvent } from 'nostr-tools/pure'; +import { createHash } from 'node:crypto'; +import { buildHtml } from '../build.js'; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; + +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 5271, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +await page.setViewport({ width: 420, height: 900 }); +page.on('pageerror', (e) => { console.log(' page error:', e.message); ok = false; }); + +// the registrar: records what it's asked, answers as the real one would +const calls = []; +let owed = { pendingSat: 0, withdrawSat: 0 }; +const cors = { 'access-control-allow-origin': '*', 'access-control-allow-headers': 'content-type,authorization', 'access-control-allow-methods': 'GET,POST,DELETE,OPTIONS' }; +await page.setRequestInterception(true); +page.on('request', (req) => { + const u = new URL(req.url()); + if (u.hostname !== 'names.coinos.io') return req.continue(); + if (req.method() === 'OPTIONS') return req.respond({ status: 200, headers: cors, body: '{}' }); + const reply = (status, j) => req.respond({ status, headers: { ...cors, 'content-type': 'application/json' }, body: JSON.stringify(j) }); + if (u.pathname !== '/account/delete') return reply(404, { error: 'not found' }); + const body = req.postData() || ''; + let ev = null; + try { ev = JSON.parse(Buffer.from((req.headers().authorization || '').replace(/^Nostr /, ''), 'base64').toString()); } catch {} + const tag = (k) => ev?.tags.find((t) => t[0] === k)?.[1]; + const signed = !!ev && ev.kind === 27235 && verifyEvent(ev) && tag('method') === 'POST' + && new URL(tag('u')).pathname === '/account/delete' && tag('payload') === createHash('sha256').update(body).digest('hex'); + const j = JSON.parse(body || '{}'); + calls.push({ check: !!j.check, signed, pubkey: ev?.pubkey }); + const blocked = owed.pendingSat + owed.withdrawSat > 0; + if (j.check) return reply(200, { names: ['[email protected]'], ...owed, paying: 0, blocked }); + if (blocked) return reply(409, { error: 'funds', ...owed, paying: 0 }); + return reply(200, { ok: true, names: ['[email protected]'] }); +}); + +const click = (sel, t) => page.evaluate((s, x) => { const e = [...document.querySelectorAll(s)].find((n) => n.textContent.trim().toLowerCase().includes(x.toLowerCase())); if (e) { e.click(); return true; } return false; }, sel, t); +const until = async (fn, ms = 15000) => { const end = Date.now() + ms; for (;;) { const v = await fn(); if (v) return v; if (Date.now() > end) return null; await sleep(250); } }; +const text = () => page.evaluate(() => document.body.innerText); +const goBtn = () => page.evaluate(() => { const b = [...document.querySelectorAll('button.btn-danger')].find((x) => x.textContent.trim() === 'Delete account' && x.closest('.card')?.querySelector('input[type=checkbox]')); return b ? { disabled: b.disabled } : null; }); +const openCard = async () => { + await page.evaluate(() => document.querySelector('[data-key="delete-account"] button')?.click()); + await until(async () => (await text()).includes('[email protected] is released')); +}; + +try { + await page.goto('http://localhost:5271/', { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); + await sleep(400); + await click('button', 'Create a new wallet'); + await sleep(300); + await click('button', 'Have an existing seed'); + await sleep(300); + await page.waitForSelector('textarea'); + await page.type('textarea', generateMnemonic(wordlist)); + await click('button', 'Open wallet'); + await until(async () => /receive/i.test(await text())); + await page.evaluate(() => [...document.querySelectorAll('button')].find((e) => e.getAttribute('aria-label') === 'Settings')?.click()); + await until(async () => (await text()).includes('Advanced')); + await page.evaluate(() => [...document.querySelectorAll('.settings-tile')].find((e) => [...e.querySelectorAll('span')].some((x) => x.textContent.trim() === 'Wallet'))?.click()); + await sleep(500); + if (process.env.DEBUG) console.log((await text()).slice(0, 600)); + check('Settings → Wallet has a Delete account card', !!(await until(() => page.evaluate(() => !!document.querySelector('[data-key="delete-account"]'))))); + + console.log('\n[sats still owed]'); + owed = { pendingSat: 21, withdrawSat: 500 }; + await openCard(); + let tx = await text(); + check('says the name is released, records deleted, and what stays', /is released/.test(tx) && /Our servers delete/.test(tx) && /Not deleted: your coins/.test(tx)); + check('names the sats still owed and won\'t go on', /521 sats are still on their way/.test(tx) && (await goBtn())?.disabled === true, tx.match(/⚠[^\n]*/)?.[0]?.slice(0, 80)); + check('the question was signed by the wallet\'s key', calls.length === 1 && calls[0].check && calls[0].signed); + await click('button', 'Back'); + await sleep(300); + check('Back returns to the settings page, account intact', !!(await page.evaluate(() => !!document.querySelector('[data-key="delete-account"]'))) && calls.every((c) => c.check)); + + console.log('\n[nothing in the way]'); + owed = { pendingSat: 0, withdrawSat: 0 }; + await openCard(); + check('the button waits for the box to be ticked', (await goBtn())?.disabled === true); + await page.evaluate(() => document.querySelector('.card input[type=checkbox]')?.click()); + await sleep(300); + check('ticked: the button is live', (await goBtn())?.disabled === false); + const before = calls.length; + await page.evaluate(() => [...document.querySelectorAll('button.btn-danger')].find((x) => x.textContent.trim() === 'Delete account' && !x.disabled)?.click()); + const gone = await until(async () => /create a new wallet/i.test(await text()), 20000); + if (process.env.DEBUG) console.log((await text()).slice(0, 900)); + check('the registrar was told to delete, signed', calls.slice(before).some((c) => !c.check && c.signed), JSON.stringify(calls.slice(before).map((c) => ({ check: c.check, signed: c.signed })))); + check('the wallet is gone from the device: back at the front door', !!gone); + const left = await page.evaluate(() => ({ session: sessionStorage.getItem('btc-wallet-accounts'), vault: localStorage.getItem('btc-wallet-vault') })); + check('no account left in the session', !left.session || !JSON.parse(left.session).accounts?.length, String(left.session).slice(0, 60)); + await page.reload({ waitUntil: 'domcontentloaded' }); + check('and a reload doesn\'t bring it back', !!(await until(async () => /create a new wallet/i.test(await text()), 10000))); +} catch (e) { + console.log(' error:', e.message); ok = false; +} finally { + await browser.close(); + server.stop(true); +} +console.log(ok ? '\nPASS' : '\nFAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/amber-login-test.js b/tools/amber-login-test.js deleted file mode 100644 index 46a16f6..0000000 --- a/tools/amber-login-test.js +++ /dev/null @@ -1,104 +0,0 @@ -// NIP-55: on Android, "Sign in with Amber" opens a nostrsigner: intent for the -// pubkey; the answer is read from the clipboard when the tab comes back (or -// pasted); creating the wallet then makes an encrypt and a sign round trip. -// The intent launcher and the clipboard are stubbed; relays answer nothing. -// Run: bun tools/amber-login-test.js -import puppeteer from './puppeteer.js'; -import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure'; -import { npubEncode } from 'nostr-tools/nip19'; -import { buildHtml } from '../build.js'; -const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); -let ok = true; -const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; -const SK = generateSecretKey(); const PK = getPublicKey(SK); -const html = await buildHtml({ minify: true, pwa: false }); -const server = Bun.serve({ port: 5308, fetch: (req) => { const p = new URL(req.url).pathname; if (p === '/verify-worker.js' || p.startsWith('/punks')) return new Response(Bun.file('dist' + p)); return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); -const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); -const page = await browser.newPage(); -await page.setUserAgent('Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0 Mobile Safari/537.36'); -await page.evaluateOnNewDocument(() => { - window.__amberUrls = []; - window.__coinosAmberLaunch = (u) => { window.__amberUrls.push(u); }; - window.__clip = ''; - Object.defineProperty(navigator, 'clipboard', { value: { readText: async () => window.__clip, writeText: async () => {} }, configurable: true }); - const Real = window.WebSocket; - window.WebSocket = function (...a) { const ws = new Real(...a); const send = ws.send.bind(ws); ws.send = (d) => { try { const m = JSON.parse(d); if (m[0] === 'REQ') { setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) })), 0); return; } if (m[0] === 'EVENT') { window.__published = (window.__published || []).concat([m[1]]); setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['OK', m[1].id, true, '']) })), 0); return; } } catch {} return send(d); }; return ws; }; - window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real); -}); -const errs = []; -page.on('pageerror', (e) => errs.push(String(e))); -const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); -const waitText = async (x, ms = 20000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; -const urls = () => page.evaluate(() => window.__amberUrls); -const lastType = async () => { const u = await urls(); const last = u[u.length - 1] || ''; return (last.match(/[?&]type=([a-z_0-9]+)/) || [])[1] || null; }; -const deliver = (text) => page.evaluate((t) => { window.__clip = t; document.dispatchEvent(new Event('visibilitychange')); window.dispatchEvent(new Event('focus')); }, text); - -try { - await page.setViewport({ width: 390, height: 844 }); - await page.goto('http://localhost:5308/', { waitUntil: 'domcontentloaded' }); - await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); - await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(500); - console.log('\n[the Amber door]'); - await click('sign in to an existing account'); await sleep(300); - check('the front door offers Nostr sign-in', await click('sign in with nostr') || await click('nostr')); - await sleep(500); - check('on Android, the login offers Amber', await waitText('sign in with a signer app', 5000)); - await click('sign in with a signer app'); await sleep(400); - check('tapping it opens a get_public_key intent', (await lastType()) === 'get_public_key', JSON.stringify(await urls())); - check('...and shows the waiting card with a paste box', await waitText('waiting for your signer', 2000) && !!(await page.$('.amber-paste'))); - await deliver(npubEncode(PK)); - // a fresh account: the wallet is minted and its backup goes to the app to be encrypted - let t0 = Date.now(); while (Date.now() - t0 < 15000 && (await lastType()) !== 'nip44_encrypt') await sleep(250); - check('the pubkey read off the clipboard signs the account in; the seed goes to the app for encryption', (await lastType()) === 'nip44_encrypt', JSON.stringify((await urls()).map((u) => (u.match(/[?&]type=([a-z_0-9]+)/) || [])[1]))); - check('...and the npub left on the clipboard is not mistaken for the ciphertext', await page.evaluate(() => !!document.querySelector('.amber-paste'))); - - console.log('\n[creating the wallet: encrypt, then sign, each a round trip]'); - const encUrl = (await urls()).pop(); - check('...addressed to the user\'s own key', new URL(encUrl.replace('nostrsigner:', 'http://x/')).searchParams.get('pubkey') === PK); - // this time the clipboard is not readable: the answer is pasted - await page.evaluate(() => { navigator.clipboard.readText = async () => { throw new Error('denied'); }; }); - const fakeCipher = 'Ag' + btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(96)))).replace(/=+$/, '').replace(/[^A-Za-z0-9+/]/g, 'a'); - await page.type('.amber-paste', fakeCipher); - await click('use it'); await sleep(800); - check('the pasted ciphertext moves things on to a signature', (await lastType()) === 'sign_event', await lastType()); - const signUrl = (await urls()).pop(); - const unsigned = JSON.parse(decodeURIComponent(signUrl.slice('nostrsigner:'.length).split('?')[0])); - check('...of an event under the signed-in pubkey', unsigned.pubkey === PK && typeof unsigned.kind === 'number', JSON.stringify({ kind: unsigned.kind, pk: unsigned.pubkey.slice(0, 8) })); - const signed = finalizeEvent({ kind: unsigned.kind, created_at: unsigned.created_at, tags: unsigned.tags, content: unsigned.content }, SK); - await page.evaluate(() => { navigator.clipboard.readText = async () => window.__clip; }); - await deliver(JSON.stringify(signed)); await sleep(2500); - const pub = await page.evaluate(() => (window.__published || []).map((e) => e.kind)); - check('the signed backup is published and the new identity walks into onboarding', pub.includes(30078) && await waitText('write down your recovery phrase', 10000), 'published kinds ' + JSON.stringify(pub)); - // the rest of the first run: every further signature (relay list, follows) - // is one more trip through Amber, taken in turn, while the words screen is - // walked through - const signedKinds = []; - let signedUrls = 1; - // answer the next sign_event intent, if one is waiting - const signNext = async () => { - const pend = (await urls()).filter((u) => /type=sign_event/.test(u)); - if (pend.length <= signedUrls) return false; - const u = pend[signedUrls]; signedUrls++; - const ev = JSON.parse(decodeURIComponent(u.slice('nostrsigner:'.length).split('?')[0])); - signedKinds.push(ev.kind); - await deliver(JSON.stringify(finalizeEvent({ kind: ev.kind, created_at: ev.created_at, tags: ev.tags, content: ev.content }, SK))); - return true; - }; - for (let i = 0; i < 80 && !(await page.evaluate(() => document.body.innerText.toLowerCase().includes('receive'))); i++) { - if (!(await signNext())) { await click('later') || await click('skip verification') || await click("i've written it down") || await click('continue'); } - await sleep(500); - } - // The starter follows wait on a deep look for a list this key may already - // have (2026-10-02 follows-overwrite fix), so their signature can arrive - // after the wallet is open: keep answering until things go quiet. - for (let i = 0, idle = 0; i < 60 && idle < 8; i++) { - if (await signNext()) idle = 0; else if (signedKinds.length) idle++; - await sleep(500); - } - if (!(await page.evaluate(() => document.body.innerText.toLowerCase().includes('receive')))) console.log(' DEBUG loop end:', JSON.stringify(await page.evaluate(() => ({ btns: [...document.querySelectorAll('button')].map((b) => b.textContent.trim()).filter(Boolean).slice(0, 12), text: document.body.innerText.slice(0, 160).replace(/\n+/g, ' | ') })))); - check('each later signature (follows, relays) was its own trip, and the wallet opens on Receive', await waitText('receive', 5000) && signedKinds.length > 0, 'signed kinds after the backup ' + JSON.stringify(signedKinds)); - check('no request cancelled another', !(await page.evaluate(() => document.body.innerText)).includes('took its place')); - check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); -} finally { await browser.close(); server.stop(true); } -console.log(ok ? '\n✅ Amber signs in and signs, one trip at a time' : '\n❌ failed'); -process.exit(ok ? 0 : 1); diff --git a/tools/amount-field-unit-test.js b/tools/amount-field-unit-test.js index 596969d..a25432e 100644 --- a/tools/amount-field-unit-test.js +++ b/tools/amount-field-unit-test.js @@ -11,7 +11,7 @@ import puppeteer from './puppeteer.js'; const bundle = await Bun.build({ entrypoints: ['src/app.js'], target: 'browser', minify: true, plugins: [{ name: 'amount-field-test', setup(build) { build.onLoad({ filter: /src\/app\.js$/ }, async ({ path }) => ({ loader: 'js', contents: await Bun.file(path).text() + ` -window.amtApp = { ctx, ui, toggleUnit, get unit() { return unit; } }; +window.amtApp = { ctx, ui, toggleUnit, handleScanned, get unit() { return unit; } }; ` })); build.onLoad({ filter: /src\/video-compress\.js$/ }, () => ({ loader: 'js', contents: 'export async function compressVideo(f) { return f; }' })); } }] }); @@ -46,6 +46,16 @@ try { out.ring = []; for (let i = 0; i < 3; i++) { amtApp.toggleUnit(); out.ring.push([amtApp.unit, ...rs.map((r) => r.amount)]); } rs.splice(1); + // a scanned payment request with an amount, with dollars as the unit + while (amtApp.unit !== 'fiat') amtApp.toggleUnit(); + rs[0].amount = ''; rs[0].address = ''; + amtApp.handleScanned('bitcoin:bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080?amount=0.0005&label=x'); + out.scan = [amtApp.unit, localStorage.getItem('btc-wallet-unit'), rs[0].address, rs[0].amount, ctx.parseAmount(rs[0].amount)]; + // without an amount the unit is left alone + amtApp.toggleUnit(); + const before = amtApp.unit; + amtApp.handleScanned('bitcoin:bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080'); + out.plain = [before, amtApp.unit]; return out; }); console.log(r); @@ -60,6 +70,9 @@ try { ['fiat', '93.31', '0.13', '', 'abc'], ['sats', '62212', '93', '', 'abc'], ], 'a typed amount follows the unit around the ring and comes back exact; blanks and junk are left alone'); + assert.deepEqual(r.scan, ['btc', 'btc', 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080', '0.00050000', 50000], + 'a scanned bitcoin: request with an amount switches the unit to BTC and fills 50,000 sats, not 0.0005 dollars'); + assert.deepEqual(r.plain, ['fiat', 'fiat'], 'a request with no amount leaves the unit as it was'); assert.deepEqual(errors, []); console.log('✅ amount fills follow the display unit'); } finally { await browser.close(); server.stop(true); } diff --git a/tools/ark-refund-mailbox.test.js b/tools/ark-refund-mailbox.test.js new file mode 100644 index 0000000..03a76da --- /dev/null +++ b/tools/ark-refund-mailbox.test.js @@ -0,0 +1,47 @@ +// bun test tools/ark-refund-mailbox.test.js — a failed Lightning payment's +// refund that the wallet lost (the server cosigned the revocation, the page +// was reloaded before the coin was written down: json534543, 2026-11-20, +// 14,786 sats) comes back through the mailbox to the refund key. The wallet +// takes a coin paid to any key it has handed out, closes the payment it +// refunds as failed, and still refuses a coin to a key that is not its own. +import { test, expect, mock } from 'bun:test'; +import { hex } from '@scure/base'; +import * as validate from '../src/ark/validate.js'; +const seen = []; +mock.module('../src/ark/validate.js', () => ({ ...validate, validateVtxo: async (v, o) => { seen.push(o.expectPubkeys); if (!o.expectPubkeys.includes(v.policy.userPubkey)) throw new validate.VtxoValidationError('vtxo not paid to one of our keys'); } })); +const { ArkManager } = await import('../src/ark/manager.js'); +const pk = (i) => hex.encode(Uint8Array.from({ length: 33 }, () => i + 2)); +const mgr = () => { + const m = Object.create(ArkManager.prototype); + m.state = { vtxos: [{ id: 'htlc', state: 'pending', amountSat: 14786, policy: 'serverHtlcSend' }], movements: [], nextKeyIndex: 9, mailboxCheckpoint: 0, + actions: [{ type: 'ln-pay', step: 'revoking', amountSat: 14770, invoice: 'lnbc1', paymentHash: 'aa', htlcVtxoIds: ['htlc'], htlcKeyIndex: 6, revKeyIndex: 7 }] }; + m._key = (i) => ({ pubkey: hex.decode(pk(i)), privkey: new Uint8Array(32) }); + m._tipMemo = async () => 900000; m._save = () => {}; m._estimateReceiveTs = () => 1; + m._movement = (x) => m.state.movements.push(x); + return m; +}; +const coin = (id, amountSat, key) => ({ id, amountSat, expiryHeight: 985313, policy: { type: 'pubkey', userPubkey: pk(key) }, _raw: { bytes: Uint8Array.of(1, 2, 3) } }); +test('a refund delivered to the refund key is taken and closes the payment', async () => { + const m = mgr(); + const changed = await m._handleMailboxMessage({ kind: 'arkoor', checkpoint: 0, vtxos: [coin('refund', 14786, 7), coin('dust', 2, 7)] }); + expect(changed).toBe(true); + const held = Object.fromEntries(m.state.vtxos.map((v) => [v.id, v])); + expect(held.refund.state).toBe('spendable'); expect(held.refund.keyIndex).toBe(7); + expect(held.dust.keyIndex).toBe(7); + expect(held.htlc.state).toBe('spent'); + expect(m.state.actions[0].step).toBe('failed'); + expect(m.state.movements).toEqual([{ type: 'ln-send', amountSat: 14770, status: 'failed', detail: 'payment failed, funds returned', invoice: 'lnbc1' }]); +}); +test('an ordinary receive to key 0 is a receive, as before', async () => { + const m = mgr(); + await m._handleMailboxMessage({ kind: 'arkoor', checkpoint: 0, vtxos: [coin('gift', 500, 0)] }); + expect(m.state.vtxos.find((v) => v.id === 'gift').keyIndex).toBe(0); + expect(m.state.movements[0].type).toBe('receive'); expect(m.state.movements[0].status).toBe('complete'); + expect(m.state.actions[0].step).toBe('revoking'); +}); +test('a coin to a key that is not ours is refused', async () => { + const m = mgr(); + await m._handleMailboxMessage({ kind: 'arkoor', checkpoint: 0, vtxos: [coin('theirs', 500, 200)] }); + expect(m.state.vtxos.some((v) => v.id === 'theirs')).toBe(false); + expect(m.state.movements[0].status).toBe('rejected'); +}); diff --git a/tools/ark/dust-shapes-test.js b/tools/ark/dust-shapes-test.js new file mode 100644 index 0000000..d5a9f5f --- /dev/null +++ b/tools/ark/dust-shapes-test.js @@ -0,0 +1,59 @@ +// The arkoor shapes whose dust isolation changed for server-0.9.0 (!2822), +// sent through a real server: each from a wallet holding ONE coin, so the +// split is exactly the one named. +// 400 → 100 (+300 change) every output dust: both isolated +// 500 → 100 (+400 change) the change can't pad the dust: isolated whole +// 1000 → 100 (+900 change) the change pads the dust (unchanged) +// 300 → 100 (+200 change) dust input: nothing isolated (unchanged) +// Each payment arrives, and the change is spent onward (the coin is real). +// Usage: bun tools/ark/dust-shapes-test.js (ARK_URL to point at another captaind) +import { execSync } from 'node:child_process'; +import { generateMnemonic, mnemonicToSeedSync } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; +import { HDKey } from '@scure/bip32'; +import { ArkManager } from '../../src/ark/manager.js'; + +const ARK = process.env.ARK_URL || 'http://127.0.0.1:3535'; +const ESPLORA = 'http://127.0.0.1:30002'; +const ALICE = `${process.env.HOME}/bark/target/debug/bark --datadir ${process.env.HOME}/ark-regtest/alice`; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (name, cond, detail = '') => { console.log(` ${cond ? '✓' : '✗'} ${name}${detail ? ' — ' + detail : ''}`); if (!cond) ok = false; }; + +const newWallet = async () => { + let raw = null; + const account = HDKey.fromMasterSeed(mnemonicToSeedSync(generateMnemonic(wordlist))).derive("m/86'/0'/9'"); + return new ArkManager({ account, storage: { load: () => (raw ? JSON.parse(raw) : null), save: (s) => { raw = JSON.stringify(s); } }, arkUrl: ARK, esploraUrl: ESPLORA }).init(); +}; +const waitBalance = async (m, want, tries = 15) => { + for (let i = 0; i < tries && m.balance().spendableSat < want; i++) { await m.sync(); await sleep(1500); } + return m.balance().spendableSat; +}; + +const sink = await newWallet(); +let sunk = 0; +// a bank of ours with one big coin pays each wallet: one coin each, always +// (alice's CLI wallet pays from whatever coins it holds, sometimes several) +const bank = await newWallet(); +execSync(`${ALICE} -q send ${bank.address()} "20000 sat"`); +check('bank funded', (await waitBalance(bank, 20000)) >= 20000); +if (bank.state.vtxos.filter((v) => v.state === 'spendable').length > 1) { await bank.refresh(); for (let i = 0; i < 40 && bank.state.vtxos.filter((v) => v.state === 'spendable').length !== 1; i++) { execSync('docker exec bc bitcoin-cli -rpcwallet=coinos -generate 1'); await bank.sync(); await sleep(2000); } } +check('...in one coin', bank.state.vtxos.filter((v) => v.state === 'spendable').length === 1); +for (const [coin, pay, shape] of [[400, 100, 'all dust'], [500, 100, 'change isolated whole'], [1000, 100, 'change pads the dust'], [300, 100, 'dust input']]) { + console.log(`\n[${coin} → ${pay}] ${shape}`); + const w = await newWallet(), to = await newWallet(); + await bank.send(w.address(), coin); + check(`funded with one ${coin}-sat coin`, (await waitBalance(w, coin)) === coin && w.state.vtxos.filter((v) => v.state === 'spendable').length === 1); + let err = null; + try { await w.send(to.address(), pay); } catch (e) { err = e.message; } + check(`${pay} sent, server cosigned`, !err, err || ''); + check(`${pay} arrived`, (await waitBalance(to, pay)) === pay); + const change = coin - pay; + check(`${change} change spendable`, (await waitBalance(w, change)) === change); + let err2 = null; + try { await w.send(sink.address(), change); sunk += change; } catch (e) { err2 = e.message; } + check(`...and spent onward`, !err2, err2 || ''); +} +check('every onward spend arrived', (await waitBalance(sink, sunk)) === sunk, `${sink.balance().spendableSat}/${sunk}`); +console.log(ok ? '\n✅ every dust shape goes through ' + ARK : '\n❌ a dust shape failed on ' + ARK); +process.exit(ok ? 0 : 1); diff --git a/tools/ark/isolate-dust-test.js b/tools/ark/isolate-dust-test.js new file mode 100644 index 0000000..1170d68 --- /dev/null +++ b/tools/ark/isolate-dust-test.js @@ -0,0 +1,98 @@ +// Dust isolation matches bark's ArkoorBuilder::new_isolate_dust (server-0.9.0) +// case for case, and every split it makes passes the arkoor amount checks of +// both server-0.8.0 and server-0.9.0 (lib/src/arkoor/mod.rs validate_amounts, +// ported below). 0.9.0 (!2822) refuses a checkpoint with a sub-dust output +// unless the input is dust; the old split "accepted the mix" in two cases. +// Run: bun tools/ark/isolate-dust-test.js +import assert from 'node:assert/strict'; +import { isolateDust } from '../../src/ark/send.js'; +import { ArkManager } from '../../src/ark/manager.js'; + +const D = 330; +const P = (n) => ({ type: 'pubkey', userPubkey: 'k' + n }); +const outs = (...a) => a.map((amountSat, i) => ({ amountSat, policy: P(i) })); +const amts = (l) => l.map((o) => o.amountSat); +const check = (name, ok, detail = '') => { assert(ok, name + (detail ? ' — ' + detail : '')); console.log(' ✓ ' + name); }; + +// validate_amounts, both versions. Returns null or the error. +function validate(inputSat, normal, iso, version) { + const sum = (l) => l.reduce((n, o) => n + o.amountSat, 0); + if (sum(normal) + sum(iso) !== inputSat) return 'Unbalanced'; + if (version === '0.9' && [...normal, ...iso].some((o) => o.amountSat === 0)) return 'ZeroValueOutput'; + if (iso.length && sum(iso) < D) return 'Dust'; + if (iso.some((o) => o.amountSat >= 2 * D)) return 'IsolationNotNeeded'; + if (iso.length && iso.every((o) => o.amountSat >= D)) return 'IsolationNotNeeded'; + if (version === '0.9') { + if (inputSat >= D && normal.some((o) => o.amountSat < D)) return 'Dust'; + } else { + // seen on regtest 0.8.0: "An error occurred while building arkoor: At least one output is required" + if (!normal.length) return 'NoOutputs'; + if (iso.length && normal.some((o) => o.amountSat < D)) return 'Dust'; + if (normal.some((o) => o.amountSat < D) && normal.some((o) => o.amountSat >= 2 * D)) return 'Dust'; + } + return null; +} + +// upstream's tests (lib/src/arkoor/mod.rs, isolate_dust_*) +const cases = [ + ['all non-dust', 1000, [500, 500], [500, 500], []], + ['all dust', 400, [200, 200], [], [200, 200]], + ['all dust from a dust input', 300, [200, 100], [200, 100], []], + ['sufficient dust', 1000, [600, 200, 200], [600], [200, 200]], + ['split successful', 1000, [800, 100, 100], [670], [130, 100, 100]], + ['split impossible', 600, [400, 100, 100], [], [400, 100, 100]], + ['split impossible isolates the smallest', 950, [450, 400, 100], [450], [400, 100]], + ['exactly at the boundary', 1000, [660, 170, 170], [660], [170, 170]], +]; +for (const [name, input, o, wantOuts, wantIso] of cases) { + const r = isolateDust(outs(...o), input); + check(`${name}: ${o.join('+')} → [${wantOuts}] + isolated [${wantIso}]`, + JSON.stringify(amts(r.outs)) === JSON.stringify(wantOuts) && JSON.stringify(amts(r.isolated)) === JSON.stringify(wantIso), + `got [${amts(r.outs)}] + [${amts(r.isolated)}]`); + check(`...which 0.9.0 accepts`, !validate(input, r.outs, r.isolated, '0.9')); + const l = isolateDust(outs(...o), input, { legacy: true }); + check(`...and the legacy split for the same payment, 0.8.0`, !validate(input, l.outs, l.isolated, '0.8'), `[${amts(l.outs)}] + [${amts(l.isolated)}]`); +} + +// the two shapes the old split sent that 0.9.0 refuses, as our payments make +// them (destination first, change last) +{ + const r = isolateDust(outs(100, 300), 400); + check('100 sent from 400 (all dust): both isolated, none on the checkpoint', !r.outs.length && amts(r.isolated).join() === '100,300'); + check('...which the old split left on the checkpoint, refused by 0.9.0', validate(400, outs(100, 300), [], '0.9') === 'Dust'); + const r2 = isolateDust(outs(100, 400), 500); + check('100 sent from 500 (change 400 can\'t pad it): the change isolated whole', !r2.outs.length && amts(r2.isolated).join() === '400,100'); + check('...which the old split also left mixed, refused by 0.9.0', validate(500, outs(100, 400), [], '0.9') === 'Dust'); +} +// the split keeps each output's policy: the pad piece is paid to the output it came from +{ + const o = outs(800, 100, 100); + const r = isolateDust(o, 1000); + check('the pad piece keeps the policy of the output it came from', r.isolated[0].policy === o[0].policy && r.outs[0].policy === o[0].policy); +} + +// random payments: each rule's split passes its own server's checks +let n = 0; +for (let i = 0; i < 200000; i++) { + const input = 1 + Math.floor(Math.random() ** 3 * 5000); + const k = 1 + Math.floor(Math.random() * 3); + const cuts = Array.from({ length: k - 1 }, () => 1 + Math.floor(Math.random() * (input - 1))).sort((a, b) => a - b); + const parts = [...cuts, input].map((c, j, a) => c - (j ? a[j - 1] : 0)).filter((x) => x > 0); + if (parts.reduce((a, b) => a + b, 0) !== input) continue; + for (const [v, legacy] of [['0.9', false], ['0.8', true]]) { + const r = isolateDust(outs(...parts), input, { legacy }); + const err = validate(input, r.outs, r.isolated, v); + assert(!err, `${parts.join('+')} from ${input} → [${amts(r.outs)}] + [${amts(r.isolated)}] refused by ${v}: ${err}`); + } + n++; +} +check(`${n.toLocaleString('en-US')} random payments (1–3 outputs, 1–5,000 sat) pass 0.9.0's checks with the new split and 0.8.0's with the legacy one`, n > 100000); +// which rule a wallet uses: the server's own info decides +{ + const m = Object.create(ArkManager.prototype); + m.info = { maxVtxoExitDepth: 100 }; + const before = m._legacyDust(); + m.info = { maxVtxoExitDepth: 100, maxRoundParticipationOutputs: 4 }; + check('a server without ArkInfo field 23 (before 0.9.0) gets the legacy split; one with it, the new', before === true && m._legacyDust() === false); +} +console.log('\n✅ dust isolation matches server-0.9.0, and 0.8.0 keeps its own'); diff --git a/tools/ark/rescue-claimed-test.js b/tools/ark/rescue-claimed-test.js index 7d3c68b..9e36c61 100644 --- a/tools/ark/rescue-claimed-test.js +++ b/tools/ark/rescue-claimed-test.js @@ -12,6 +12,9 @@ mock.module('../../src/ark/refresh.js', () => ({ ...refresh, requestForfeitNonces: async () => { claims++; throw new Error('network'); }, roundParticipationStatus: async () => { statusAsks++; throw new Error('network'); }, + // the round's coins themselves are checked in round-outputs-check-test; + // these fake actions carry none + checkRoundOutputs: () => {}, })); const { ArkManager } = await import('../../src/ark/manager.js'); const mgr = new ArkManager({ storage: { save() {} }, arkUrl: 'http://test.invalid' }); diff --git a/tools/ark/round-outputs-check-test.js b/tools/ark/round-outputs-check-test.js new file mode 100644 index 0000000..da2dbbb --- /dev/null +++ b/tools/ark/round-outputs-check-test.js @@ -0,0 +1,33 @@ +// A round's new coins are checked before we forfeit for them (bark !2803): +// locked by our unlock hash, anchored in this round's transaction, paid to +// our key, worth what we asked for. Any mismatch throws, so nothing is signed. +// Run: bun tools/ark/round-outputs-check-test.js +import assert from 'node:assert/strict'; +import { hex } from '@scure/base'; +import { sha256 } from '@noble/hashes/sha256'; +import { checkRoundOutputs } from '../../src/ark/refresh.js'; + +const check = (name, ok, detail = '') => { assert(ok, name + (detail ? ' — ' + detail : '')); console.log(' ✓ ' + name); }; +const preimage = 'ab'.repeat(32), other = 'cd'.repeat(32); +const ours = hex.encode(sha256(hex.decode(preimage))); +const theirs = hex.encode(sha256(hex.decode(other))); +const me = '02' + '11'.repeat(32), funding = 'f0'.repeat(32); +const coin = ({ hash = ours, type = 'hashLockedCosigned', txid = funding, owner = me, sat = 50_000, unlock } = {}) => ({ + id: 'c' + Math.random().toString(16).slice(2, 8) + ':0', amountSat: sat, + anchorPoint: { txid, vout: 0 }, policy: { type: 'pubkey', userPubkey: owner }, + genesis: [{ transition: { type: 'cosigned' } }, { transition: { type, unlock: unlock || { hash } } }], +}); +const opts = { unlockHash: ours, fundingTxid: funding, ownerPubkey: me, minTotalSat: 50_000 }; +const refuses = (vtxos, o, re) => { try { checkRoundOutputs(vtxos, o); return false; } catch (e) { return re.test(e.message); } }; + +check('coins locked by our hash, in this round, to our key, as asked: accepted', (() => { checkRoundOutputs([coin()], opts); return true; })()); +check('...v0 leaves too, and two coins that add up', (() => { checkRoundOutputs([coin({ type: 'hashLockedCosigned_v0', sat: 20_000 }), coin({ sat: 30_000 })], opts); return true; })()); +check('...and a coin already carrying our preimage', (() => { checkRoundOutputs([coin({ unlock: { preimage } })], opts); return true; })()); +check('a coin locked by ANOTHER unlock hash: refused (the !2803 attack)', refuses([coin({ hash: theirs })], opts, /locked by unlock hash/)); +check('...even beside a good one', refuses([coin(), coin({ hash: theirs, sat: 1 })], opts, /locked by unlock hash/)); +check('a coin anchored in another transaction: refused', refuses([coin({ txid: 'ee'.repeat(32) })], opts, /anchored in/)); +check('a coin paid to someone else: refused', refuses([coin({ owner: '03' + '22'.repeat(32) })], opts, /not paid to our key/)); +check('less than we asked for: refused', refuses([coin({ sat: 49_999 })], opts, /49999 sat, 50000 were asked/)); +check('not a round leaf: refused', refuses([coin({ type: 'arkoor' })], opts, /not a hash-locked round leaf/)); +check('no coins at all: refused', refuses([], opts, /no coins/)); +console.log('\n✅ a round\'s coins are checked before we forfeit for them'); diff --git a/tools/balance-settings-row-test.js b/tools/balance-settings-row-test.js new file mode 100644 index 0000000..351e2fe --- /dev/null +++ b/tools/balance-settings-row-test.js @@ -0,0 +1,70 @@ +// Settings → Wallet lists Spending and Savings; each row opens the page the +// balance card's gear opens. "I simply cannot find this option" (Nils, +// 2026-11-12) — the Spending gear was the only way in. +// Run: bun tools/balance-settings-row-test.js (NO_BUILD=1 to reuse dist/) +import puppeteer from './puppeteer.js'; +import { generateMnemonic } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +if (!process.env.NO_BUILD && Bun.spawnSync(['bun', 'build.js']).exitCode !== 0) throw new Error('build failed'); +const server = Bun.serve({ port: 0, fetch: async (req) => { + const path = new URL(req.url).pathname; + const f = Bun.file('dist' + path); + return path.includes('.') && await f.exists() ? new Response(f) : new Response(Bun.file('dist/index.html')); +} }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errs = []; +// mainnet so Spending turns on (the Ark server's info is read); every other +// outside request is refused, so nothing is claimed or published +await page.setRequestInterception(true); +page.on('request', (r) => { const u = new URL(r.url()); (u.origin === server.url.origin || u.hostname === 'ark.coinos.io') ? r.continue() : r.abort(); }); +page.on('pageerror', (e) => errs.push(String(e))); +const click = (x) => page.evaluate((s) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(s)); if (e) e.click(); return !!e; }, x); +const waitText = async (x, ms = 20000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; +const openWalletPage = async () => { + await page.evaluate(() => [...document.querySelectorAll('button')].find((e) => e.getAttribute('aria-label') === 'Settings').click()); await sleep(500); + await page.evaluate(() => [...document.querySelectorAll('.settings-tile')].find((e) => /^Wallet/.test(e.textContent.trim())).click()); await sleep(500); +}; +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto(server.url.href, { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => (localStorage.setItem('btc-wallet-network', 'mainnet'), localStorage.setItem('btc-wallet-separate-balances', '1'))); + await page.reload({ waitUntil: 'domcontentloaded' }); + await sleep(400); + // on mainnet Create makes a Spending-only account (signup-quick-test); a + // seed wallet with Savings alone comes in through the seed-phrase door + await page.waitForSelector('#onb-signin'); await page.click('#onb-signin'); await sleep(400); + await page.click('#onb-restore'); await sleep(400); + await page.waitForSelector('textarea'); await page.type('textarea', generateMnemonic(wordlist)); await click('open wallet'); + if (await waitText('claim a username', 8000)) { await click('not now'); await sleep(800); } + await waitText('receive'); + await sleep(1500); + check('savings-only wallet lists Savings alone', await (async () => { await openWalletPage(); const v = await page.$$eval('.balance-settings-row', (l) => l.map((e) => e.dataset.view)); await page.goBack(); await page.goBack(); await sleep(500); return v.join() === 'savings'; })()); + await waitText('set up a spending account', 30000); + await click('set up a spending account'); await sleep(800); + if (await waitText('claim a username', 5000)) { await click('not now'); await sleep(800); } + await waitText('receive'); await sleep(800); + if (process.env.DEBUG) console.log((await page.evaluate(() => document.body.innerText)).slice(0, 600)); + const gears = await page.$$eval('.balance-gear', (l) => l.length); + await openWalletPage(); + if (process.env.SHOT) { await page.evaluate(() => document.querySelector('.balance-settings-row').closest('.card').scrollIntoView()); await page.screenshot({ path: process.env.SHOT }); } + const views = await page.$$eval('.balance-settings-row', (l) => l.map((e) => e.dataset.view)); + check('Settings → Wallet lists the balances', views.length >= 1, views.join(',')); + check('Spending is listed when the card shows it', views.includes('spending'), `gears on the wallet: ${gears}`); + await page.evaluate(() => document.querySelector('.balance-settings-row[data-view="spending"]')?.click()); await sleep(600); + const st = await page.evaluate(() => ({ screen: history.state.nav.screen, view: history.state.nav.settingsView, h3: [...document.querySelectorAll('h3')].map((e) => e.textContent) })); + check('the Spending row opens the Spending settings', st.screen === 'accountSettings' && st.view === 'spending' && st.h3.includes('Spending'), JSON.stringify(st.h3.slice(0, 4))); + await page.goBack(); await sleep(600); + check('Back returns to Settings → Wallet', !!(await page.$('.balance-settings-row'))); + await page.evaluate(() => document.querySelector('.balance-settings-row[data-view="savings"]')?.click()); await sleep(600); + const sv = await page.evaluate(() => ({ screen: history.state.nav.screen, view: history.state.nav.settingsView })); + check('the Savings row opens the Savings settings', sv.screen === 'accountSettings' && sv.view === 'savings'); + check('no page errors', errs.length === 0, errs.join(' | ')); +} finally { + await browser.close(); server.stop(true); +} +console.log(ok ? 'PASS' : 'FAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/bare-link-test.js b/tools/bare-link-test.js new file mode 100644 index 0000000..71161af --- /dev/null +++ b/tools/bare-link-test.js @@ -0,0 +1,45 @@ +// A web address written without https:// ("saturdaybitcoin.com/rally/1?…") +// is a link, as Amethyst shows it; file names, emails and nip05s stay text. +// Run: bun tools/bare-link-test.js +import assert from 'node:assert/strict'; +import puppeteer from './puppeteer.js'; +import { finalizeEvent, generateSecretKey } from 'nostr-tools/pure'; +import { buildHtml, buildVerifyWorker } from '../build.js'; + +const sk = generateSecretKey(), now = Math.floor(Date.now() / 1000); +const note = finalizeEvent({ kind: 1, created_at: now, tags: [], content: 'Rally No. 1 is set.\n\nJoin the rally: saturdaybitcoin.com/rally/1?utm_source=nostr&utm_campaign=rally1-announce\n\nOr see example.org. Built with node.js, mail [email protected], I am [email protected].' }, sk); +const profile = finalizeEvent({ kind: 0, created_at: now, tags: [], content: JSON.stringify({ name: 'Saturday Bitcoin' }) }, sk); +const html = await buildHtml({ minify: true, pwa: false }); +const worker = await buildVerifyWorker({ minify: true }); +const server = Bun.serve({ port: 0, fetch(req) { + const path = new URL(req.url).pathname; + if (path === '/api/feed') return Response.json({ version: 1, generatedAt: Date.now(), popUntil: now - 100, notes: [note], profiles: [profile] }); + if (path === '/verify-worker.js') return new Response(worker, { headers: { 'Content-Type': 'text/javascript' } }); + if (path.startsWith('/punks')) return new Response(null, { status: 404 }); + return new Response(html, { headers: { 'Content-Type': 'text/html' } }); +} }); +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); }; +try { + const page = await browser.newPage(); + const errors = []; + page.on('pageerror', (e) => errors.push(e.message)); + await page.setRequestInterception(true); + page.on('request', (r) => (r.url().startsWith(server.url.origin) || r.url().startsWith('data:') ? r.continue() : r.abort())); + await page.goto(server.url.origin + '/feed'); + await page.waitForFunction(() => document.body.innerText.includes('Rally No. 1'), { timeout: 8000 }); + const links = await page.$$eval('.notes-feed .note-content a, .notes-feed a', (as) => [...new Set(as)].map((a) => ({ text: a.textContent, href: a.getAttribute('href') })).filter((a) => /^https:/.test(a.href || ''))); + const rally = links.find((a) => /saturdaybitcoin/.test(a.href)); + check('the bare address is a link', !!rally, JSON.stringify(links)); + check('...to its https address', rally.href === 'https://saturdaybitcoin.com/rally/1?utm_source=nostr&utm_campaign=rally1-announce', rally.href); + check('...shown as written', /^saturdaybitcoin\.com\/rally/.test(rally.text), rally.text); + const ex = links.find((a) => /example\.org/.test(a.href)); + check('a bare domain ending a sentence is a link without the full stop', ex && ex.href === 'https://example.org' && ex.text === 'example.org', JSON.stringify(ex)); + check('a file name, an email and a nip05 stay text', !links.some((a) => /node\.js|gmail|coinos/.test(a.href)), JSON.stringify(links)); + check('the text around them is intact', (await page.evaluate(() => document.querySelector('.notes-feed').innerText)).includes('example.org. Built with node.js, mail [email protected], I am [email protected].')); + check('no page errors', !errors.length, errors.join(' | ')); + console.log('\n✅ bare web addresses are links'); +} finally { + await browser.close(); + server.stop(true); +} diff --git a/tools/chat-layout-test.js b/tools/chat-layout-test.js index 7c79858..a0f00ad 100644 --- a/tools/chat-layout-test.js +++ b/tools/chat-layout-test.js @@ -164,7 +164,7 @@ try { console.log('\n[direct messages]'); await page.click('.chat-back'); await sleep(500); - check('footer returns when the conversation closes', await page.$eval('.footer', (el) => getComputedStyle(el).display !== 'none')); + // (no footer to bring back: with a wallet open the pickers live in Settings, 2026-11-15) await click('button', 'New message'); await setInput('input[placeholder*="npub" i]', '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'); await click('button', 'Open'); diff --git a/tools/chat-remove-member-test.js b/tools/chat-remove-member-test.js new file mode 100644 index 0000000..1007973 --- /dev/null +++ b/tools/chat-remove-member-test.js @@ -0,0 +1,224 @@ +// A community's admin taps a message and removes its author, with everything +// they said: one owner-signed ban-list edition (CORD-04 vsk 4) that every +// client folds. "can i have some control as a chat group admin to click on a +// message and see an option to remove the user and all their messages from +// the group?" (Adam, 2026-11-10). +// +// Everything runs against a relay inside this process: the page's sockets all +// go there, so nothing reaches a live room. +// +// Run: bun tools/chat-remove-member-test.js +import puppeteer from './puppeteer.js'; +import { generateMnemonic } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; +import { generateSecretKey, getPublicKey } from 'nostr-tools/pure'; +import { buildHtml } from '../build.js'; +import { + parseInviteLink, openInviteBundle, channelStream, channelEpoch, controlKey, wrapRumor, openWrap, msTags, + foldControl, banlistHead, makeBanlist, +} from '../src/concord.js'; +import { hexToBytes } from '@noble/hashes/utils'; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; + +// ---- a relay in a few lines: stores what it's given, serves it by filter ---- +const events = new Map(); +const socks = new Map(); // ws -> Map(subId -> filters) +const matches = (f, e) => (!f.kinds || f.kinds.includes(e.kind)) && (!f.authors || f.authors.includes(e.pubkey)) + && (!f.ids || f.ids.includes(e.id)) && (!f.since || e.created_at >= f.since) && (!f.until || e.created_at <= f.until) + && Object.entries(f).every(([k, v]) => k[0] !== '#' || e.tags.some((t) => t[0] === k.slice(1) && v.includes(t[1]))); +const store = (e) => { + if (events.has(e.id)) return; + events.set(e.id, e); + for (const [ws, subs] of socks) for (const [id, fs] of subs) if (fs.some((f) => matches(f, e))) ws.send(JSON.stringify(['EVENT', id, e])); +}; +const RELAY_PORT = 27811, RELAY = `ws://127.0.0.1:${RELAY_PORT}`; +const relay = Bun.serve({ + port: RELAY_PORT, hostname: '127.0.0.1', + fetch(req, srv) { return srv.upgrade(req) ? undefined : new Response('relay'); }, + websocket: { + open(ws) { socks.set(ws, new Map()); }, + close(ws) { socks.delete(ws); }, + message(ws, raw) { + let m; try { m = JSON.parse(raw); } catch { return; } + if (m[0] === 'EVENT') { store(m[1]); ws.send(JSON.stringify(['OK', m[1].id, true, ''])); } + else if (m[0] === 'REQ') { + const fs = m.slice(2); + socks.get(ws).set(m[1], fs); + for (const f of fs) { + const hit = [...events.values()].filter((e) => matches(f, e)).sort((a, b) => b.created_at - a.created_at); + for (const e of f.limit ? hit.slice(0, f.limit) : hit) ws.send(JSON.stringify(['EVENT', m[1], e])); + } + ws.send(JSON.stringify(['EOSE', m[1]])); + } else if (m[0] === 'CLOSE') socks.get(ws)?.delete(m[1]); + else if (m[0] === 'COUNT') ws.send(JSON.stringify(['COUNT', m[1], { count: 0 }])); + else if (/^NEG-/.test(m[0])) ws.send(JSON.stringify(['NEG-ERR', m[1], 'blocked: unsupported'])); + }, + }, +}); + +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 5263, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +await page.setViewport({ width: 1100, height: 850 }); +page.on('pageerror', (e) => { console.log(' page error:', e.message); ok = false; }); +await page.evaluateOnNewDocument((relayUrl) => { + const Real = window.WebSocket; + window.WebSocket = function (url, protocols) { return new Real(/^wss?:/.test(url) ? relayUrl : url, protocols); }; + window.WebSocket.prototype = Real.prototype; + Object.assign(window.WebSocket, { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 }); + localStorage.setItem('btc-wallet-network', 'regtest'); + // the invite link is "copied": keep it where the test can read it + try { Object.defineProperty(navigator, 'clipboard', { value: { writeText: async (v) => { window.__clip = v; }, readText: async () => window.__clip || '' }, configurable: true }); } catch {} +}, RELAY); + +const click = (sel, t) => page.evaluate((s, x) => { const e = [...document.querySelectorAll(s)].find((n) => n.textContent.trim().toLowerCase().includes(x.toLowerCase())); if (e) { e.click(); return true; } return false; }, sel, t); +const setInput = (sel, v) => page.evaluate((s, val) => { const e = document.querySelector(s); if (!e) return false; e.value = val; e.dispatchEvent(new Event('input', { bubbles: true })); return true; }, sel, v); +const until = async (fn, ms = 20000) => { const end = Date.now() + ms; for (;;) { const v = await fn(); if (v) return v; if (Date.now() > end) return null; await sleep(300); } }; +const bodyText = () => page.evaluate(() => document.body.innerText); +const waitText = (x, ms = 20000) => until(async () => (await bodyText()).toLowerCase().includes(x.toLowerCase()), ms); +const logText = () => page.evaluate(() => document.querySelector('.chat-log')?.innerText || ''); +const say = async (text) => { + await page.waitForSelector('#msg-draft', { timeout: 15000 }); + await page.evaluate((v) => { + const e = document.querySelector('#msg-draft'); + const ta = e.shadowRoot ? e.shadowRoot.querySelector('textarea') : (e.querySelector && e.querySelector('textarea')) || e; + ta.focus(); ta.value = v; + ta.dispatchEvent(new Event('input', { bubbles: true, composed: true })); + }, text); + await sleep(150); + await page.keyboard.press('Enter'); +}; +const tapBubble = (text) => page.evaluate((x) => { + const b = [...document.querySelectorAll('.chat-log .chat-bubble')].find((n) => n.innerText.includes(x)); + if (b) b.click(); + return !!b; +}, text); +const sheet = () => page.evaluate(() => [...document.querySelectorAll('.msg-sheet .msg-sheet-item')].map((b) => b.innerText.trim())); + +try { + await page.goto('http://localhost:5263/', { waitUntil: 'domcontentloaded' }); + await sleep(400); + await click('button', 'Create a new wallet'); + await sleep(300); + await click('button', 'Have an existing seed'); + await sleep(300); + await page.waitForSelector('textarea'); + await page.type('textarea', generateMnemonic(wordlist)); + await click('button', 'Open wallet'); + await waitText('receive', 15000); + await page.evaluate(() => [...document.querySelectorAll('.app-nav-button')].find((b) => /message/i.test(b.getAttribute('aria-label') || ''))?.click()); + await sleep(800); + await click('button', 'Create'); + await sleep(300); + await setInput('input[placeholder*="name" i]', 'removal test'); + await sleep(200); + await page.evaluate(() => { const i = document.querySelector('input[placeholder*="name" i]'); const b = i && i.parentElement.querySelector('button'); if (b) b.click(); }); + await waitText('removal test', 25000); + await click('.item', 'removal test'); + await page.waitForSelector('#msg-draft', { timeout: 15000 }); + await say('the admin says hello'); + check('the admin posts in their community', await until(async () => (await logText()).includes('the admin says hello'))); + + // the join material, the way anyone gets it: the invite link + await page.evaluate(() => document.querySelector('[aria-label="Add person"]')?.click()); + await sleep(300); + await click('button', 'Copy invite link'); + const link = await until(() => page.evaluate(() => window.__clip || null), 10000); + const parsed = parseInviteLink(link || ''); + const bundleEv = parsed && [...events.values()].find((e) => e.kind === 33301 && e.pubkey === parsed.signerPk); + const jm = bundleEv && openInviteBundle(bundleEv, parsed.token); + check('invite link opens the community', !!(jm && jm.community_root), link ? link.slice(0, 50) + '…' : 'no link'); + if (!jm) throw new Error('no join material'); + await page.evaluate(() => document.querySelector('[aria-label="Add person"]')?.click()); + const ch = jm.channels[0]; + const stream = channelStream(jm, ch); + const post = async (sk, text) => { + const { created_at, ms } = msTags(Date.now()); + const rumor = { kind: 9, pubkey: getPublicKey(sk), content: text, tags: [['channel', ch.id], ['epoch', String(channelEpoch(jm, ch))], ms], created_at }; + store(await wrapRumor(rumor, sk, stream)); + }; + const spammer = generateSecretKey(), friend = generateSecretKey(); + await post(spammer, 'Can I have some free sats'); + await sleep(30); + await post(friend, 'good evening all'); + await sleep(30); + await post(spammer, 'Any donation can help'); + check('members\' messages arrive', await until(async () => { const x = await logText(); return x.includes('free sats') && x.includes('good evening') && x.includes('donation'); })); + + console.log('\n[the sheet]'); + await tapBubble('the admin says hello'); + await sleep(300); + let items = await sheet(); + check('own message: no remove option', items.length > 0 && !items.some((x) => /remove/i.test(x)), items.join(' / ')); + await page.keyboard.press('Escape'); + await page.evaluate(() => document.querySelector('.confirm-pop-backdrop')?.click()); + await sleep(300); + await tapBubble('free sats'); + await sleep(300); + items = await sheet(); + check('someone else\'s message: "Remove … and their messages"', items.some((x) => /Remove .+ and their messages$/.test(x)), items.join(' / ')); + await click('.msg-sheet-item', 'and their messages'); + await sleep(300); + items = await sheet(); + check('first tap only asks', items.some((x) => /tap again/i.test(x)) && (await logText()).includes('free sats'), items.join(' / ')); + await click('.msg-sheet-item', 'tap again'); + const gone = await until(async () => { const x = await logText(); return !x.includes('free sats') && !x.includes('donation'); }, 15000); + check('second tap: every message of theirs is gone', !!gone); + const after = await logText(); + check('everyone else\'s stay', after.includes('good evening') && after.includes('the admin says hello')); + + console.log('\n[what other clients see]'); + const control = controlKey(hexToBytes(jm.community_root), jm.community_id, jm.root_epoch || 0); + const entries = () => [...events.values()].filter((e) => e.kind === 1059 && e.pubkey === control.pk).map((w) => openWrap(w, control)).filter(Boolean); + let folded = foldControl(entries(), { ownerHex: jm.owner, cid: jm.community_id }); + check('the relay holds an owner-signed ban list naming them', folded.banned.has(getPublicKey(spammer)) && folded.banned.size === 1); + // a member (not the owner) signing a higher version can't undo it + const head = banlistHead(entries(), { ownerHex: jm.owner, cid: jm.community_id }); + const forged = { ...makeBanlist({ ...head, version: head.version + 5 }, [], Date.now()), pubkey: getPublicKey(spammer) }; + store(await wrapRumor(forged, spammer, control, { plaintext: true })); + folded = foldControl(entries(), { ownerHex: jm.owner, cid: jm.community_id }); + check('a member\'s own "empty list" edition changes nothing', folded.banned.has(getPublicKey(spammer))); + await post(spammer, 'me again, free sats?'); + await post(friend, 'still here'); + await until(async () => (await logText()).includes('still here')); + check('their new messages never show', !(await logText()).includes('me again')); + + console.log('\n[after a reload, and a second removal]'); + await page.reload({ waitUntil: 'domcontentloaded' }); + await until(async () => (await logText()).includes('good evening'), 25000); + await sleep(1500); + check('still gone after a reload', !/free sats|donation|me again/.test(await logText()) && (await logText()).includes('good evening')); + const second = generateSecretKey(); + await post(second, 'buy my course'); + await until(async () => (await logText()).includes('buy my course')); + await tapBubble('buy my course'); + await sleep(300); + await click('.msg-sheet-item', 'and their messages'); + await sleep(300); + await click('.msg-sheet-item', 'tap again'); + await until(async () => !(await logText()).includes('buy my course'), 15000); + folded = foldControl(entries(), { ownerHex: jm.owner, cid: jm.community_id }); + check('the second removal keeps the first', folded.banned.has(getPublicKey(spammer)) && folded.banned.has(getPublicKey(second)) && folded.banned.size === 2, `${folded.banned.size} on the list`); + + console.log('\n[putting someone back]'); + await page.evaluate(() => document.querySelector('.chat-head .col.clickable')?.click()); + await sleep(500); + const hasList = await until(async () => (await bodyText()).includes('Removed from this community'), 5000); + check('the member list shows who was removed (to the admin)', !!hasList); + await page.evaluate(() => { const rows = [...document.querySelectorAll('.chat-members .item')].filter((r) => [...r.querySelectorAll('button')].some((b) => b.textContent.trim() === 'Restore')); rows.at(-1)?.querySelector('button')?.click(); }); + const back = await until(async () => (await logText()).includes('buy my course'), 15000); + check('Restore brings their messages back', !!back); + folded = foldControl(entries(), { ownerHex: jm.owner, cid: jm.community_id }); + check('and the list keeps the other', folded.banned.has(getPublicKey(spammer)) && folded.banned.size === 1); +} catch (e) { + console.log(' error:', e.message); ok = false; +} finally { + await browser.close(); + server.stop(true); relay.stop(true); +} +console.log(ok ? '\nPASS' : '\nFAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/connect-relays-test.js b/tools/connect-relays-test.js new file mode 100644 index 0000000..f54407d --- /dev/null +++ b/tools/connect-relays-test.js @@ -0,0 +1,18 @@ +// The relays a nostrconnect:// link names: relay.coinos.io first, then the +// next live ones, three in all, leaving out any this device found dead. +// Run: bun tools/connect-relays-test.js +import { connectRelays } from '../src/nostr-login.js'; +import { markRelaySick } from '../src/nostr.js'; +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const fresh = connectRelays(); +check('three relays, ours first, primal second', fresh.length === 3 && fresh[0] === 'wss://relay.coinos.io' && fresh[1] === 'wss://relay.primal.net', fresh.join(' ')); +check('nos.lol is no longer second', fresh[1] !== 'wss://nos.lol'); +markRelaySick('wss://nos.lol', 'test'); +const after = connectRelays(); +check('a relay found dead is left out, the next one takes its place', !after.includes('wss://nos.lol') && after.includes('wss://offchain.pub') && after.length === 3, after.join(' ')); +markRelaySick('wss://relay.primal.net', 'test'); markRelaySick('wss://offchain.pub', 'test'); +const one = connectRelays(); +check('relay.coinos.io stays whatever else is down', one[0] === 'wss://relay.coinos.io', one.join(' ')); +console.log(ok ? '\n✅ connect links name live relays' : '\n❌ failed'); +process.exit(ok ? 0 : 1); diff --git a/tools/extension-test.js b/tools/extension-test.js new file mode 100644 index 0000000..6ea9e2a --- /dev/null +++ b/tools/extension-test.js @@ -0,0 +1,198 @@ +// The browser extension (extension/): a site is asked once, then signing and +// paying go through without a prompt; a blocked site stays blocked. +// Loads the built extension into Chrome, with a relay and a wallet service +// (NIP-47) of its own on this machine. +// bun extension/build.js && bun tools/extension-test.js +import puppeteer from 'puppeteer-core'; +import { finalizeEvent, generateSecretKey, getPublicKey, nip04, nip19, nip44, verifyEvent } from 'nostr-tools'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = join(dirname(fileURLToPath(import.meta.url)), '..'); +let failed = 0; +const check = (name, ok, extra = '') => { console.log(`${ok ? '✓' : '✗'} ${name}${ok ? '' : ' ' + extra}`); if (!ok) failed++; }; +const hex = (b) => Buffer.from(b).toString('hex'); + +// ── a relay with a wallet service behind it ──────────────────────────────── +const walletSk = generateSecretKey(); +const walletPk = getPublicKey(walletSk); +const clientSk = generateSecretKey(); +const clientPk = getPublicKey(clientSk); +const asked = []; +const socks = new Set(); +const relay = Bun.serve({ + port: 0, + fetch(req, server) { return server.upgrade(req) ? undefined : new Response('relay'); }, + websocket: { + open(ws) { ws.data = { subs: new Set() }; socks.add(ws); }, + close(ws) { socks.delete(ws); }, + async message(ws, raw) { + const m = JSON.parse(raw); + if (m[0] === 'REQ') { ws.data.subs.add(m[1]); ws.send(JSON.stringify(['EOSE', m[1]])); return; } + if (m[0] === 'CLOSE') { ws.data.subs.delete(m[1]); return; } + if (m[0] !== 'EVENT') return; + const ev = m[1]; + ws.send(JSON.stringify(['OK', ev.id, true, ''])); + if (ev.kind !== 23194 || ev.pubkey !== clientPk) return; + const req = JSON.parse(await nip04.decrypt(walletSk, ev.pubkey, ev.content)); + asked.push(req); + const result = { + get_balance: { balance: 21_000_000 }, + pay_invoice: { preimage: 'ab'.repeat(32) }, + make_invoice: { invoice: 'lnbc50n1made', payment_hash: 'cd'.repeat(32) }, + list_transactions: { transactions: [{ type: 'incoming', amount: 5000_000, description: 'coffee', settled_at: 1 }] }, + }[req.method]; + const body = req.method === 'pay_invoice' && req.params.invoice === 'lnbc1toobig' + ? { result_type: req.method, error: { code: 'QUOTA_EXCEEDED', message: 'Over this connection\'s budget' } } + : { result_type: req.method, result }; + const res = finalizeEvent({ kind: 23195, created_at: Math.floor(Date.now() / 1000), tags: [['p', ev.pubkey], ['e', ev.id]], content: await nip04.encrypt(walletSk, ev.pubkey, JSON.stringify(body)) }, walletSk); + for (const s of socks) for (const sub of s.data.subs) s.send(JSON.stringify(['EVENT', sub, res])); + }, + }, +}); +const site = Bun.serve({ port: 0, fetch: () => new Response('<!doctype html><title>site</title><h1>a site</h1>', { headers: { 'content-type': 'text/html' } }) }); +const nwcUri = `nostr+walletconnect://${walletPk}?relay=${encodeURIComponent('ws://127.0.0.1:' + relay.port)}&secret=${hex(clientSk)}`; + +const userSk = generateSecretKey(); +const userPk = getPublicKey(userSk); +const peerSk = generateSecretKey(); +const peerPk = getPublicKey(peerSk); + +const browser = await puppeteer.launch({ + executablePath: process.env.CHROME || '/usr/bin/google-chrome', + headless: true, pipe: true, enableExtensions: [join(root, 'extension', 'dist')], + args: ['--no-sandbox'], +}); +try { + const sw = await browser.waitForTarget((t) => t.type() === 'service_worker' && t.url().endsWith('/background.js'), { timeout: 15000 }); + const base = sw.url().replace(/\/background\.js$/, ''); + const prompts = () => browser.targets().filter((t) => t.url().startsWith(base + '/prompt.html')); + const promptPage = async () => (await browser.waitForTarget((t) => t.url().startsWith(base + '/prompt.html'), { timeout: 8000 })).asPage(); + const noPrompt = async () => { await new Promise((r) => setTimeout(r, 400)); return prompts().length === 0; }; + // run a call in the page and report { ok, value | error } + const call = (page, expr) => page.evaluate(`(async () => { try { return { ok: true, value: await (${expr}) }; } catch (e) { return { ok: false, error: e.message }; } })()`); + + const page = await browser.newPage(); + await page.goto(`http://127.0.0.1:${site.port}/`); + check('the page has window.nostr and window.webln', await page.evaluate(() => !!(window.nostr && window.nostr._coinos && window.webln && window.webln._coinos))); + + let r = await call(page, 'window.nostr.getPublicKey()'); + check('without a key a site is told to set the extension up', !r.ok && /no key yet/.test(r.error), JSON.stringify(r)); + + // set the key up in the popup + const popup = await browser.newPage(); + await popup.goto(base + '/popup.html?tab'); + await popup.waitForSelector('#key-input', { visible: true }); + await popup.type('#key-input', 'not a key'); + await popup.click('#key-save'); + await popup.waitForFunction(() => document.getElementById('key-err').textContent.length > 0); + check('a wrong key is refused with a reason', true); + await popup.$eval('#key-input', (e) => { e.value = ''; }); + await popup.type('#key-input', nip19.nsecEncode(userSk)); + await popup.click('#key-save'); + await popup.waitForSelector('#main', { visible: true }); + const npub = nip19.npubEncode(userPk); + check('the popup shows the key\'s npub', (await popup.$eval('#npub', (e) => e.textContent)).startsWith(npub.slice(0, 14))); + + // first call from a site: one question, then the answer + await page.bringToFront(); + let pending = call(page, 'window.nostr.getPublicKey()'); + let ask = await promptPage(); + await ask.waitForSelector('#allow'); + check('the prompt names the site', (await ask.$eval('#origin', (e) => e.textContent)).includes('127.0.0.1:' + site.port)); + await ask.click('#allow'); + r = await pending; + check('after Always allow the site gets the public key', r.ok && r.value === userPk, JSON.stringify(r)); + + r = await call(page, `window.nostr.signEvent({ kind: 1, content: 'hello', tags: [['t', 'x']], created_at: 1700000000 })`); + check('signing needs no second prompt', r.ok && (await noPrompt())); + check('the signature verifies under the key', r.ok && r.value.pubkey === userPk && verifyEvent(r.value) && r.value.content === 'hello'); + + r = await call(page, `window.nostr.nip44.encrypt('${peerPk}', 'secret words')`); + check('nip44 encrypts to a peer', r.ok && nip44.decrypt(r.value, nip44.getConversationKey(peerSk, userPk)) === 'secret words', JSON.stringify(r)); + const fromPeer = nip44.encrypt('back to you', nip44.getConversationKey(peerSk, userPk)); + r = await call(page, `window.nostr.nip44.decrypt('${peerPk}', '${fromPeer}')`); + check('nip44 decrypts from a peer', r.ok && r.value === 'back to you', JSON.stringify(r)); + r = await call(page, `window.nostr.nip04.encrypt('${peerPk}', 'old style')`); + check('nip04 encrypts to a peer', r.ok && (await nip04.decrypt(peerSk, userPk, r.value)) === 'old style', JSON.stringify(r)); + + // the wallet + r = await call(page, 'window.webln.enable()'); + check('with no wallet connected, paying says so', !r.ok && /No wallet is connected/.test(r.error), JSON.stringify(r)); + await popup.bringToFront(); + await popup.type('#nwc-input', nwcUri); + await popup.click('#nwc-save'); + await popup.waitForFunction(() => /21,000/.test(document.getElementById('balance').textContent), { timeout: 10000 }); + check('the popup shows the wallet\'s balance', true); + await popup.waitForFunction(() => /coffee/.test(document.getElementById('txs').textContent), { timeout: 10000 }); + check('the popup lists recent payments', true); + if (process.env.SHOTS) { await popup.setViewport({ width: 360, height: 560 }); await popup.screenshot({ path: process.env.SHOTS + '/popup.png' }); } + + await page.bringToFront(); + pending = call(page, 'window.webln.enable()'); + ask = await promptPage(); + await ask.waitForSelector('#allow'); + if (process.env.SHOTS) await ask.screenshot({ path: process.env.SHOTS + '/prompt.png' }); + check('paying is asked about separately', /wallet/.test(await ask.$eval('#what', (e) => e.textContent))); + await ask.click('#allow'); + r = await pending; + check('the site is enabled for payments', r.ok && r.value.enabled === true, JSON.stringify(r)); + r = await call(page, 'window.webln.getBalance()'); + check('the site reads the balance in sats', r.ok && r.value.balance === 21000, JSON.stringify(r)); + r = await call(page, `window.webln.sendPayment('lnbc1invoice')`); + check('a payment returns the preimage, with no prompt', r.ok && r.value.preimage === 'ab'.repeat(32) && (await noPrompt()), JSON.stringify(r)); + check('the wallet was asked to pay that invoice', asked.some((a) => a.method === 'pay_invoice' && a.params.invoice === 'lnbc1invoice')); + r = await call(page, `window.webln.sendPayment('lnbc1toobig')`); + check('the wallet\'s refusal reaches the site', !r.ok && /budget/.test(r.error), JSON.stringify(r)); + r = await call(page, `window.webln.makeInvoice({ amount: 5, defaultMemo: 'tea' })`); + check('an invoice is made for the amount in sats', r.ok && r.value.paymentRequest === 'lnbc50n1made' && asked.some((a) => a.method === 'make_invoice' && a.params.amount === 5000 && a.params.description === 'tea'), JSON.stringify(r)); + + // another site: blocked for good + const other = await browser.newPage(); + await other.goto(`http://localhost:${site.port}/`); + pending = call(other, 'window.nostr.getPublicKey()'); + ask = await promptPage(); + await ask.waitForSelector('#never'); + await ask.click('#never'); + r = await pending; + check('Never for this site refuses the call', !r.ok && /blocked/.test(r.error), JSON.stringify(r)); + r = await call(other, 'window.nostr.getPublicKey()'); + check('and it stays refused without asking again', !r.ok && /blocked/.test(r.error) && (await noPrompt()), JSON.stringify(r)); + + // a dismissed prompt refuses once and asks again later + const third = await browser.newPage(); + await third.goto(`http://127.0.0.1:${relay.port}/`); + pending = call(third, 'window.nostr.getPublicKey()'); + ask = await promptPage(); + await ask.close(); + r = await pending; + check('closing the prompt refuses that one call', !r.ok && /dismissed/.test(r.error), JSON.stringify(r)); + pending = call(third, 'window.nostr.getPublicKey()'); + ask = await promptPage(); + await ask.waitForSelector('#deny'); + await ask.click('#deny'); + r = await pending; + check('the site is asked again, and Not now refuses', !r.ok && /denied/.test(r.error), JSON.stringify(r)); + + // the popup lists the sites and can forget one + await popup.bringToFront(); + await popup.reload(); + await popup.waitForSelector('#sites li'); + const rows = await popup.$$eval('#sites li', (ls) => ls.map((l) => l.textContent)); + check('the popup lists the allowed site as signing and paying', rows.some((t) => t.includes('127.0.0.1:' + site.port) && t.includes('signs') && t.includes('pays')), rows.join(' | ')); + check('and the blocked one as blocked', rows.some((t) => t.includes('localhost') && t.includes('blocked')), rows.join(' | ')); + await popup.click(`#sites button[aria-label="Remove http://127.0.0.1:${site.port}"]`); + await popup.waitForFunction((n) => document.querySelectorAll('#sites li').length === n, {}, rows.length - 1); + await page.bringToFront(); + pending = call(page, 'window.nostr.getPublicKey()'); + ask = await promptPage(); + check('a removed site is asked again', !!ask); + await ask.close(); + await pending; +} finally { + await browser.close(); + relay.stop(true); + site.stop(true); +} +console.log(failed ? `\n${failed} check(s) failed` : '\nall checks passed'); +process.exit(failed ? 1 : 0); diff --git a/tools/feed-mention-tap-test.js b/tools/feed-mention-tap-test.js index d381288..fde2ddb 100644 --- a/tools/feed-mention-tap-test.js +++ b/tools/feed-mention-tap-test.js @@ -14,6 +14,8 @@ const key = () => { const sk = generateSecretKey(); return { sk, pk: getPublicKe const AUTHOR = key(), FRIEND = key(); const now = Math.floor(Date.now() / 1000); const POST = finalizeEvent({ kind: 1, created_at: now - 100, tags: [['p', FRIEND.pk]], content: 'say hello to nostr:' + npubEncode(FRIEND.pk) + ' today' }, AUTHOR.sk); +// a name typed out as plain text: no key in it, no p tag +const PLAIN = finalizeEvent({ kind: 1, created_at: now - 50, tags: [], content: 'big thanks to @poster and @somebody for testing' }, FRIEND.sk); const html = await buildHtml({ minify: true, pwa: false }); const server = Bun.serve({ port: 5319, fetch: (req) => { const p = new URL(req.url).pathname; if (p === '/verify-worker.js' || p.startsWith('/punks')) return new Response(Bun.file('dist' + p)); return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); @@ -39,11 +41,11 @@ try { await waitText('Receive', 20000); const base = cacheKeyFor(mn + '\n'); await page.evaluate(([k, a, f, ns]) => { - localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', a]], c: '', at: Math.floor(Date.now() / 1000) })); + localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', a], ['p', f]], c: '', at: Math.floor(Date.now() / 1000) })); localStorage.setItem(k + ':feedNotes', JSON.stringify(ns)); localStorage.setItem(k + ':profiles', JSON.stringify({ [a]: { name: 'Poster', t: Date.now() }, [f]: { name: 'Friendly', t: Date.now() } })); localStorage.setItem('btc-wallet-feed:' + k, 'following'); - }, [base, AUTHOR.pk, FRIEND.pk, [POST]]); + }, [base, AUTHOR.pk, FRIEND.pk, [PLAIN, POST]]); await page.reload({ waitUntil: 'domcontentloaded' }); await waitText('Receive', 20000); await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]')?.click()); @@ -52,6 +54,22 @@ try { await sleep(1200); const where = await page.evaluate(() => location.pathname); check('the tap opens Friendly\'s profile, not the post', where.startsWith('/npub1') && !where.includes('nevent'), where); + // a typed-out name: the one follow who goes by it opens, anyone else is a search + const tapPlain = async (name) => { + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitText('Receive', 20000); + await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]')?.click()); + await waitText('big thanks to', 15000); + await page.evaluate((n) => [...document.querySelectorAll('[data-zap-post] a')].find((a) => a.textContent === n).click(), name); + await sleep(1200); + }; + await tapPlain('@poster'); + const where2 = await page.evaluate(() => location.pathname); + check('"@poster" typed as plain text opens the follow named Poster', where2 === '/' + npubEncode(AUTHOR.pk) || where2.startsWith('/npub1'), where2); + check('...and it is Poster\'s page', await waitText('Poster', 5000) && !(await page.evaluate(() => !!document.querySelector('.user-search, [data-key="user-search"]')))); + await tapPlain('@somebody'); + const where3 = await page.evaluate(() => location.pathname); + check('"@somebody", whom you do not follow, is still a search', !where3.startsWith('/npub1'), where3); check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); } finally { await browser.close(); server.stop(true); } console.log(ok ? '\n✅ a mention opens the person' : '\n❌ failed'); diff --git a/tools/feed-picture-pager-test.js b/tools/feed-picture-pager-test.js index f74c981..5b5b80f 100644 --- a/tools/feed-picture-pager-test.js +++ b/tools/feed-picture-pager-test.js @@ -13,6 +13,8 @@ let ok = true; const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; const png = (size) => Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=' + size, '-frames:v', '1', '-f', 'image2', '-c:v', 'png', 'pipe:1']).stdout; const PICS = { a1: png('400x300'), a2: png('300x400'), b: png('320x320'), d: png('360x240') }; +// a GIF made without a loop instruction (plays once in a browser) +const GIF = Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=320x240:rate=5:duration=1', '-loop', '-1', '-f', 'gif', 'pipe:1']).stdout; const SK = generateSecretKey(), AUTHOR = getPublicKey(SK); const now = Math.floor(Date.now() / 1000); @@ -23,6 +25,7 @@ const server = Bun.serve({ port: 0, fetch: (req) => { if (path.startsWith('/punks')) return new Response(Bun.file('dist' + path)); const m = /^\/(a1|a2|b|d)\.png$/.exec(path); if (m) return new Response(PICS[m[1]], { headers: { 'content-type': 'image/png' } }); + if (path === '/once.gif') return new Response(GIF, { headers: { 'content-type': 'image/gif' } }); return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); const U = (n) => server.url.origin + '/' + n + '.png'; @@ -30,6 +33,7 @@ const seeded = [ post('two pictures ' + U('a1') + ' ' + U('a2'), 100), post('one picture ' + U('b'), 200), post('only words here, nothing to look at', 300), + post('a gif reply ' + server.url.origin + '/once.gif', 3000), // (past the fillers: the pager walk above doesn't meet it) post('a last picture ' + U('d'), 400), ...Array.from({ length: 12 }, (_, i) => post('filler ' + i + ' ' + 'lorem ipsum dolor sit amet. '.repeat(5), 500 + i * 60)), ]; @@ -82,6 +86,33 @@ try { await waitText('receive', 20000); await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]').click()); check('the pictures are in the feed', await waitFor(() => document.querySelectorAll('.notes-feed img.note-img').length >= 4, null, 20000)); + // a post's run of pictures shares one box of justified rows (the Images + // feed's layout), not a screen each; a lone picture stays as it was + const gal = await page.evaluate(() => { + const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('two pictures')); + const one = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('one picture')); + const g = r && r.querySelector('.note-gallery'); + const im = g ? [...g.querySelectorAll('img.note-img')].map((i) => i.getBoundingClientRect()) : []; + return { n: im.length, sameRow: im.length === 2 && Math.abs(im[0].top - im[1].top) < 1 && Math.abs(im[0].height - im[1].height) < 1.5, h: im[0] ? Math.round(im[0].height) : 0, lone: !!one && !one.querySelector('.note-gallery') && !!one.querySelector('img.note-img') }; + }); + check('two pictures in a post: one gallery, side by side, one height', gal.n === 2 && gal.sameRow && gal.h > 50 && gal.h < 300, JSON.stringify(gal)); + check('a lone picture is not put in a gallery', gal.lone); + // a GIF that would play once is painted from a copy that loops + await waitFor(() => { window.scrollTo(0, document.body.scrollHeight); return [...document.querySelectorAll('.notes-feed [data-key]')].some((n) => n.textContent.includes('a gif reply') && n.querySelector('img.note-img')); }, null, 10000); + const gifLoop = await page.evaluate(async () => { + const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('a gif reply')); + const img = r && r.querySelector('img.note-img'); + if (!img || !/^blob:/.test(img.src)) return { src: img && img.src.slice(0, 40) }; + const b = new Uint8Array(await (await fetch(img.src)).arrayBuffer()); + return { src: 'blob', loops: new TextDecoder('latin1').decode(b).includes('NETSCAPE2.0') }; + }); + check('a GIF without a loop is painted from a copy that loops', gifLoop.src === 'blob' && gifLoop.loops, JSON.stringify(gifLoop)); + await page.evaluate(() => window.scrollTo(0, 0)); await sleep(500); + // painted from the tile copy (a proper resize), not the column copy shrunk by the browser + check('gallery tiles are painted from the tile copies', await waitFor(() => { + const g = document.querySelector('.notes-feed .note-gallery'); + return !!g && [...g.querySelectorAll('img')].every((i) => /^blob:/.test(i.currentSrc || i.src) && i.naturalHeight > 0 && i.naturalHeight <= 360); + }, null, 5000)); console.log('\n[a tap on the picture that opened it shows its details; the next closes it]'); const y0 = await openPic('two pictures'); diff --git a/tools/feed-when-test.js b/tools/feed-when-test.js new file mode 100644 index 0000000..38be4ef --- /dev/null +++ b/tools/feed-when-test.js @@ -0,0 +1,139 @@ +// While the feed scrolls, a chip under the top bar says when the post at the +// top of the screen was written, and fades once the scrolling stops. +// Run: bun tools/feed-when-test.js +import puppeteer from './puppeteer.js'; +import { generateMnemonic } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; +import { cacheKeyFor } from '../src/wallet.js'; +import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure'; +import { noteEncode, npubEncode } from 'nostr-tools/nip19'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (name, condition, detail = '') => { + console.log(`${condition ? '✓' : '✗'} ${name}${detail ? ' — ' + detail : ''}`); + if (!condition) ok = false; +}; +const sk = generateSecretKey(), pk = getPublicKey(sk); +const otherKey = generateSecretKey(), other = getPublicKey(otherKey); +const now = Math.floor(Date.now() / 1000); +const event = (content, at, key = sk, kind = 1) => finalizeEvent({ kind, content, created_at: at, tags: [] }, key); +const origin = 'http://localhost:5299'; +// two hours apart: the feed spans days +const seeded = Array.from({ length: 45 }, (_, i) => event('Post ' + i + '\nEnough text to make each post a comfortable reading target, and a second line of it too.', now - 600 - i * 7200)); +const requested = new Map(); +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 5299, fetch: async (req) => { + const path = new URL(req.url).pathname; + if (path === '/') return new Response(html, { headers: { 'content-type': 'text/html' } }); + if (path.startsWith('/punks')) return new Response(Bun.file('dist' + path)); + requested.set(path, (requested.get(path) || 0) + 1); + const delay = 20; + await sleep(delay); + return new Response('<svg xmlns="http://www.w3.org/2000/svg" width="160" height="100"><rect width="160" height="100" fill="teal"/></svg>', { + headers: { 'content-type': 'image/svg+xml', 'cache-control': 'public, max-age=3600' }, + }); +} }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errors = []; +page.on('pageerror', (e) => errors.push(String(e))); +await page.setViewport({ width: 390, height: 844 }); +await page.evaluateOnNewDocument((fixtures) => { + const sockets = []; + class FakeSocket extends EventTarget { + constructor(url) { + super(); this.url = url; this.readyState = 0; this.subs = new Map(); sockets.push(this); + setTimeout(() => { this.readyState = 1; this.emit('open', new Event('open')); }, 0); + } + emit(type, ev) { this.dispatchEvent(ev); this['on' + type]?.(ev); } + message(data) { this.emit('message', new MessageEvent('message', { data: JSON.stringify(data) })); } + send(raw) { + let m; try { m = JSON.parse(raw); } catch { return; } + if (m[0] === 'CLOSE') { this.subs.delete(m[1]); return; } + if (m[0] !== 'REQ') return; + const [_, id, filter] = m; + (window.__feedRequests ||= []).push(filter); + this.subs.set(id, filter); + let events = []; + if (filter.kinds?.includes(1) && !filter.since && !filter.until) events = window.__catchup || []; + setTimeout(() => { + if (!this.subs.has(id)) return; + for (const e of events) this.message(['EVENT', id, e]); + this.message(['EOSE', id]); + }, events.length ? 700 : 20); + } + close() { this.readyState = 3; this.emit('close', new Event('close')); } + } + Object.assign(FakeSocket, { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 }); + window.WebSocket = FakeSocket; + window.__inject = (e) => { + let count = 0; + for (const ws of sockets) for (const [id, f] of ws.subs) { + if (ws.readyState === 1 && f.kinds?.includes(1) && f.since) { ws.message(['EVENT', id, e]); count++; } + } + return count; + }; +}, {}); +const click = (text) => page.evaluate((text) => [...document.querySelectorAll('button')].find((e) => e.textContent.toLowerCase().includes(text))?.click(), text); +const row = (id) => `.notes-feed > [data-key="${id}"]`; +// the Feed is a tab in the bottom nav (it was a row on the chat home) +const feedTab = () => [...document.querySelectorAll('.app-nav-button')].find((b) => b.getAttribute('aria-label') === 'Feed'); +const snapshot = () => page.evaluate(() => [...document.querySelectorAll('.notes-feed > [data-zap-post]')].map((n) => { + const b = n.getBoundingClientRect(); + return { id: n.dataset.key, top: b.top, height: b.height, text: n.innerText, avatar: n.querySelector('.note-avatar')?.getAttribute('style') }; +})); +try { + await page.goto(origin); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload(); await sleep(300); + await click('create a new wallet'); await sleep(400); + await click('to import'); + await page.waitForSelector('textarea'); + const mnemonic = generateMnemonic(wordlist); + await page.type('textarea', mnemonic); + await click('open wallet'); + await page.waitForFunction(() => document.body.innerText.toLowerCase().includes('receive')); + const base = cacheKeyFor(mnemonic + '\n'); + await page.evaluate(([base, pk, seeded, origin]) => { + localStorage.setItem(base + ':follows', JSON.stringify({ tags: [['p', pk]], c: '', at: Math.floor(Date.now() / 1000) })); + localStorage.setItem(base + ':feedNotes', JSON.stringify(seeded)); + localStorage.setItem(base + ':profiles', JSON.stringify({ [pk]: { name: 'Cached Author', picture: origin + '/avatar.png', t: Date.now() } })); + localStorage.setItem('btc-wallet-feed:' + base, 'following'); // a wallet with no feed remembered opens on Popular + }, [base, pk, seeded, origin]); + await page.reload(); + await page.waitForFunction(() => document.body.innerText.toLowerCase().includes('receive')); + await sleep(2000); + await page.evaluate((tab) => eval(tab)()?.click(), feedTab.toString()); + await page.waitForSelector('.notes-feed:not([data-booting]) > .row', { timeout: 15000 }); + await sleep(800); + await page.evaluate(() => scrollBy(0, 40)); await sleep(100); + check('no chip near the top of the feed', !(await page.$('.feed-when.on'))); + for (let i = 0; i < 12; i++) { await page.evaluate(() => scrollBy(0, 300)); await sleep(30); } + await sleep(100); + const shown = await page.evaluate(() => { + const el = document.querySelector('.feed-when.on'); + const top = document.querySelector('.brand-header').getBoundingClientRect().bottom; + const r = [...document.querySelectorAll('.notes-feed > .row[data-key]')].find((r) => r.getBoundingClientRect().bottom > top + 12); + return el && { text: el.textContent, key: r?.dataset.key, y: el.getBoundingClientRect().top, head: top }; + }); + const ev = shown && seeded.find((e) => e.id === shown.key); + check('the chip shows while scrolling, under the top bar', !!shown && shown.y >= shown.head, JSON.stringify(shown)); + // seeded posts are two hours apart: the chip's minute is one of those between this post and the next + const between = ev && await page.evaluate((s) => Array.from({ length: 121 }, (_, m) => new Date((s - m * 60) * 1000).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })), ev.created_at); + check('...with a time between the top post and the next', !!between && between.some((x) => shown.text.includes(x)), shown?.text); + check('...and how long ago', /ago|yesterday/i.test(shown?.text || ''), shown?.text); + if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT }); + // the clock rolls between posts: a few px down the same post moves it on + const at = (y) => page.evaluate(async (y) => { scrollBy(0, y); await new Promise((r) => setTimeout(r, 60)); return document.querySelector('.feed-when')?.textContent; }, y); + const a = await at(1), b = await at(60); + check('the time blends between posts as you scroll', !!a && !!b && a !== b, a + ' → ' + b); + await sleep(450); + check('it fades once the scrolling stops', !(await page.$('.feed-when.on'))); + check('no page errors', !errors.length, errors.join('; ')); +} finally { + await browser.close(); + server.stop(true); +} +console.log(ok ? 'PASS' : 'FAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/footer-support-test.js b/tools/footer-support-test.js index a37c070..0de6c9a 100644 --- a/tools/footer-support-test.js +++ b/tools/footer-support-test.js @@ -1,5 +1,6 @@ -// The footer's "Show your support" link opens the hat shop, from any page, -// and only shows once a wallet is open (the shop pays from it). +// "Show your support" lives on Settings → About (2026-11-15: the footer is +// gone once a wallet is open; language and currency top the Settings hub) and opens the hat shop; it shows only +// once a wallet is open (the shop pays from it). // Run: bun tools/footer-support-test.js import puppeteer from './puppeteer.js'; import { generateMnemonic } from '@scure/bip39'; @@ -18,31 +19,43 @@ const browser = await puppeteer.launch({ executablePath: process.env.CHROME || ' const page = await browser.newPage(); const errs = []; page.on('pageerror', (e) => errs.push(String(e))); const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); -const link = () => page.evaluate(() => [...document.querySelectorAll('.footer button')].some((b) => b.textContent.trim() === 'Show your support')); +const link = () => page.evaluate(() => !!document.getElementById('about-support')); +const footerOnly = () => page.evaluate(() => { const f = document.querySelector('.footer'); return f ? { selects: f.querySelectorAll('select').length, other: f.querySelectorAll('button, a').length, text: f.innerText.replace(/\s+/g, ' ').trim() } : null; }); +const openAbout = async () => { + await page.evaluate(() => [...document.querySelectorAll('button')].find((e) => e.getAttribute('aria-label') === 'Settings').click()); await sleep(500); + await page.evaluate(() => [...document.querySelectorAll('.settings-tile')].find((e) => /^About/.test(e.textContent.trim())).click()); await sleep(500); +}; try { await page.setViewport({ width: 390, height: 844 }); await page.goto(server.url.origin, { waitUntil: 'domcontentloaded' }); await sleep(600); check('no link before there is a wallet', !(await link())); - await click('create a new wallet'); await sleep(500); await click('to import'); await sleep(400); + await page.waitForSelector('#onb-signin'); await page.click('#onb-signin'); await sleep(400); + await page.click('#onb-restore'); await sleep(400); await page.waitForSelector('textarea'); await page.type('textarea', generateMnemonic(wordlist)); await click('open wallet'); for (let i = 0; i < 80 && !(await page.evaluate(() => [...document.querySelectorAll('button')].some((b) => b.textContent.trim() === 'Send'))); i++) { await page.evaluate(() => [...document.querySelectorAll('button')].find((b) => /^(not now|skip|continue|later)$/i.test(b.textContent.trim()))?.click()); await sleep(400); } await sleep(1500); - check('the footer has "Show your support"', await link()); - // from another page: the feed - await page.evaluate(() => [...document.querySelectorAll('nav button, .bottom-nav button')].find((b) => /feed/i.test(b.textContent))?.click()); await sleep(800); - await page.evaluate(() => [...document.querySelectorAll('.footer button')].find((b) => b.textContent.trim() === 'Show your support').click()); + const f = await footerOnly(); + check('with a wallet open there is no footer', !f || (await page.$eval('.footer', (el) => getComputedStyle(el).display === 'none')), JSON.stringify(f)); + await page.evaluate(() => [...document.querySelectorAll('button')].find((e) => e.getAttribute('aria-label') === 'Settings').click()); await sleep(500); + check('Settings carries the language and currency', await page.evaluate(() => document.querySelectorAll('.settings-prefs select').length) === 2); + if (process.env.SHOT2) await page.screenshot({ path: process.env.SHOT2 }); + await page.evaluate(() => [...document.querySelectorAll('.settings-tile')].find((e) => /^About/.test(e.textContent.trim())).click()); await sleep(500); + const about = await page.evaluate(() => document.querySelector('.about-card')?.innerText || ''); + check('About has the credits, How it works, the theme and the commit', /Adam Soltys/.test(about) && /git\.coinos\.io/.test(about) && /How it works/.test(about) && /(Dark|Light) mode/.test(about) && /Running git commit [0-9a-f]{7}/.test(about), about.replace(/\n/g, ' | ')); + check('...and "Show your support"', await link()); + const th = await page.evaluate(() => document.documentElement.dataset.theme); + await page.click('#about-theme'); await sleep(300); + check('the theme switch works from there', await page.evaluate(() => document.documentElement.dataset.theme) !== th); + await page.click('#about-theme'); await sleep(300); + if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT }); + await page.click('#about-support'); await sleep(1200); const txt = await page.evaluate(() => document.body.innerText); - check('it opens the hat shop', /hat/i.test(txt) && !!(await page.evaluate(() => document.querySelector('.hat-btn') || /Crown|Top hat|hats?/i.test(document.querySelector('.card')?.innerText || ''))), txt.slice(0, 160).replace(/\n/g, ' | ')); - await page.evaluate(() => { document.querySelector('.bottom-nav, nav')?.remove(); window.scrollTo(0, 1e6); }); - await sleep(300); - if (process.env.SHOT) await (await page.$('.footer')).screenshot({ path: process.env.SHOT }); - else await page.screenshot({ path: '/tmp/footer-support.png', fullPage: true }); - // || '/tmp/footer-support.png', fullPage: true }); + check('it opens the hat shop', /hat/i.test(txt), txt.slice(0, 160).replace(/\n/g, ' | ')); check('no page errors', errs.length === 0, errs.join('; ').slice(0, 300)); } catch (e) { console.error(e); ok = false; } finally { await browser.close(); server.stop(); } console.log(ok ? 'PASS' : 'FAIL'); diff --git a/tools/gif-loop-test.js b/tools/gif-loop-test.js new file mode 100644 index 0000000..a135e36 --- /dev/null +++ b/tools/gif-loop-test.js @@ -0,0 +1,21 @@ +// A GIF made without a loop instruction plays once in every browser; the +// copy the feed paints from gets "loop forever" added. One that loops +// already, or isn't a GIF, is left alone. +// Run: bun tools/gif-loop-test.js +import { loopGif } from '../src/image-thumbnails.js'; +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const make = (args) => Bun.spawnSync(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=64x48:rate=5:duration=1', ...args, '-f', 'gif', 'pipe:1']).stdout; +const once = new Uint8Array(make(['-loop', '-1'])), looping = new Uint8Array(make(['-loop', '0'])); +const has = (b) => Buffer.from(b).includes('NETSCAPE2.0'); +check('ffmpeg made one GIF without a loop and one with', !has(once) && has(looping)); +const fixed = loopGif(once); +check('the one-shot GIF gets the loop extension', !!fixed && has(fixed)); +const i = Buffer.from(fixed).indexOf('NETSCAPE2.0'); +check('…loop forever (count 0), right after the colour table', fixed[i + 11] === 3 && fixed[i + 12] === 1 && fixed[i + 13] === 0 && fixed[i + 14] === 0 && fixed[i + 15] === 0 && fixed[i - 3] === 0x21 && fixed[i - 2] === 0xff); +const probe = Bun.spawnSync(['ffprobe', '-v', 'error', '-count_frames', '-show_entries', 'stream=nb_read_frames', '-of', 'csv=p=0', '-i', 'pipe:0'], { stdin: fixed }).stdout.toString().trim(); +check('the patched GIF still decodes, every frame', probe === '5', probe); +check('a GIF that loops already is left alone', loopGif(looping) === null); +check('not a GIF: left alone', loopGif(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])) === null); +console.log(ok ? '\n✅ GIFs loop' : '\n❌ failed'); +process.exit(ok ? 0 : 1); diff --git a/tools/hats-link-test.js b/tools/hats-link-test.js new file mode 100644 index 0000000..411dbd3 --- /dev/null +++ b/tools/hats-link-test.js @@ -0,0 +1,46 @@ +// v3.coinos.io/hats opens the hat shop. "Someone in the coinos group is +// asking where to get hats. Can we make the hat shop have a linkable url +// like v3.coinos.io/hats that I can direct him to?" (Adam, 2026-11-22). +// With a wallet the link lands in the shop; the bar says /hats while the +// shop is on screen and / again once it is left; someone with no wallet +// gets the shop after making one. +// Run: bun tools/hats-link-test.js +import puppeteer, { seedWords, skipSeedCheck } from './puppeteer.js'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 5348, fetch: (req) => { const p = new URL(req.url).pathname; if (p === '/verify-worker.js' || p.startsWith('/punks')) return new Response(Bun.file('dist' + p)); if (p.startsWith('/hats/')) return Response.json({ owned: [], equipped: null }); return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errs = []; +page.on('pageerror', (e) => errs.push(String(e))); +const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); +const text = () => page.evaluate(() => document.body.innerText); +const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await text()).toLowerCase().includes(x.toLowerCase())) return true; await sleep(250); } return false; }; +const path = () => page.evaluate(() => location.pathname); +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto('http://localhost:5348/', { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + // no wallet yet: the link, then a new wallet, then the shop + await page.goto('http://localhost:5348/hats', { waitUntil: 'domcontentloaded' }); await waitText('create a new wallet', 20000); await sleep(400); + check('with no wallet the link shows the way in, not the shop', !(await text()).includes('Hat shop')); + await click('create a new wallet'); await sleep(600); + await seedWords(page); + await skipSeedCheck(page); + check('...and the shop opens once the wallet is made', await waitText('Hat shop', 25000)); + // with a wallet: straight in + await page.goto('http://localhost:5348/hats', { waitUntil: 'domcontentloaded' }); + check('with a wallet /hats opens the hat shop', await waitText('Hat shop', 25000)); + await sleep(600); + check('the bar says /hats', (await path()) === '/hats', await path()); + await page.evaluate(() => [...document.querySelectorAll('button')].find((n) => /\bback\b/i.test(n.textContent))?.click()); await sleep(900); + const t = await text(); + check('Back leaves the shop', !t.includes('Hat shop')); + check('...and the bar is / again', (await path()) === '/', await path()); + check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); +} finally { await browser.close(); server.stop(true); } +console.log(ok ? '\n✅ /hats opens the hat shop' : '\n❌ failed'); +process.exit(ok ? 0 : 1); diff --git a/tools/link-preview-test.js b/tools/link-preview-test.js index 190b220..3b2aad3 100644 --- a/tools/link-preview-test.js +++ b/tools/link-preview-test.js @@ -19,6 +19,8 @@ const POSTS = [ finalizeEvent({ kind: 1, created_at: now - 30, tags: [], content: 'Well, yeah https://news.example/story/1' }, AUTHOR), finalizeEvent({ kind: 1, created_at: now - 60, tags: [], content: 'nothing here https://blank.example/page' }, AUTHOR), finalizeEvent({ kind: 1, created_at: now - 90, tags: [], content: 'a picture http://localhost:5311/pic.png' }, AUTHOR), + finalizeEvent({ kind: 1, created_at: now - 120, tags: [], content: 'film night https://paff.club/movie/1382-hackers-1995/play?q=1080p&t=4910' }, AUTHOR), + finalizeEvent({ kind: 1, created_at: now - 150, tags: [], content: 'on repeat https://paff.club/song/abc123' }, AUTHOR), ]; const PROFILE = finalizeEvent({ kind: 0, created_at: now - 100, tags: [], content: JSON.stringify({ name: 'Linker', picture: 'http://localhost:5311/face.png' }) }, AUTHOR); @@ -30,14 +32,38 @@ const server = Bun.serve({ port: 5311, fetch: (req) => { const target = u.searchParams.get('url'); previewHits.push(target); const meta = target === 'https://news.example/story/1' ? { url: target, title: 'Lawmakers doubt the plan', description: 'A story in one line.', image: 'http://localhost:5311/card.png', site: 'News Example' } - : {}; + : target === 'https://movies.example/movie/1382/play?t=4910' || target.startsWith('https://paff.club/movie/1382') + ? { url: target, title: 'Hackers (1995) · from 1:21:50', description: 'Teenage hackers.', image: 'http://localhost:5311/movie.png', site: 'PAFF' } + : target === 'https://paff.club/song/abc123' + ? { url: target, title: 'Halcyon · Orbital', description: 'Orbital 2 · 1993', image: 'http://localhost:5311/cover.png', site: 'PAFF' } + : {}; return new Response(JSON.stringify(meta), { headers: { 'content-type': 'application/json', 'access-control-allow-origin': '*' } }); } if (u.pathname.endsWith('.png')) return new Response(PNG, { headers: { 'content-type': 'image/png' } }); if (u.pathname.startsWith('/punks') || u.pathname === '/verify-worker.js') return new Response(Bun.file('dist' + u.pathname)); return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); -const browser = await puppeteer.launch({ relays: 'read', executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +// a stand-in paff.club (self-signed, resolved here): its embed player speaks +// PAFF's postMessage protocol and logs the commands it gets +const certDir = (await import('node:fs')).mkdtempSync((await import('node:os')).tmpdir() + '/paff-cert-'); +Bun.spawnSync(['openssl', 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-days', '1', '-subj', '/CN=paff.club', + '-keyout', certDir + '/k.pem', '-out', certDir + '/c.pem']); +const paffLog = []; +const paffServer = Bun.serve({ port: 5313, tls: { cert: Bun.file(certDir + '/c.pem'), key: Bun.file(certDir + '/k.pem') }, fetch: async (req) => { + const u = new URL(req.url); + if (u.pathname === '/log') { paffLog.push(await req.text()); return new Response('ok'); } + return new Response(`<!doctype html><body style="background:#000;color:#fff">player<script> + const say = (event) => parent.postMessage({ source: 'paff', event, t: 0 }, '*'); + setTimeout(() => say('playing'), 150); + addEventListener('message', (e) => { + if (e.data?.source !== 'paff' || !e.data.command) return; + fetch('/log', { method: 'POST', body: e.data.command }); + say(e.data.command === 'pause' ? 'pause' : 'playing'); + }); + </script>`, { headers: { 'content-type': 'text/html' } }); +} }); +const browser = await puppeteer.launch({ relays: 'read', executablePath: '/usr/bin/google-chrome', headless: 'new', + args: ['--no-sandbox', '--host-resolver-rules=MAP paff.club:443 127.0.0.1:5313', '--ignore-certificate-errors'] }); const page = await browser.newPage(); await page.evaluateOnNewDocument((posts, profile) => { // the registrar's preview endpoint answers from this test's server @@ -113,11 +139,69 @@ try { check('...and its picture, already decoded', !!story?.thumb && story.thumbShown, JSON.stringify({ thumb: story?.thumb, shown: story?.thumbShown })); check('a page with nothing to show stays a bare link', !!blank && blank.bareLink && !blank.card, JSON.stringify(blank)); check('a picture link is still a picture, not a card', !!pic && pic.img && !pic.card, JSON.stringify(pic)); + // a PAFF film link plays in the post, PAFF's bare player loaded only on a tap + const paff = await page.evaluate(() => { + const r = [...document.querySelectorAll('.notes-feed > .row')].find((n) => /film night/.test(n.textContent)); + const b = r && r.querySelector('.paff-embed'); + return b && { title: b.querySelector('.paff-title')?.textContent, poster: !!b.querySelector('img.yt-poster'), frame: !!b.querySelector('iframe') }; + }); + check('a PAFF film link shows as a player with its backdrop and title', !!paff && paff.poster && /Hackers/.test(paff.title || '') && !paff.frame, JSON.stringify(paff)); + const src = await page.evaluate(() => { + const b = [...document.querySelectorAll('.paff-embed')][0]; + b.scrollIntoView({ block: 'center' }); + b.querySelector('.yt-play').click(); + return b.querySelector('iframe')?.getAttribute('src'); + }); + check('...and a tap loads PAFF\'s embed player there, the link\'s query kept', src === 'https://paff.club/embed/movie/1382-hackers-1995?q=1080p&t=4910', src); + await sleep(900); // the stand-in reports it's playing + await page.evaluate(() => scrollTo(0, document.documentElement.scrollHeight + 5000)); + await page.evaluate(() => { const s = document.createElement('div'); s.style.height = '3000px'; s.id = 'pad'; document.body.append(s); scrollTo(0, document.documentElement.scrollHeight); }); + for (let i = 0; i < 20 && !paffLog.includes('pause'); i++) await sleep(150); + check('a playing film pauses once its post is off the screen', paffLog.includes('pause'), JSON.stringify(paffLog)); + await page.evaluate(() => document.querySelector('.paff-embed').scrollIntoView({ block: 'center' })); + for (let i = 0; i < 20 && !paffLog.includes('play'); i++) await sleep(150); + check('...and carries on when it comes back', paffLog.join() === 'pause,play', JSON.stringify(paffLog)); + await page.evaluate(() => { document.getElementById('pad')?.remove(); scrollTo(0, 0); }); + // a PAFF song plays in the bar above the nav, and keeps playing as you go + const song = await page.evaluate(() => { + const c = document.querySelector('.paff-song'); + return c && { title: c.querySelector('.paff-song-title')?.textContent, cover: !!c.querySelector('img.paff-song-cover'), frame: !!c.querySelector('iframe') }; + }); + check('a PAFF song link is a card with its cover and title', !!song && song.cover && song.title === 'Halcyon · Orbital' && !song.frame, JSON.stringify(song)); + await page.evaluate(() => { const c = document.querySelector('.paff-song'); c.scrollIntoView({ block: 'center' }); c.click(); }); + await sleep(300); + const bar = await page.evaluate(() => { + const b = document.querySelector('.music-bar'), f = b?.querySelector('iframe'), nav = document.querySelector('.app-bottom-nav'); + const r = b?.getBoundingClientRect(), n = nav?.getBoundingClientRect(); + return b && { src: f?.getAttribute('src'), above: !n || r.bottom <= n.top + 1, playing: document.querySelector('.paff-song')?.textContent.includes('Playing below') }; + }); + check('a tap plays it in the bar above the nav', !!bar && bar.src === 'https://paff.club/embed/song/abc123?bar=1' && bar.above, JSON.stringify(bar)); + check('...and the card says it is playing', !!bar?.playing); + if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT }); + await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Wallet"]')?.click()); + await sleep(500); + const still = await page.evaluate(() => document.querySelector('.music-bar iframe')?.getAttribute('src')); + check('the song carries on on another page', still === 'https://paff.club/embed/song/abc123?bar=1', still); + await page.evaluate(() => document.querySelector('.music-close').click()); + check('× stops and closes it', await page.evaluate(() => !document.querySelector('.music-bar') && !document.body.classList.contains('music-open'))); + await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]').click()); + await sleep(500); check('the registrar was asked once per link', previewHits.filter((u) => u === 'https://news.example/story/1').length === 1 && !previewHits.some((u) => u.endsWith('.png')), JSON.stringify(previewHits)); let kept = 0; // written behind, a second after the card was learned - for (let i = 0; i < 12 && !kept; i++) { kept = await page.evaluate(() => JSON.parse((window.coinosCache || localStorage).getItem('coinos-link-previews') || '[]').length); if (!kept) await sleep(300); } - check('the card is remembered for next time', kept === 1, kept + ' kept'); + for (let i = 0; i < 12 && kept < 3; i++) { kept = await page.evaluate(() => JSON.parse((window.coinosCache || localStorage).getItem('coinos-link-previews') || '[]').length); if (kept < 3) await sleep(300); } + check('the cards are remembered for next time', kept === 3, kept + ' kept'); // the story's, the film's and the song's + // a draft's preview shows the card too (Adam, 2026-11-17: a paff.club + // movie link stayed a bare URL in Preview), once the typing settles + const opened = await page.evaluate(() => { const b = [...document.querySelectorAll('button')].find((n) => (n.getAttribute('aria-label') || n.textContent).trim().toLowerCase() === 'new post'); if (b) { b.click(); return true; } return false; }); + await sleep(400); + const typeDraft = (v) => page.evaluate((val) => { const e = document.querySelector('coinos-text'); e.focus(); e.value = val; e.dispatchEvent(new Event('input', { bubbles: true })); }, v); + await typeDraft('watch this\n\nhttps://movies.example/movie/1382/play?t=4910'); + await page.evaluate(() => [...document.querySelectorAll('button')].find((b) => /preview/i.test(b.getAttribute('aria-label') || ''))?.click()); + let draft = null; + for (let i = 0; i < 20; i++) { draft = await page.evaluate(() => { const p = document.querySelector('.draft-preview'); return p && { card: !!p.querySelector('.link-card'), title: p.querySelector('.link-title')?.textContent }; }); if (draft?.card) break; await sleep(250); } + check('a draft\'s preview shows the link as its card', opened && draft?.card && /Hackers/.test(draft.title || ''), JSON.stringify(draft)); + check('...asked for once the typing settled, not per keystroke', previewHits.filter((u) => u.startsWith('https://movies.example')).length === 1, JSON.stringify(previewHits)); check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); -} finally { await browser.close(); server.stop(true); } +} finally { await browser.close(); server.stop(true); paffServer.stop(true); } console.log(ok ? '\n✅ links show as the cards their pages describe' : '\n❌ failed'); process.exit(ok ? 0 : 1); diff --git a/tools/live-stream-test.js b/tools/live-stream-test.js index 56dcb71..cf5e056 100644 --- a/tools/live-stream-test.js +++ b/tools/live-stream-test.js @@ -224,6 +224,30 @@ try { const rowSel = '.live-message[data-key="' + chat.id + '"]'; check('comments use the group-chat bubble and shared composer', await page.$(rowSel + ' .chat-bubble') && await page.$('.live-page coinos-text#msg-draft')); check('...drawn plain on a phone, no bubble walls', await page.evaluate((q) => { const b = document.querySelector(q); return b && getComputedStyle(b).borderStyle === 'none' && getComputedStyle(b).display === 'block'; }, rowSel + ' .chat-bubble')); + // the message box is on screen without scrolling the page: the chat takes + // the room left under the stream, down to the nav (it was a fixed 60vh and + // the card ran off the bottom, where a swipe inside the chat couldn't + // bring it up) + { + const fit = await page.evaluate(() => { + window.scrollTo(0, 0); + const r = (q) => document.querySelector(q)?.getBoundingClientRect(); + const box = r('.live-page coinos-text#msg-draft'), nav = r('.app-bottom-nav'), chat = document.querySelector('.live-page .live-chat'); + return { box: box && Math.round(box.bottom), nav: nav ? Math.round(nav.top) : innerHeight, chat: chat.clientHeight, behaviour: getComputedStyle(chat).overscrollBehaviorY }; + }); + check('on a phone the message box sits on screen, over the nav', fit.box && fit.box <= fit.nav && fit.chat >= 120, JSON.stringify(fit)); + check('...and the chat no longer holds a scroll that reaches its end', fit.behaviour === 'auto'); + // a wall of chat: the box stays where it is, the newest line just above it + await page.addStyleTag({ content: '.live-page .live-chat::before{content:"";flex:none;height:3000px}' }).then((el) => el.evaluate((n) => { n.id = 'tall-chat'; })); + await page.evaluate(() => { const c = document.querySelector('.live-page .live-chat'); c.scrollTop = c.scrollHeight; }); + const tall = await page.evaluate(() => { + const r = (q) => document.querySelector(q)?.getBoundingClientRect(); + const c = document.querySelector('.live-page .live-chat'), last = c.lastElementChild.getBoundingClientRect(), nav = r('.app-bottom-nav'); + return { box: Math.round(r('.live-page coinos-text#msg-draft').bottom), nav: nav ? Math.round(nav.top) : innerHeight, last: Math.round(last.bottom), chatBottom: Math.round(c.getBoundingClientRect().bottom), pageY: window.scrollY }; + }); + check('...with a long chat too, the newest line showing above it', tall.box <= tall.nav && tall.last <= tall.chatBottom + 1 && tall.pageY === 0, JSON.stringify(tall)); + await page.evaluate(() => document.getElementById('tall-chat')?.remove()); + } check('another client’s e-only reaction arrives on the comment', await waitFor(id => document.querySelector('.live-message[data-key="'+id+'"] .chat-reacts')?.textContent.includes('👍'), 6000, chat.id)); check('per-comment zap receipts show under the bubble', await waitFor(id => document.querySelector('.live-message[data-key="'+id+'"] .zap-tally')?.textContent.includes('5'), 6000, chat.id)); await page.click(rowSel + ' .chat-bubble'); diff --git a/tools/ln-pay-double-wake.test.js b/tools/ln-pay-double-wake.test.js index 18a1943..c29d625 100644 --- a/tools/ln-pay-double-wake.test.js +++ b/tools/ln-pay-double-wake.test.js @@ -18,7 +18,7 @@ const asp = { initiate: null, check: null, revoked: 0, checks: 0 }; mock.module('../src/ark/lightning.js', () => ({ ...realLn, initiateLightningPayment: async () => { if (asp.initiate) throw asp.initiate; }, - checkLightningPayment: async () => { asp.checks++; if (asp.check instanceof Error) throw asp.check; return asp.check; }, + checkLightningPayment: async (_u, _h, wait) => { asp.checks++; (asp.waits = asp.waits || []).push(!!wait); if (asp.check instanceof Error) throw asp.check; return asp.check; }, requestLightningPayHtlcRevocation: async () => { asp.revoked++; throw new Error('revocation should not be asked for'); }, })); mock.module('../src/ark/proto.js', () => ({ ...realProto, decodeVtxo: () => ({ id: 'htlc1', point: { raw: new Uint8Array(36) } }) })); @@ -72,3 +72,40 @@ test("a send the ASP never saw (not found) is still revoked", async () => { await m._driveLnPay(action).catch(() => {}); expect(asp.revoked).toBe(1); }); + +// A zap's wait is made of round trips (398ja, 2026-11-10: NWC zaps "a lot more +// slower"). A send just handed to the ASP used to ask its status at once +// ("pending"), fetch the chain tip to go with that, hold a call until it +// settled, then ask once more for the preimage it had just been given: four +// round trips where the one held call does. +test('a fresh send: initiate, then the one held call settles it', async () => { + Object.assign(asp, { initiate: null, check: { status: 'success', preimage: PRE }, revoked: 0, checks: 0, waits: [] }); + const { m, action } = mgrWith('cosigned'); + let tips = 0; + m.chain = { tipHeight: async () => { tips++; return 900; } }; + await m._driveLnPay(action); + expect(action.step).toBe('initiated'); // handed over, nothing asked yet + expect(asp.checks).toBe(0); + expect(tips).toBe(0); + const a = await m.awaitLnPay(action.id, 5000); + expect(a.step).toBe('done'); + expect(a.preimage).toBe(PRE); + expect(asp.waits).toEqual([true]); // the held call alone + expect(m.state.movements.filter((x) => x.type === 'ln-send' && x.status === 'complete').length).toBe(1); +}); + +test('a held call that comes back failed is checked the ordinary way (and revoked)', async () => { + Object.assign(asp, { initiate: null, check: { status: 'failed' }, revoked: 0, checks: 0, waits: [] }); + const { m, action } = mgrWith('initiated'); + m._revokeLnPay = async (x) => { x.step = 'failed'; }; + const a = await m.awaitLnPay(action.id, 5000); + expect(asp.waits[0]).toBe(true); + expect(a.step).toBe('failed'); +}); + +test('a held call with a preimage that does not match the hash settles nothing', async () => { + Object.assign(asp, { initiate: null, check: { status: 'success', preimage: 'cd'.repeat(32) }, revoked: 0, checks: 0, waits: [] }); + const { m, action } = mgrWith('initiated'); + const a = await m.awaitLnPay(action.id, 5000); + expect(a.step).not.toBe('done'); +}); diff --git a/tools/lnurl-withdraw-links-test.js b/tools/lnurl-withdraw-links-test.js new file mode 100644 index 0000000..0e0b340 --- /dev/null +++ b/tools/lnurl-withdraw-links-test.js @@ -0,0 +1,187 @@ +// Prepaid withdraw links (src/features/withdraw-links.js + coinosv3-server +// names/withdraw.js): create one from Send (it pays the registrar up front), +// get an LNURL QR, have it claimed — here by our own LNURL-withdraw redeem +// flow (zaps.js), the same road any Lightning wallet takes — and take back +// what's left. The registrar is the real withdraw service behind a stand-in +// HTTP server (NIP-98 checked) with a fake Lightning node; the Ark side is +// faked through the hooks. Run: bun tools/lnurl-withdraw-links-test.js +import assert from 'node:assert/strict'; +import { verifyEvent } from 'nostr-tools/pure'; +import puppeteer from './puppeteer.js'; +import { withdrawService } from '../../coinosv3-server/names/withdraw.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 { withdrawLinks } from './src/features/withdraw-links.js'; +import { zapsFeature } from './src/features/zaps.js'; +import { finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools/pure'; +${domHelper} +const sk = generateSecretKey(); +const ui = { screen: 'wallet', tab: 'send', giftMode: false, send: { recipients: [{ address: '', amount: '' }] } }; +let lnInvoices = 0; const watched = []; +const wallet = { watchOnly: false, nostrSign: async (e) => finalizeEvent(e, sk), loadFeatureState: (k, d) => d, saveFeatureState: () => {} }; +const api = async (p) => (await fetch(p)).json(); +const ctx = { + h, ui, wallet, render, toast: (m) => (window.toasts = (window.toasts || [])).push(m), + withdrawRegistrar: location.origin, + copyBtn: (v, label) => h('button', { class: 'btn-sm', onClick: () => { window.copied = v; } }, label), + goBack: (fn) => { fn(); render(); }, + blankSend: () => ({ recipients: [{ address: '', amount: '' }] }), + fmtAmount: (n) => Number(n).toLocaleString('en-US'), unitLabel: () => 'sats', unitTag: () => h('span', { class: 'unit-tag' }, 'sats'), + parseAmount: (v) => { const n = Number(String(v).replace(/,/g, '')); return isFinite(n) && n > 0 ? Math.round(n) : null; }, getUnit: () => 'sats', + amountField: (sat) => String(sat), + hook(name, ...a) { + if (name === 'arkReady' || name === 'canLnPay') return true; + if (name === 'arkSpendableSat') return window.spendable ?? 100000; + if (name === 'arkPayInvoice') { window.paidInvoices = (window.paidInvoices || 0) + 1; return api('/__pay?bolt11=' + a[0]); } + // a coinos wallet's Lightning receive lives on the registrar's own node + if (name === 'arkLnInvoice') { lnInvoices++; return api('/__mkinv?own=1&sat=' + a[0]).then((r) => ({ id: 'ln' + lnInvoices, invoice: r.bolt11, amountSat: a[0] })); } + if (name === 'arkLnWatch') { watched.push(a[0]); return true; } + if (name === 'arkLnUnwatch' || name === 'arkLnCancel') return true; + return null; + }, +}; +const wl = withdrawLinks(ctx); +const zaps = zapsFeature(ctx); +function render() { + const v = (ui.giftMode === 'lnurl' && wl.view()) || zaps.sendView() || h('div', { id: 'closed' }, wl.entry()); + document.querySelector('#app').replaceChildren(v); +} +window.test = { ui, render, pk: getPublicKey(sk), redeem: (s) => zaps.matchSendText(s, false), watched }; +render(); +`; +const bundle = await Bun.build({ + entrypoints: ['wl-test-entry'], target: 'browser', + plugins: [{ name: 'wl-test', setup(build) { + build.onResolve({ filter: /^wl-test-entry$/ }, () => ({ path: 'entry', namespace: 'wl-test' })); + build.onLoad({ filter: /.*/, namespace: 'wl-test' }, () => ({ contents: entry, loader: 'js', resolveDir: process.cwd() })); + } }], +}); +assert(bundle.success, bundle.logs.join('\n')); +const css = await Bun.file('src/style.css').text(); +const js = await bundle.outputs[0].text(); +const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><style>${css}</style><div id="app"></div><script type="module">${js}</script>`; + +// ---- the stand-in registrar: the real service, a fake node ---- +const OUR = '02' + 'aa'.repeat(32), THEIRS = '03' + 'bb'.repeat(32); +const invoices = {}, decoded = {}, outbound = {}; +let seq = 0, circular = 0, routeless = false; +const mk = (sat, payee) => { const hash = (++seq).toString(16).padStart(64, '0'); const b = 'lnbc' + sat + 'n1fake' + seq; decoded[b] = { valid: true, payment_hash: hash, amount_msat: sat * 1000, payee, created_at: Math.floor(Date.now() / 1000), expiry: 3600 }; return { b, hash }; }; +const ln = { async call(m, p) { + if (m === 'invoice') { const { b, hash } = mk(p.amount_msat / 1000, OUR); invoices[hash] = { status: 'unpaid', bolt11: b }; return { bolt11: b, payment_hash: hash }; } + if (m === 'listinvoices') return { invoices: invoices[p.payment_hash] ? [invoices[p.payment_hash]] : [] }; + if (m === 'decode') { if (!decoded[p.string]) throw new Error('bad'); return decoded[p.string]; } + if (m === 'pay') { const d = decoded[p.bolt11]; if (routeless) { outbound[d.payment_hash] = 'failed'; throw new Error('Failed: We could not find a usable set of paths'); } outbound[d.payment_hash] = 'complete'; return { status: 'complete', amount_msat: d.amount_msat, amount_sent_msat: d.amount_msat }; } + if (m === 'waitsendpay') { outbound[p.payment_hash] = 'complete'; return { status: 'complete' }; } + if (m === 'listsendpays') return { payments: outbound[p.payment_hash] ? [{ status: outbound[p.payment_hash] }] : [] }; + throw new Error('unexpected ' + m); +} }; +const state = {}; +let svc; // made once the server has its port: the service's URLs are built on it +const nip98 = async (req, url, body) => { + const evt = JSON.parse(atob((req.headers.get('authorization') || '').replace(/^Nostr /, ''))); + assert(verifyEvent(evt) && evt.kind === 27235 && new URL(evt.tags.find((t) => t[0] === 'u')[1]).pathname === url.pathname); + return evt.pubkey; +}; +const server = Bun.serve({ port: 0, async fetch(req) { + const u = new URL(req.url); + const j = (b, s = 200) => Response.json(b, { status: s }); + if (u.pathname === '/__pay') { const d = decoded[u.searchParams.get('bolt11')]; invoices[d.payment_hash].status = 'paid'; return j({ ok: true }); } + if (u.pathname === '/__mkinv') { const { b } = mk(Number(u.searchParams.get('sat')), u.searchParams.get('own') ? OUR : THEIRS); return j({ bolt11: b }); } + const w = u.pathname.match(/^\/w\/([A-Za-z0-9_-]+)(\/cb)?$/); + if (w) return j(w[2] ? await svc.callback(w[1], u.searchParams.get('k1'), u.searchParams.get('pr')) : svc.params(w[1])); + if (u.pathname.startsWith('/withdraw/')) { + const body = req.method === 'POST' ? await req.text() : ''; + const pk = await nip98(req, u, body); + const b = body ? JSON.parse(body) : {}; + try { + if (u.pathname === '/withdraw/mine') return j({ links: svc.mine(pk) }); + if (u.pathname === '/withdraw/new') return j(await svc.create({ pubkey: pk, ...b })); + if (u.pathname === '/withdraw/funded') return j(await svc.confirmFunded(b.id, pk)); + if (u.pathname === '/withdraw/reclaim') return j(await svc.reclaim(b.id, pk, b.invoice)); + } catch (e) { return j({ error: e.message }, e.status || 500); } + } + return new Response(html, { headers: { 'content-type': 'text/html' } }); +} }); +svc = withdrawService({ state, persist: () => {}, lnFor: () => ln, ourNodeId: async () => OUR, + circularPick: async () => ({ cap: 1e9 }), payCircular: async () => { circular++; return { feeMsat: 0 }; }, wait: async () => {}, publicBase: server.url.origin.replace(/\/$/, '') }); + +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, ' ')); +const waitText = async (re, ms = 6000) => { for (let i = 0; i < ms / 100; i++) { if (re.test(await text())) return true; await pause(100); } return false; }; +const click = (label) => page.evaluate((x) => { const b = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().startsWith(x)); if (!b) return false; b.click(); return true; }, label); +const type = (sel, v) => page.evaluate(([s, val]) => { const i = document.querySelector(s); i.value = val; i.dispatchEvent(new Event('input', { bubbles: true })); }, [sel, v]); +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto(server.url.href); + await page.waitForSelector('#wl-open'); + console.log('[making a link]'); + await page.click('#wl-open'); + check('Send opens the withdraw-link page', await waitText(/A Lightning link or QR code that anyone can withdraw sats from/)); + await page.click('#wl-create'); + check('no amount: asked for one, nothing paid', await waitText(/Enter an amount/) && !(await page.evaluate(() => window.paidInvoices))); + await type('#wl-amount', '500'); await type('#wl-uses', '3'); + check('the button and the line say what gets paid now', /Create link for 1,500 sats/.test(await text()) && /1,500 sats paid now from Spending: 3 withdrawals of up to 500 sats/.test(await text()), await text()); + await page.evaluate(() => { window.spendable = 1000; }); + await page.click('#wl-create'); + check('more than Spending holds: refused before paying', await waitText(/Not enough in Spending for 1,500 sats/) && !(await page.evaluate(() => window.paidInvoices))); + await page.evaluate(() => { window.spendable = 100000; }); + await type('textarea', 'Meetup door prize'); + await page.click('#wl-create'); + check('it pays the registrar once and shows the link', await waitText(/Your withdraw link is ready/) && (await page.evaluate(() => window.paidInvoices)) === 1, await text()); + check('…with a QR, the terms and the note', !!(await page.$('svg')) && /Up to 500 sats each, 3 of 3 withdrawals left/.test(await text()) && /Meetup door prize/.test(await text()), await text()); + const lnurl = await page.evaluate(() => [...document.querySelectorAll('.addr-box')].map((e) => e.textContent.trim())[0]); + check('the link is an LNURL', /^LNURL1[0-9A-Z]+$/.test(lnurl), lnurl); + const link = Object.values(state.withdraws)[0]; + check('the registrar holds it funded', link.status === 'open' && link.totalSat === 1500 && link.pubkey === (await page.evaluate(() => test.pk))); + + console.log('\n[claiming it with a Lightning wallet: ours]'); + await click('Back'); + await page.evaluate(() => { test.ui.giftMode = false; }); + check('the redeem flow takes the LNURL', await page.evaluate((s) => test.redeem(s), lnurl)); + check('…and reads the link\'s terms', await waitText(/will pay you between 1 and 500 sats/) && /Meetup door prize/.test(await text()), await text()); + await click('Withdraw'); + check('the claim is paid out of the link', await waitText(/has your invoice for 500 sats/) && (await (async () => { await pause(100); return link.claims[0]?.status === 'paid'; })()), JSON.stringify(link.claims)); + check('…round the circular route (a coinos wallet\'s own invoice)', circular === 1); + + console.log('\n[taking back the rest]'); + await page.evaluate(() => { test.ui.lnWithdraw = null; test.ui.giftMode = false; test.render(); }); + await page.evaluate(() => document.querySelector('#wl-open').click()); + check('the list shows what is left', await waitText(/Your withdraw links/) && /1,000 sats left/.test(await text()), await text()); + await page.evaluate(() => document.querySelector('.wl-row').click()); + check('the link page shows 2 of 3 left', await waitText(/2 of 3 withdrawals left/)); + await click('Take back 1,000 sats'); + check('take back pays the remainder to the wallet and closes the link', await waitText(/This link is closed/) && link.status === 'closed' && link.spentSat === 1500, JSON.stringify(link)); + check('…and the wallet watched for that payment', (await page.evaluate(() => test.watched.length)) >= 1); + check('…the toast says so', (await page.evaluate(() => window.toasts || [])).some((m) => /1,000 sats is back in Spending/.test(m))); + check('a closed link refuses claims', svc.params(link.id).status === 'ERROR'); + + console.log('\n[a claim with no route to the wallet that asked]'); + await click('← Back'); + if (!(await page.$('#wl-amount'))) await page.evaluate(() => document.querySelector('#wl-open')?.click()); + await page.waitForSelector('#wl-amount', { timeout: 3000 }).catch(async () => { throw new Error('no form: ' + await text()); }); + await type('#wl-amount', '700'); await type('#wl-uses', '1'); await type('textarea', ''); + await page.click('#wl-create'); + check('a second link is made', await waitText(/Your withdraw link is ready/)); + const link2 = Object.values(state.withdraws).find((x) => x.id !== link.id); + routeless = true; + const theirs = mk(700, THEIRS).b; + check('the claimer is told OK (LUD-03 pays after)', (await svc.callback(link2.id, link2.k1, theirs)).status === 'OK'); + for (let i = 0; i < 50 && link2.claims[0]?.status !== 'failed'; i++) await pause(20); + check('it was tried again before giving up, and the sats went back', link2.claims[0].status === 'failed' && link2.claims[0].tries > 1 && link2.spentSat === 0, JSON.stringify(link2)); + await page.evaluate(() => { test.ui.giftMode = false; test.render(); document.querySelector('#wl-open').click(); }); + check('the list says the claim failed', await waitText(/claim failed · 700 sats left/), await text()); + await page.evaluate(() => [...document.querySelectorAll('.wl-row')].find((b) => /claim failed/.test(b.textContent)).click()); + check('the link page says nothing was sent and the sats are still here', await waitText(/A claim of 700 sats couldn't be delivered.*sats are still in this link/), await text()); + check('…and still offers the QR and take back', !!(await page.$('svg')) && /Take back 700 sats/.test(await text())); + routeless = false; + check('the same link pays a claim once a route is there', (await svc.callback(link2.id, link2.k1, mk(700, THEIRS).b)).status === 'OK' && (await (async () => { await pause(50); return link2.claims[1]?.status === 'paid'; })()), JSON.stringify(link2.claims)); + check('no page errors', errors.length === 0, errors.join('; ')); + console.log('\n✅ prepaid withdraw links'); +} catch (e) { console.error('\n❌', e.message); process.exitCode = 1; } finally { await browser.close(); server.stop(true); } diff --git a/tools/lnurl-withdraw-test.js b/tools/lnurl-withdraw-test.js index cc1b152..0241f31 100644 --- a/tools/lnurl-withdraw-test.js +++ b/tools/lnurl-withdraw-test.js @@ -22,7 +22,7 @@ const ctx = { parseAmount: (v) => { const n = Number(String(v).replace(/,/g, '')); return isFinite(n) ? Math.round(n) : null; }, getUnit: () => 'sats', amountField: (sat) => String(sat), hook(name, ...a) { - if (name === 'canLnPay') return true; + if (name === 'canLnPay') return !window.noPay; if (name === 'arkLnInvoice') { invoices++; return Promise.resolve({ id: 'ln' + invoices, invoice: 'lnbc' + a[0] + 'n1testinvoice' + invoices, amountSat: a[0] }); } if (name === 'arkLnWatch') { watch = { id: a[0], cb: a[1] }; return true; } if (name === 'arkLnUnwatch') { if (watch && watch.id === a[0]) watch = null; return true; } @@ -94,6 +94,13 @@ try { await click('Back'); await pause(50); check('Back before it is paid stops watching', (await page.evaluate(() => test.watch)) === null && !!(await page.$('#closed'))); + console.log('[scanned while Spending is still connecting]'); + await page.evaluate(() => { window.noPay = true; }); + check('a withdraw lnurl is still taken (it pays us; nothing to spend)', await page.evaluate((s) => test.paste(s), lnurl('/withdraw'))); + check('…and opens as a withdraw, not a zap', await waitText(/Withdraw over Lightning/) && !/Zap/.test(await text()), await text()); + await click('Back'); await pause(50); + await page.evaluate(() => { window.noPay = false; }); + console.log('[a site that refuses]'); await page.evaluate((s) => test.paste(s), lnurl('/withdraw-spent')); await waitText(/will pay you 1 sats/); await click('Withdraw'); diff --git a/tools/media-moments-feed-test.js b/tools/media-moments-feed-test.js index 5b4c8fb..00baf9c 100644 --- a/tools/media-moments-feed-test.js +++ b/tools/media-moments-feed-test.js @@ -140,7 +140,10 @@ try { check('no "at this time" buttons', await page.evaluate(() => !document.body.innerText.includes('at this time'))); await act('.note-audio', 'Like'); await page.waitForSelector('.msg-sheet'); - await page.evaluate(() => document.querySelector('.msg-sheet button').click()); + // the moment is offered, not taken (Adam, 2026-11-14): tick it to tie the reaction to 0:05 + check('the reaction sheet offers the moment, off', await page.evaluate(() => { const b = document.querySelector('.msg-sheet .moment-toggle'); return !!b && b.getAttribute('aria-pressed') === 'false' && b.textContent.includes('0:05'); })); + await page.click('.msg-sheet .moment-toggle'); + await page.evaluate(() => document.querySelector('.msg-sheet button:not(.moment-toggle)').click()); await sleep(400); const reaction = await page.evaluate(() => window.__relayGuard.events.find(e => e.kind === 7 && e.tags.some(t => t[0] === 'media'))); check('reaction is signed with the selected file and position', reaction?.tags.some(t => t[0] === 'media' && t[2] === '5')); @@ -149,7 +152,9 @@ try { await page.screenshot({ path: '/tmp/media-timeline-playing.png' }); await act('.note-audio', 'Reply'); await page.waitForSelector('.thread-reply-input'); - check('timestamp is visible in the reply composer', (await page.evaluate(() => document.body.innerText)).includes('Comment at 0:05')); + check('the reply composer offers the moment, off', await page.evaluate(() => { const b = document.querySelector('.thread-reply .moment-toggle'); return !!b && b.getAttribute('aria-pressed') === 'false' && b.textContent.includes('0:05'); })); + await page.click('.thread-reply .moment-toggle'); + check('…tapped, it is on', await page.evaluate(() => document.querySelector('.thread-reply .moment-toggle').getAttribute('aria-pressed') === 'true')); await page.evaluate(() => { const input = document.querySelector('.thread-reply-input'); input.value = 'Great moment'; input.dispatchEvent(new Event('input', { bubbles: true })); }); await page.click('.thread-reply-send'); await sleep(500); @@ -169,7 +174,8 @@ try { await sleep(150); await page.evaluate(() => document.querySelector('.media-pager .mp-cur .mp-like').click()); await page.waitForSelector('.msg-sheet'); - await page.evaluate(() => document.querySelector('.msg-sheet button').click()); + await page.evaluate(() => document.querySelector('.msg-sheet .moment-toggle').click()); + await page.evaluate(() => document.querySelector('.msg-sheet button:not(.moment-toggle)').click()); await sleep(300); check('video reaction carries the video URL and selected second', await page.evaluate(() => window.__relayGuard.events.some(e => e.kind === 7 && e.tags.some(t => t[0] === 'media' && t[1].endsWith('.mp4') && t[2] === '1')))); check('...and shows over the pager\'s seek bar', await page.waitForFunction(() => !!document.querySelector('.media-pager .mp-cur .mp-seek .mp-mark'), { timeout: 3000 }).then(() => true, () => false)); diff --git a/tools/mention-ac-test.js b/tools/mention-ac-test.js index e476e61..04d7e12 100644 --- a/tools/mention-ac-test.js +++ b/tools/mention-ac-test.js @@ -106,11 +106,16 @@ try { await sleep(300); check('...and on a second line, in place', /\ncc nostr:npub1[a-z0-9]+ $/.test(await value()) && !(await value()).includes('@glo'), JSON.stringify((await value()).slice(-90))); + // a name typed out in full and never picked from the list + await page.keyboard.type('ty @globetrotter and @nobody9 ok'); + await sleep(300); + console.log('\n[posting]'); await page.evaluate(() => { window.__published = []; [...document.querySelectorAll('.post-actions button')].find((b) => /^post$/i.test(b.textContent.trim())).click(); }); await waitFor(() => window.__published.some((e) => e.kind === 1), 8000); const ev = (await page.evaluate(() => window.__published)).find((e) => e.kind === 1); check('the post carries both p tags', !!ev && [FRIEND, STRANGER].every((pk) => ev.tags.some((x) => x[0] === 'p' && x[1] === pk)), JSON.stringify(ev && ev.tags)); + check('a followed name typed out, not picked, goes out as their npub', !!ev && ev.content.endsWith('ty nostr:' + npubEncode(FRIEND) + ' and @nobody9 ok'), JSON.stringify(ev && ev.content.slice(-110))); check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); } finally { await browser.close(); server.stop(true); } console.log(ok ? '\n✅ @mentions suggest people and tag them' : '\n❌ failed'); 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/<name>/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 = `<!doctype html><meta charset="utf-8"><style>${await Bun.file('src/style.css').text()}</style><div id="app"></div><script type="module">${await bundle.outputs[0].text()}</script>`; +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/nip29-group-test.js b/tools/nip29-group-test.js new file mode 100644 index 0000000..ddc7258 --- /dev/null +++ b/tools/nip29-group-test.js @@ -0,0 +1,163 @@ +// NIP-29 relay groups in Messages: New group → Relay group → paste an +// address → Join. Reads the real "pyramid runners" group off +// pyramid.fiatjaf.com (relays: 'read' — nothing published leaves the page: +// the join request, the kind 10009 list and the test message are answered +// OK in place and checked here). +// Run: bun tools/nip29-group-test.js +import puppeteer, { seedWords, skipSeedCheck } from './puppeteer.js'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const ADDR = process.env.GROUP || "https://chachi.chat/pyramid.fiatjaf.com/Tnq7x2ZTgrPZWFrC"; +const GID = 'Tnq7x2ZTgrPZWFrC'; + +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 0, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); +const browser = await puppeteer.launch({ relays: 'read', executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errs = []; +page.on('console', (m) => { if (/nip29/.test(m.text())) console.log(' [page]', m.text()); }); +page.on('pageerror', (e) => errs.push(String(e))); +const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase() === x); if (e) { e.click(); return true; } return false; }, t); +const waitText = async (x, ms = 20000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; +const published = () => page.evaluate(() => window.__relayGuard.events); + +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto(server.url.href, { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); + await sleep(400); + await page.evaluate(() => [...document.querySelectorAll('button')].find((n) => /create a new wallet/i.test(n.textContent))?.click()); await sleep(600); + await seedWords(page); + const phrase = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' '); + await skipSeedCheck(page); + await waitText('receive', 20000); + await page.click('[aria-label="Messages"]'); + await waitText('new group', 10000); + await click('new group'); await sleep(300); + check('New group offers a relay group', await click('relay group')); + await sleep(200); + await page.type('.nip29-address', 'not an address'); + await click('join'); await sleep(500); + check('a bad address is refused', await waitText("isn't a group address", 3000)); + await page.evaluate(() => { const i = document.querySelector('.nip29-address'); i.value = ''; i.dispatchEvent(new Event('input', { bubbles: true })); }); + await page.type('.nip29-address', ADDR); + await click('join'); + check('the group opens, named by its relay', await waitText('pyramid runners', 20000)); + check('its messages arrive', await waitText('paff.club', 20000)); + const evs = await published(); + const join = evs.find((e) => e.kind === 9021); + check('a join request went to the group', !!join && join.tags.some((x) => x[0] === 'h' && x[1] === GID)); + // the 10009 write reads the newest list first, everywhere (a first write) + let list = null; + for (let i = 0; i < 80 && !list; i++) { list = (await published()).filter((e) => e.kind === 10009).pop(); if (!list) await sleep(250); } + check('the group is added to the kind 10009 list', !!list && list.tags.some((x) => x[0] === 'group' && x[1] === GID && /pyramid\.fiatjaf\.com/.test(x[2])), JSON.stringify(list?.tags)); + + // say something (answered OK in place, never sent) + await page.click('#msg-draft'); + await page.type('#msg-draft', 'hello from the nip29 test'); + await page.keyboard.press('Enter'); + await sleep(1500); + const msg = (await published()).find((e) => e.kind === 9 && e.content === 'hello from the nip29 test'); + check('a message is a kind 9 with the group h tag', !!msg && msg.tags.some((x) => x[0] === 'h' && x[1] === GID), JSON.stringify(msg?.tags)); + check('...and previous tags from the timeline', !!msg && msg.tags.some((x) => x[0] === 'previous' && /^[0-9a-f]{8}$/.test(x[1]))); + check('it shows in the group', await waitText('hello from the nip29 test', 3000)); + + // members: the relay's list + await page.evaluate(() => document.querySelector('.chat-head .clickable')?.click()); await sleep(800); + check('the member panel says it is a relay group', await waitText('not encrypted', 3000)); + const n = await page.evaluate(() => document.querySelectorAll('.chat-members .chat-thread-row').length); + check('members come from the relay', n > 10, n + ' members'); + + // back home: a row of its own; reload keeps it + await page.evaluate(() => document.querySelector('.chat-head button')?.click()); await sleep(600); + check('the group is listed in Messages', await page.evaluate(() => [...document.querySelectorAll('.chat-thread-row')].some((r) => r.textContent.includes('pyramid runners')))); + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitText('receive', 20000); + await page.click('[aria-label="Messages"]'); + let kept = false; + for (let i = 0; i < 40 && !kept; i++) { kept = await page.evaluate(() => [...document.querySelectorAll('.chat-thread-row')].some((r) => r.textContent.includes('pyramid runners'))); if (!kept) await sleep(250); } + check('...and still is after a reload', kept); + + // the same wallet on another device, already open: the laptop's list + // arrives on its live 10009 subscription and the group appears there + // ("Not seeing the pyramid runners chat I joined … on my laptop appear on + // my phone", Adam, 2026-11-12) + { + const ctx = await browser.createBrowserContext(); + const p2 = await ctx.newPage(); + p2.on('console', (m) => { if (process.env.DEBUG && /nip29|chat|10009/.test(m.text())) console.log(' [p2]', m.text()); }); + p2.on('pageerror', (e) => errs.push('p2: ' + e)); + await p2.evaluateOnNewDocument(() => { + window.__subs = []; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (d) { + try { const m = JSON.parse(d); if (m[0] === 'REQ') window.__subs.push({ ws: this, id: m[1], filters: m.slice(2) }); } catch {} + return send.call(this, d); + }; + }); + const t2 = async (x, ms = 20000) => { for (let i = 0; i < ms / 250; i++) { if ((await p2.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; + await p2.setViewport({ width: 390, height: 844 }); + await p2.goto(server.url.href, { waitUntil: 'domcontentloaded' }); + await p2.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await p2.reload({ waitUntil: 'domcontentloaded' }); + await t2('sign in to an existing account'); + await p2.evaluate(() => document.getElementById('onb-signin')?.click()); await sleep(500); + await p2.evaluate(() => document.getElementById('onb-restore')?.click()); await sleep(600); + await p2.type('textarea[placeholder*="seed words" i]', phrase); + await p2.evaluate(() => [...document.querySelectorAll('button')].find((n) => /open wallet/i.test(n.textContent))?.click()); + await t2('receive'); + await p2.click('[aria-label="Messages"]'); await sleep(500); + let subbed = false; + for (let i = 0; i < 60 && !subbed; i++) { subbed = await p2.evaluate(() => window.__subs.some((x) => x.ws.readyState === 1 && x.filters.some((f) => (f.kinds || []).includes(10009) && f.limit === 1))); if (!subbed) await sleep(250); } + check('another device follows the 10009 list live', subbed); + const before = await p2.evaluate(() => [...document.querySelectorAll('.chat-thread-row')].some((r) => r.textContent.includes('pyramid runners'))); + const fromLaptop = list; // the laptop's own signed list, from before its reload + await p2.evaluate((ev) => { + for (const x of window.__subs.filter((x) => x.ws.readyState === 1 && x.filters.some((f) => (f.kinds || []).includes(10009) && f.limit === 1))) + x.ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', x.id, ev]) })); + }, fromLaptop); + let shown = false; + for (let i = 0; i < 60 && !shown; i++) { shown = await p2.evaluate(() => [...document.querySelectorAll('.chat-thread-row')].some((r) => r.textContent.includes('pyramid runners'))); if (!shown) await sleep(250); } + check('...and the group joined on the laptop appears there', !before && shown); + // a group whose relay is gone says so on its row, not "0 members" + await p2.evaluate(() => [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase() === 'new group')?.click()); await sleep(300); + await p2.evaluate(() => [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase() === 'relay group')?.click()); await sleep(200); + await p2.type('.nip29-address', "gone.invalid'deadgroup"); + await p2.evaluate(() => [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase() === 'join')?.click()); await sleep(1500); + await p2.evaluate(() => document.querySelector('.chat-head button')?.click()); await sleep(500); + let dead = ''; + for (let i = 0; i < 60 && !/answering/.test(dead); i++) { dead = await p2.evaluate(() => [...document.querySelectorAll('.chat-thread-row')].find((r) => r.textContent.includes('deadgroup'))?.textContent || ''); if (!/answering/.test(dead)) await sleep(250); } + check("a group on a relay that's gone says so", /gone\.invalid isn't answering/.test(dead), dead.slice(0, 80)); + // leaving it from its own screen ("Tried to leave but got this": a + // ReferenceError on the screen of a group that had just gone) + await p2.evaluate(() => [...document.querySelectorAll('.chat-thread-row')].find((r) => r.textContent.includes('deadgroup'))?.click()); await sleep(800); + await p2.click('[aria-label="Leave group"]'); await sleep(200); + await p2.click('[aria-label="Leave group"]'); await sleep(2500); + const after = await p2.evaluate(() => document.body.innerText); + check('leaving a group from its screen goes back to Messages', !/something broke/i.test(after) && !/deadgroup/.test(after) && /new group/i.test(after), after.slice(0, 120)); + await ctx.close(); + } + + // leave: two taps, a 9022 to the relay, and off the list + await page.evaluate(() => [...document.querySelectorAll('.chat-thread-row')].find((r) => r.textContent.includes('pyramid runners'))?.click()); await sleep(800); + await page.click('[aria-label="Leave group"]'); await sleep(200); + await page.click('[aria-label="Leave group"]'); + let left = null, relist = null; + for (let i = 0; i < 80 && !(left && relist); i++) { + const evs = await published(); + left = evs.find((e) => e.kind === 9022); + relist = evs.filter((e) => e.kind === 10009).find((e) => !e.tags.some((x) => x[0] === 'group')); + if (!(left && relist)) await sleep(250); + } + check('leaving tells the relay (9022)', !!left && left.tags.some((x) => x[0] === 'h' && x[1] === GID)); + check('...and takes it off the 10009 list', !!relist); + check('...and out of Messages', !(await page.evaluate(() => [...document.querySelectorAll('.chat-thread-row')].some((r) => r.textContent.includes('pyramid runners'))))); + check('no page errors', !errs.length, errs.join(' | ')); +} catch (e) { console.error(e); ok = false; } finally { + await browser.close(); server.stop(); +} +console.log(ok ? '\nPASS' : '\nFAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/noffer-test.js b/tools/noffer-test.js index 152ef0b..5886f84 100644 --- a/tools/noffer-test.js +++ b/tools/noffer-test.js @@ -31,8 +31,9 @@ const published = []; const nwcTransport = { subscribe: (relays, filter, on) => { subHandlers.push({ filter, on }); return () => {}; }, publish: async (relays, evt) => { published.push(evt); return true; }, - query: async () => [], + query: async (relays, filter) => queryImpl(relays, filter), }; +let queryImpl = async () => []; const wallet = { watchOnly: false, loadFeatureState: (n, fb) => JSON.parse(store['fs:' + n] || 'null') || fb, @@ -95,5 +96,24 @@ await offerSub.on(reqEv); await new Promise((r) => setTimeout(r, 60)); check('replayed request ignored', published.filter((e) => e.kind === 21001).length === before); +console.log('\n[the receipt, from two devices]'); +// the zap is paid: this device publishes its receipt once +hooks.arkMovements = () => [{ type: 'ln-receive', status: 'complete', invoice: 'lnbc_mock_21', preimage: 'ee'.repeat(32) }]; +const receipts = () => published.filter((e) => e.kind === 9735); +queryImpl = async (relays, filter) => published.filter((e) => (filter.kinds || []).includes(e.kind) && (!filter.authors || filter.authors.includes(e.pubkey))); +await f.nwcPublishZapReceipts(); +check('the paid zap gets its receipt', receipts().length === 1 && receipts()[0].pubkey === offer.pubkey); +await f.nwcPublishZapReceipts(); +check('…once, however often the pass runs', receipts().length === 1); +// another device: the synced state still lists it pending (it synced before +// this device's pass), and the relays have the receipt already +const st3 = JSON.parse(store['fs:nwc']); +st3.zapPending = [{ zap: JSON.stringify(zapReq), invoice: 'lnbc_mock_21', ts: Date.now() }]; +st3.zapDone = []; +store['fs:nwc'] = JSON.stringify(st3); +await f.nwcPublishZapReceipts(); +check('a second device finds it on the relays and stays quiet', receipts().length === 1, receipts().length + ' receipts'); +check('…and drops it from the pending list', (JSON.parse(store['fs:nwc']).zapPending || []).length === 0); + console.log(fails ? `\n❌ ${fails} failure(s)` : '\n✅ offer service behaves'); process.exit(fails ? 1 : 0); diff --git a/tools/notif-app-zap-test.js b/tools/notif-app-zap-test.js new file mode 100644 index 0000000..3ee2030 --- /dev/null +++ b/tools/notif-app-zap-test.js @@ -0,0 +1,109 @@ +// Notifications: a zap on your Zapstore app listing (kind 32267) reads +// "zapped your app PAFF" and opens the app's Zapstore page. It opened the +// zapper's profile: Zapstore's receipt carries no a tag (only the zap request +// inside it does), so the row looked like a zap on nothing (Adam, 2026-11-07: +// "clicking this franzap zap notification keeps bringing me to his profile"). +// A row saved before reads the receipt once on tap and goes there too. +// Run: bun tools/notif-app-zap-test.js +import puppeteer, { seedWords, skipSeedCheck } from './puppeteer.js'; +import { cacheKeyFor } from '../src/wallet.js'; +import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure'; +import { privateKeyFromSeedWords } from 'nostr-tools/nip06'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const A = generateSecretKey(), B = generateSecretKey(); +const now = Math.floor(Date.now() / 1000); +const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64'); +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 5317, fetch: (req) => { + const path = new URL(req.url).pathname; + if (path.endsWith('.png')) return new Response(PNG, { headers: { 'content-type': 'image/png' } }); + if (path.startsWith('/punks') || path === '/verify-worker.js') return new Response(Bun.file('dist' + path)); + return new Response(html, { headers: { 'content-type': 'text/html' } }); +} }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errs = []; +page.on('pageerror', (e) => errs.push(String(e))); +const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); +const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; + +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto('http://localhost:5317/', { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400); + await click('create a new wallet'); await sleep(600); + await seedWords(page); + const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' '); + await skipSeedCheck(page); + await waitText('receive', 20000); + const base = cacheKeyFor(mn + '\n'); + const ME = getPublicKey(privateKeyFromSeedWords(mn)); + const APP = '32267:' + 'c'.repeat(64) + ':club.paff.app'; + const zap = (sk, sats, ts, content) => { + const req = finalizeEvent({ kind: 9734, created_at: ts, content, tags: [['p', ME], ['amount', String(sats * 1000)], ['a', APP]] }, sk); + // the receipt Zapstore's LNURL server publishes: p and P, no a tag + return finalizeEvent({ kind: 9735, created_at: ts, content: '', tags: [['p', ME], ['P', req.pubkey], ['amount', String(sats * 1000)], ['description', JSON.stringify(req)]] }, generateSecretKey()); + }; + const OLD = zap(A, 10000, now - 120, 'Love it'); // saved by the old code, without the app + const NEW = zap(B, 2100, now - 60, 'great app'); + const LISTING = finalizeEvent({ kind: 32267, created_at: now - 3600, content: '', tags: [['d', 'club.paff.app'], ['name', 'PAFF']] }, generateSecretKey()); + await page.evaluateOnNewDocument((evs, listing) => { + window.__opened = []; + window.open = (u) => { window.__opened.push(u); return null; }; + const Real = window.WebSocket; + window.WebSocket = function (...a) { + const ws = new Real(...a); + const send = ws.send.bind(ws); + ws.send = (data) => { + try { + const m = JSON.parse(data); + if (m[0] === 'REQ') { + const fs = m.slice(2); + const hit = [ + // the notifications sync only hands the NEW one; the old row is already held + ...evs.slice(1).filter(() => fs.some((f) => (f.kinds || []).includes(9735) && (f['#p'] || []).length)), + ...evs.filter((ev) => fs.some((f) => (f.ids || []).includes(ev.id))), + ...(fs.some((f) => (f.kinds || []).includes(32267)) ? [listing] : []), + ]; + setTimeout(() => { + for (const e of hit) ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', m[1], e]) })); + ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) })); + }, 0); + return; + } + if (m[0] === 'EVENT' || m[0] === 'NEG-OPEN') return; + } catch {} + return send(data); + }; + return ws; + }; + window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real); + }, [OLD, NEW], LISTING); + await page.evaluate(([k, me, old]) => { + const st = JSON.parse(localStorage.getItem(k + ':messages') || '{}'); + st.notifs = [{ id: old.id, what: 'zap', actor: JSON.parse(old.tags.find((t) => t[0] === 'description')[1]).pubkey, target: null, stream: null, hint: [], sats: 10000, text: 'Love it', ts: old.created_at }]; + st.notifsPk = me; st.notifsV = 2; + localStorage.setItem(k + ':messages', JSON.stringify(st)); + }, [base, ME, OLD]); + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitText('receive', 20000); + await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Notifications"]')?.click()); + console.log('\n[a zap on your app]'); + check('a new one reads "zapped your app PAFF"', await waitText('zapped your app paff 2.1k sats', 15000), + await page.evaluate(() => [...document.querySelectorAll('.alert-row')].map((r) => r.innerText.replace(/\s+/g, ' ')).join(' | '))); + await page.evaluate(() => [...document.querySelectorAll('.alert-row')].find((r) => /great app/.test(r.innerText))?.click()); + await sleep(300); + check('...and opens its Zapstore page', (await page.evaluate(() => window.__opened)).includes('https://zapstore.dev/apps/club.paff.app'), JSON.stringify(await page.evaluate(() => window.__opened))); + await page.evaluate(() => { window.__opened = []; [...document.querySelectorAll('.alert-row')].find((r) => /Love it/.test(r.innerText))?.click(); }); + for (let i = 0; i < 40 && !(await page.evaluate(() => window.__opened.length)); i++) await sleep(250); + check('a row saved before reads its receipt on tap and opens the app too', (await page.evaluate(() => window.__opened)).includes('https://zapstore.dev/apps/club.paff.app'), JSON.stringify(await page.evaluate(() => window.__opened))); + check('...and is labelled as an app zap from then on', await waitText('zapped your app paff 10k sats', 5000)); + check('still in Notifications, not a profile', await page.evaluate(() => !!document.querySelector('.alert-row'))); + check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); +} finally { await browser.close(); server.stop(true); } +console.log(ok ? '\n✅ zaps on your app open the app' : '\n❌ failed'); +process.exit(ok ? 0 : 1); diff --git a/tools/nwc-sw-test.js b/tools/nwc-sw-test.js index 7e85ee1..18528a2 100644 --- a/tools/nwc-sw-test.js +++ b/tools/nwc-sw-test.js @@ -58,7 +58,10 @@ function harness({ rec = baseRec(), recs = null, answered = false } = {}) { return { ok: true, json: async () => ({ ok: true, scheduled: true }) }; } if (url.includes('/claim')) { - return { ok: true, json: async () => ({ ok: true }) }; + // as the notifier does: a request already replied to can't be claimed + const was = typeof answered === 'function' ? answered() : answered; + if (JSON.parse(opts.body).release) return { ok: true, json: async () => ({ ok: true, released: true }) }; + return { ok: true, json: async () => (was ? { ok: false, answered: true } : { ok: true }) }; } if (url.includes('/answered')) { return { ok: true, json: async () => ({ answered: typeof answered === 'function' ? answered() : answered }) }; diff --git a/tools/onboard-backup-test.js b/tools/onboard-backup-test.js index 8fc1071..946f342 100644 --- a/tools/onboard-backup-test.js +++ b/tools/onboard-backup-test.js @@ -64,6 +64,10 @@ try { const page = await browser.newPage(); await page.setViewport({ width: 390, height: 844 }); await page.goto('http://localhost:5291/', { waitUntil: 'domcontentloaded' }); + // regtest: the classic phrase flow. Where a name can be claimed (mainnet, + // mutinynet) Create is the quick sign-up instead — signup-quick-test.js. + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(1500); // Two choices and nothing else (2026-11-06): a new wallet, or one you // already have — the sign-in methods wait behind the second. diff --git a/tools/own-boost-feed-test.js b/tools/own-boost-feed-test.js new file mode 100644 index 0000000..ab2a88f --- /dev/null +++ b/tools/own-boost-feed-test.js @@ -0,0 +1,113 @@ +// Your own boost shows in your feed. "I tried boosting this post but I don't +// see it in my feed" (Adam, 2026-11-22): the post was already in Following +// (he follows its author), and a note shows once, so his boost was folded +// away. "We dedupe other boosts right? so maybe make an exception for our +// own": my boost has its own row at the time I boosted, under "<me> +// reposted", and the post itself stays where it was. +// Run: bun tools/own-boost-feed-test.js +import puppeteer, { seedWords, skipSeedCheck } from './puppeteer.js'; +import { cacheKeyFor } from '../src/wallet.js'; +import { generateSecretKey, getPublicKey, finalizeEvent, verifyEvent } from 'nostr-tools/pure'; +import { privateKeyFromSeedWords } from 'nostr-tools/nip06'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const key = () => { const sk = generateSecretKey(); return { sk, pk: getPublicKey(sk) }; }; +const PNK = key(), FILLER = key(); +const now = Math.floor(Date.now() / 1000); +const note = (who, content, ago) => finalizeEvent({ kind: 1, created_at: now - ago, tags: [], content }, who.sk); +const PAFF = note(PNK, 'Running a PAFF server on my phone pledging storage', 72000); +const POSTS = [PAFF, ...Array.from({ length: 12 }, (_, i) => note(FILLER, `filler post number ${i + 1} with words enough to tell apart ${'abcdefghijkl'[i].repeat(6)}`, 600 + i * 900))]; +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 5347, fetch: (req) => { const p = new URL(req.url).pathname; if (p === '/verify-worker.js' || p.startsWith('/punks')) return new Response(Bun.file('dist' + p)); return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); +const browser = await puppeteer.launch({ relays: 'read', executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +await page.evaluateOnNewDocument((fx) => { + const Real = window.WebSocket; + const fits = (ev, f) => (!f.kinds || f.kinds.includes(ev.kind)) && (!f.authors || f.authors.includes(ev.pubkey)) && (!f.ids || f.ids.includes(ev.id)); + const pubd = () => { try { return JSON.parse(localStorage.getItem('__pub') || '[]'); } catch { return []; } }; + window.WebSocket = function (...a) { + const ws = new Real(...a); const send = ws.send.bind(ws); + const say = (m) => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(m) })); + ws.send = (d) => { + try { + const m = JSON.parse(d); + if (m[0] === 'REQ') { const fs = m.slice(2); setTimeout(() => { if (window.__live) for (const ev of fx.concat(pubd()).filter((e) => fs.some((f) => fits(e, f)))) say(['EVENT', m[1], ev]); say(['EOSE', m[1]]); }, 0); return; } + if (m[0] === 'EVENT') { if (m[1].kind === 6) { const all = pubd(); if (!all.some((e) => e.id === m[1].id)) localStorage.setItem('__pub', JSON.stringify([...all, m[1]])); } setTimeout(() => say(['OK', m[1].id, true, '']), 0); return; } + } catch {} + return send(d); + }; + return ws; + }; + window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real); +}, POSTS); +const errs = []; +page.on('pageerror', (e) => errs.push(String(e))); +const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); +const text = () => page.evaluate(() => document.body.innerText); +const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await text()).toLowerCase().includes(x.toLowerCase())) return true; await sleep(250); } return false; }; +const rows = () => page.evaluate(() => [...document.querySelectorAll('.notes-feed > .row[data-key]')].map((r) => ({ paff: r.textContent.includes('Running a PAFF server'), reposted: /reposted/.test(r.querySelector('.note-reposted')?.textContent || '') }))); +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto('http://localhost:5347/', { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400); + await click('create a new wallet'); await sleep(600); + await seedWords(page); + const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' '); + await skipSeedCheck(page); + await waitText('receive', 20000); + const base = cacheKeyFor(mn + '\n'); + await page.evaluate(([k, p, f]) => { + localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', p], ['p', f]], c: '', at: Math.floor(Date.now() / 1000) })); + localStorage.setItem(k + ':profiles', JSON.stringify({ [p]: { name: 'pnk', t: Date.now() }, [f]: { name: 'Filler', t: Date.now() } })); + localStorage.setItem('btc-wallet-feed:' + k, 'following'); + }, [base, PNK.pk, FILLER.pk]); + await page.evaluateOnNewDocument(() => { window.__live = true; }); + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitText('receive', 20000); + await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]')?.click()); + check('the followed post is in the feed', await waitText('Running a PAFF server', 30000)); + await sleep(1500); + let r = await rows(); + check('...once, below newer posts, not as a repost', r.filter((x) => x.paff).length === 1 && r.findIndex((x) => x.paff) > 3 && !r.find((x) => x.paff).reposted, JSON.stringify(r.map((x) => +x.paff))); + const tapped = await page.evaluate(() => { const row = [...document.querySelectorAll('.notes-feed > .row[data-key]')].find((n) => n.textContent.includes('Running a PAFF server')); const b = row && [...row.querySelectorAll('.note-acts button')].find((x) => /boost/i.test(x.getAttribute('aria-label') || x.title || '')); if (b) { b.click(); return true; } return false; }); + check('Boost tapped', tapped); + let top = null; + for (let i = 0; i < 40; i++) { r = await rows(); top = r[0]; if (top && top.paff && top.reposted) break; await sleep(250); } + check('the boost is at the top of my feed, under "… reposted"', !!top && top.paff && top.reposted, JSON.stringify(r.slice(0, 3))); + check('the row I tapped is still where it was', r.filter((x) => x.paff).length === 2); + const first = await page.evaluate(() => JSON.parse(localStorage.getItem('__pub') || '[]')); + check('the boost was published, with the signed post inside', first.length === 1 && verifyEvent(JSON.parse(first[0].content))); + await sleep(1500); // the feed cache is written + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitText('receive', 20000); + await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]')?.click()); + await waitText('Running a PAFF server', 30000); + await sleep(4000); + r = await rows(); + const both = (r) => !!r[0] && r[0].paff && r[0].reposted && r.filter((x) => x.paff).length === 2 && r.filter((x) => x.paff && x.reposted).length === 1 && r[r.length - 1].paff && !r[r.length - 1].reposted; + check('after a reload: my boost first (the newest), the post itself still in its place', both(r), JSON.stringify(r.map((x) => [+x.paff, +x.reposted]))); + // a post painted from the saved feed has no signature in memory: its boost must still carry one + const before = await page.evaluate(() => JSON.parse(localStorage.getItem('__pub') || '[]').length); + const cachedTap = await page.evaluate(() => { const row = [...document.querySelectorAll('.notes-feed > .row[data-key]')].find((n) => n.textContent.includes('filler post number 3 ')); const b = row && [...row.querySelectorAll('.note-acts button')].find((x) => /boost/i.test(x.getAttribute('aria-label') || x.title || '')); if (b) { b.click(); return true; } return false; }); + let second = null; + for (let i = 0; i < 40 && !second; i++) { await sleep(250); second = await page.evaluate((n) => JSON.parse(localStorage.getItem('__pub') || '[]')[n] || null, before); } + const inner = second && JSON.parse(second.content); + check('a boost of a post from the saved feed carries the signed post', cachedTap && !!inner && !!inner.sig && verifyEvent(inner), JSON.stringify(inner && Object.keys(inner))); + // a second device: nothing cached, the post and the boost both come from relays + await page.evaluate(() => { for (const k of Object.keys(localStorage)) if (/feed-cache|feedcache|:feed:|notes/i.test(k)) localStorage.removeItem(k); }); + await page.evaluate(async () => { if (indexedDB.databases) for (const d of await indexedDB.databases()) if (/feed|note/i.test(d.name || '')) indexedDB.deleteDatabase(d.name); }); + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitText('receive', 20000); + await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]')?.click()); + await waitText('Running a PAFF server', 30000); + await sleep(4000); + r = await rows(); + const p = r.filter((x) => x.paff); + check('with no cache: my boosts lead in time order, the post itself still in its place', r[0].reposted && r[1].reposted && r[1].paff && p.length === 2 && !p[1].reposted && r.filter((x) => x.reposted).length === 2, JSON.stringify(r.map((x) => [+x.paff, +x.reposted]))); + check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); +} finally { await browser.close(); server.stop(true); } +console.log(ok ? '\n✅ my own boost shows in my feed' : '\n❌ failed'); +process.exit(ok ? 0 : 1); 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/<name>/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('[email protected]'), 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 [email protected]')); + 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)) === '[email protected] 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); +} diff --git a/tools/pos-test.js b/tools/pos-test.js index 55349cb..2b6a0b7 100644 --- a/tools/pos-test.js +++ b/tools/pos-test.js @@ -30,7 +30,7 @@ const ctx = { }; const feature = posFeature(ctx); window.__feature = feature; function render() { document.querySelector('#app').replaceChildren(feature.screenView() || h('div', { id: 'closed' }, 'closed')); } -window.test = { open: () => { feature.openPos(); }, init: () => { feature.init(); render(); }, +window.test = { open: () => { feature.openPos(); }, request: () => { feature.openAmountRequest(); }, init: () => { feature.init(); render(); }, cards: () => { document.querySelector('#app').replaceChildren(...feature.posSettingsCards()); }, settle: (ok) => { const w = watch; watch = null; w.cb({ step: ok ? 'done' : 'failed' }); }, get watch() { return watch && watch.id; }, get cancelled() { return cancelled; }, get sales() { return (state.pos || {}).sales || []; }, ui }; render(); `; @@ -128,6 +128,24 @@ try { check("the old device-wide flag is dropped on start (it can't say whose it was)", await page.evaluate(() => (test.ui.pos = null, true)) && (await boot('owner')) && await page.evaluate(() => localStorage.getItem('btc-wallet-pos-mode') === null)); check('another wallet on the same device does not start in point of sale', !(await boot('someone-else'))); check('the owner still does, after anyone else has been in', await boot('owner')); + + console.log('\n[Receive → Amount]'); + await page.evaluate(() => { localStorage.removeItem('btc-wallet-pos-mode:owner'); test.ui.pos = null; test.request(); }); await pause(50); + let rq = await text(); + check('opens as Request an amount, without the till around it', /Request an amount/.test(rq) && !/ask for a tip|Tips today|Sales today/i.test(rq) && !(await page.$('.pos-sale')), rq.slice(0, 200)); + const before = await page.evaluate(() => test.sales.length); + await type('.pos-amount', '2100'); + await page.click('#pos-charge'); await pause(100); + rq = await text(); + check('straight to the invoice, no tip prompt', /Scan to pay/i.test(rq) && /2,100/.test(rq) && !!(await page.$('.pos-qr')), rq.slice(0, 200)); + const req = await page.evaluate(() => test.sales[test.sales.length - 1]); + check('the request is for the amount, no tip, and marked', req.billSat === 2100 && req.tipSat === 0 && req.request === true, JSON.stringify(req)); + await page.evaluate(() => test.settle(true)); await pause(100); + check('paid, with Done back to Receive', /Done/.test(await text()) && !/New sale/.test(await text())); + await click('Done'); await pause(50); + check('Done closes it', !!(await page.$('#closed'))); + await page.evaluate(() => { test.ui.pos = null; test.open(); }); await pause(50); + check("the till's sales list leaves requests out", !(await text()).includes('2,100'), String(before)); check('no browser errors', errors.length === 0); } finally { await browser.close(); server.stop(true); } console.log('\n✅ point of sale'); diff --git a/tools/post-search-test.js b/tools/post-search-test.js new file mode 100644 index 0000000..81e5b62 --- /dev/null +++ b/tools/post-search-test.js @@ -0,0 +1,83 @@ +// Full-text search: words typed into Search and submitted with Enter (no +// suggestion picked) open a feed of the notes AND replies that say them, +// asked of NIP-50 relays ({ kinds: [1], search }). The search relays are +// answered in the page; nothing leaves the machine. +// Run: bun tools/post-search-test.js +import puppeteer, { seedWords, skipSeedCheck } from './puppeteer.js'; +import { generateSecretKey, finalizeEvent } from 'nostr-tools/pure'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const SK = generateSecretKey(); +const now = Math.floor(Date.now() / 1000); +const post = finalizeEvent({ kind: 1, created_at: now - 300, tags: [], content: 'talked to fiatjaf about relays today' }, SK); +const parent = 'a'.repeat(64); +// one newsletter, posted by bot keys with a word or emoji changed each time +const NL = 'In this week\'s issue: The Quiet Coup: Fiatjaf Wipes Authorship From 57 NIPs. In a 12-hour window, the documentation layer was rewritten without consent. https://nostrmag.com/article/w45'; +const copies = ['📰 ' + NL, '🗞️ BREAKING ' + NL, NL + ' 👤 NM team'].map((content, i) => finalizeEvent({ kind: 1, created_at: now - 100 - i, tags: [], content }, generateSecretKey())); +const reply = finalizeEvent({ kind: 1, created_at: now - 200, tags: [['e', parent, '', 'reply']], content: 'fiatjaf would say just use a relay' }, SK); + +const html = await buildHtml({ minify: true, pwa: false }); +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: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +await page.evaluateOnNewDocument((hits) => { + window.__searches = []; + const Real = window.WebSocket; + window.WebSocket = function (...a) { + const ws = new Real(...a); + const send = ws.send.bind(ws); + ws.send = (data) => { + try { + const m = JSON.parse(data); + if (m[0] === 'REQ' && m[2] && m[2].search) { + window.__searches.push({ url: ws.url, f: m[2] }); + const r = send(data); + setTimeout(() => { for (const ev of hits) ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', m[1], ev]) })); }, 2); + return r; + } + } catch {} + return send(data); + }; + return ws; + }; + window.WebSocket.prototype = Real.prototype; + Object.assign(window.WebSocket, Real); +}, [post, reply, ...copies]); +const errs = []; +page.on('pageerror', (e) => errs.push(String(e))); +const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); +const waitText = async (x, ms = 20000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; + +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto(server.url.href, { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); + await sleep(400); + await click('create a new wallet'); await sleep(600); + await seedWords(page); + await skipSeedCheck(page); + await waitText('receive', 20000); + await page.click('[aria-label="Search"]'); + await page.waitForSelector('.user-search-input'); + await page.type('.user-search-input', 'fiatjaf'); + await sleep(300); + check('the search page offers the words themselves', await waitText('posts and replies that say this', 3000)); + await page.keyboard.press('Enter'); + check('Enter opens a feed of posts that say it', await waitText('talked to fiatjaf about relays', 10000)); + check('...replies too', await waitText('fiatjaf would say just use a relay', 3000)); + await waitText('quiet coup', 10000); await sleep(1500); + const nl = await page.evaluate(() => (document.body.innerText.match(/Quiet Coup/g) || []).length); + check('a newsletter posted by three bot keys shows once', nl === 1, nl + ' copies'); + const s = await page.evaluate(() => window.__searches.filter((x) => x.f.search === 'fiatjaf' && !(x.f.kinds || []).includes(0))); + check('asked NIP-50 relays for kind 1 with the words', s.length > 0 && s.every((x) => JSON.stringify(x.f.kinds) === '[1]'), JSON.stringify(s.map((x) => x.url))); + check('the feed is named for the search', await page.evaluate(() => [...document.querySelectorAll('.feed-chip')].some((c) => c.classList.contains('on') && c.textContent.includes('fiatjaf'))), + JSON.stringify(await page.evaluate(() => [...document.querySelectorAll('.feed-chip')].map((c) => c.textContent.trim())))); + check('no page errors', !errs.length, errs.join(' | ')); +} catch (e) { console.error(e); ok = false; } finally { + await browser.close(); server.stop(); +} +console.log(ok ? '\nPASS' : '\nFAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/profile-depth-test.js b/tools/profile-depth-test.js new file mode 100644 index 0000000..5aea719 --- /dev/null +++ b/tools/profile-depth-test.js @@ -0,0 +1,45 @@ +// A profile's older posts, page after page, with no months skipped. Relays +// hold different parts of an author's history: paging "older than the oldest +// post on the page" jumped from late September to April on Ben Arc's profile +// because one relay held six stray copies reaching back that far, and the +// posts around his Napstr launch (2026-08-21) are on none of the relays we +// ask — only in Primal's cache. Reads real relays (relays: 'read'; nothing +// is published). +// Run: bun tools/profile-depth-test.js +import puppeteer from './puppeteer.js'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const NPUB = process.env.NPUB || 'npub1c878wu04lfqcl5avfy3p5x83ndpvedaxv0dg7pxthakq3jqdyzcs2n8avm'; +const WANT = process.env.WANT || 'For all the seeders out there'; + +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 0, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); +const browser = await puppeteer.launch({ relays: 'read', executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errs = []; +page.on('pageerror', (e) => errs.push(String(e.stack || e).slice(0, 600))); +try { + await page.setViewport({ width: 390, height: 844 }); + await page.goto(server.url.href + NPUB, { waitUntil: 'domcontentloaded' }); + await page.waitForSelector('.notes-feed:not(.note-ghosts) > [data-key]', { timeout: 20000 }); + const seen = new Map(); // key -> text + let found = false, still = 0, last = 0; + const t0 = Date.now(); + for (let i = 0; i < 400 && !found && still < 40; i++) { + const rows = await page.evaluate(() => [...document.querySelectorAll('.notes-feed > [data-key]')].map((r) => [r.dataset.key, r.textContent.slice(0, 300)])); + for (const [k, t] of rows) seen.set(k, t); + found = [...seen.values()].some((t) => t.includes(WANT)); + still = seen.size === last ? still + 1 : 0; + last = seen.size; + await page.evaluate(() => window.scrollBy(0, 1400)); + await sleep(350); + } + console.log(` ${seen.size} posts read in ${((Date.now() - t0) / 1000).toFixed(1)} s`); + check('scrolling back reaches the Napstr launch post', found, WANT); + check('...past more than a first page', seen.size > 40, seen.size + ' posts'); + check('no page errors', !errs.length, errs.join(' | ')); +} catch (e) { console.error(e); ok = false; } finally { await browser.close(); server.stop(); } +console.log(ok ? '\nPASS' : '\nFAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/profile-stream-test.js b/tools/profile-stream-test.js new file mode 100644 index 0000000..2b426bb --- /dev/null +++ b/tools/profile-stream-test.js @@ -0,0 +1,75 @@ +// A profile visited for the first time, from search: its posts used to land +// all at once after several seconds of blank (the slowest relay, then every +// post's media). Now the page shows post-shaped placeholders while it waits, +// the first posts paint as the quick relays answer, and the top search +// results are fetched before they're tapped. Reads real relays +// (relays: 'read'; nothing is published). +// Run: bun tools/profile-stream-test.js (Q="ben arc" to search someone else) +import puppeteer from './puppeteer.js'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const Q = process.env.Q || 'fiatjaf'; + +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 0, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); +const browser = await puppeteer.launch({ relays: 'read', executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errs = []; +page.on('pageerror', (e) => errs.push(String(e.stack || e).slice(0, 600))); +try { + await page.setViewport({ width: 390, height: 844 }); + if (process.env.DARK) await page.emulateMediaFeatures([{ name: 'prefers-color-scheme', value: 'dark' }]); + await page.goto(server.url.href + 'feed', { waitUntil: 'domcontentloaded' }); + await sleep(1500); + await page.evaluate(() => [...document.querySelectorAll('button')].find((b) => b.getAttribute('aria-label') === 'Search')?.click()); + await page.waitForSelector('.user-search-main', { timeout: 10000 }); + await page.type('.user-search-main', Q, { delay: 60 }); + // the result rows: people (not the "posts that say this" or #topic rows) + const rows = () => page.evaluate(() => [...document.querySelectorAll('.list .item:not(.search-scoped-row)')].filter((r) => !/^[\u{1F50D}#]/u.test(r.textContent.trim())).map((r) => r.textContent.trim().slice(0, 40))); + let found = []; + for (let i = 0; i < 60 && !found.length; i++) { found = await rows(); if (!found.length) await sleep(250); } + if (!found.length) console.log(await page.evaluate(() => document.querySelector('.user-search-main')?.closest('.col')?.parentElement?.innerHTML.slice(0, 1500))); + check('search finds people', found.length > 0, found.slice(0, 2).join(' | ')); + const wait = Number(process.env.WAIT || 0); // ms between results and the tap (prefetch's head start) + if (wait) await sleep(wait); + const t0 = Date.now(); + await page.evaluate(() => [...document.querySelectorAll('.list .item:not(.search-scoped-row)')].filter((r) => !/^[\u{1F50D}#]/u.test(r.textContent.trim()))[0].click()); + let ghostAt = 0, firstAt = 0, rowsAt3 = 0; + for (let i = 0; i < 200; i++) { + const s = await page.evaluate(() => ({ + ghost: !!document.querySelector('.note-ghosts'), + rows: document.querySelectorAll('.notes-feed:not(.note-ghosts) > [data-key]').length, + })); + const t = Date.now() - t0; + if (s.ghost && !ghostAt) { ghostAt = t; if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT }); } + if (s.rows && !firstAt) firstAt = t; + if (t >= 3000 && !rowsAt3) rowsAt3 = s.rows || -1; + if (firstAt && t >= 3000) break; + await sleep(50); + } + console.log(` placeholder ${ghostAt ? ghostAt + ' ms' : 'not seen'}, first post ${firstAt || '—'} ms, rows at 3 s ${rowsAt3}`); + check('posts arrive', firstAt > 0); + check('...while waiting, the page says posts are loading', !!ghostAt || firstAt < 300, ghostAt ? 'placeholder shown' : 'posts were already in hand'); + // a second search typed into the desktop header field while that profile + // is open: the results come forward ("the search box stops working", + // Adam 2026-11-14 — they updated a page hidden under the profile) + await page.setViewport({ width: 1300, height: 900 }); + await sleep(500); + const field = await page.$('input.header-search, .header-search-field'); + check('the desktop header has a search field', !!field); + if (field) { + await page.evaluate(() => { const f = document.querySelector('input.header-search, .header-search-field'); f.focus(); f.value = ''; }); + await field.type('jack', { delay: 60 }); + let again = []; + for (let i = 0; i < 80 && !(again.length && again[0] !== found[0]); i++) { again = await rows(); if (!(again.length && again[0] !== found[0])) await sleep(250); } + const onProfile = await page.evaluate(() => !!document.querySelector('.prof-tabs')); + check('typing a new search from a profile shows its results', again.length > 0 && !onProfile, again.slice(0, 2).join(' | ')); + await page.goBack(); await sleep(800); + check('...and Back returns to the profile', await page.evaluate(() => !!document.querySelector('.prof-tabs'))); + } + check('no page errors', !errs.length, errs.join(' | ')); +} catch (e) { console.error(e); ok = false; } finally { await browser.close(); server.stop(); } +console.log(ok ? '\nPASS' : '\nFAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/public-chat-join-test.js b/tools/public-chat-join-test.js new file mode 100644 index 0000000..3f0eee4 --- /dev/null +++ b/tools/public-chat-join-test.js @@ -0,0 +1,75 @@ +// The public chat page (/chat) on a device that already has a wallet: its +// button opens the coinos community's room itself, not the wallet, and the +// page doesn't tell a signed-in reader to sign in. And /chat's loading shell +// is not a profile named "chat". (Andy, 2026-11-10: "I can see the feed etc +// fine, so I am logged in".) Relays are the stand-ins: nothing is sent. +// +// Run: bun tools/public-chat-join-test.js +import puppeteer from './puppeteer.js'; +import { generateMnemonic } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; +import { buildHtml } from '../build.js'; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; + +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 5247, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +await page.setViewport({ width: 390, height: 844 }); +const click = (sel, t) => page.evaluate((s, x) => { const e = [...document.querySelectorAll(s)].find((n) => n.textContent.trim().toLowerCase().includes(x.toLowerCase())); if (e) { e.click(); return true; } return false; }, sel, t); +const waitFor = async (fn, ms = 15000, ...a) => { for (let i = 0; i < ms / 200; i++) { try { if (await page.evaluate(fn, ...a)) return true; } catch {} await sleep(200); } return false; }; +// did the static profile shell ever show while the page loaded? +await page.evaluateOnNewDocument(() => { + window.__shellShown = false; + const look = () => { const s = document.getElementById('boot-shell'); if (s && s.style.display !== 'none') window.__shellShown = true; }; + new MutationObserver(look).observe(document, { childList: true, subtree: true, attributes: true }); + document.addEventListener('DOMContentLoaded', look); +}); +const head = () => page.evaluate(() => { + const c = document.querySelector('.chat-head'); + return c ? { text: c.innerText, button: c.querySelector('button')?.textContent.trim() } : null; +}); + +try { + console.log('\n[a visitor]'); + await page.goto('http://localhost:5247/chat', { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitFor(() => !!document.querySelector('.chat-head')); + let hd = await head(); + check('the public chat mounts', !!hd); + check('a visitor is asked to sign in', hd?.button === 'Sign in to chat' && /sign in to join/i.test(hd.text), hd?.button); + check("/chat's loading shell is not a profile", !(await page.evaluate(() => window.__shellShown))); + await page.goto('http://localhost:5247/someone', { waitUntil: 'domcontentloaded' }); + check('a name still gets its profile shell', await page.evaluate(() => window.__shellShown)); + + console.log('\n[with a wallet on the device]'); + await page.goto('http://localhost:5247/', { waitUntil: 'domcontentloaded' }); + await sleep(400); + await click('button', 'Create a new wallet'); + await sleep(300); + await click('button', 'Have an existing seed'); + await sleep(300); + await page.waitForSelector('textarea'); + await page.type('textarea', generateMnemonic(wordlist)); + await click('button', 'Open wallet'); + check('wallet opens', await waitFor(() => /receive/i.test(document.body.innerText))); + await page.goto('http://localhost:5247/chat', { waitUntil: 'domcontentloaded' }); + await waitFor(() => !!document.querySelector('.chat-head')); + hd = await head(); + check('no "sign in" for someone signed in', !!hd && !/sign in/i.test(hd.text), hd?.text.replace(/\n/g, ' | ')); + check('the button offers the chat', hd?.button === 'Join the chat', hd?.button); + await Promise.all([page.waitForNavigation({ waitUntil: 'domcontentloaded' }), click('.chat-head button', 'Join the chat')]); + const inRoom = await waitFor(() => !!document.querySelector('.chat-compose textarea, .chat-compose input, .chat-compose [contenteditable]'), 20000); + check('it lands in the community room, composer ready', inRoom, await page.evaluate(() => document.body.innerText.slice(0, 120).replace(/\n/g, ' | '))); + check('the room is the coinos community', await page.evaluate(() => /coinos/i.test(document.querySelector('.chat-head, .chat-title')?.innerText || ''))); + check('the marker is gone from the address', await page.evaluate(() => location.pathname === '/' && !location.search)); +} finally { + await browser.close(); + server.stop(true); +} +console.log(ok ? '\nPASS' : '\nFAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/search-follows-test.js b/tools/search-follows-test.js new file mode 100644 index 0000000..c0d8673 --- /dev/null +++ b/tools/search-follows-test.js @@ -0,0 +1,53 @@ +// People search finds the people you follow first (Adam, 2026-11-17: Derek +// Ross moved to a new npub after his key leaked; searching "derek ross" came +// up with an empty impostor, because Primal doesn't index the new key yet +// and ranks by its own trust score). A follow whose name or NIP-05 matches +// outranks the search indexes; while follows' names are still loading, the +// answer isn't cached. Run: bun tools/search-follows-test.js +globalThis.localStorage = { getItem: () => null, setItem() {}, removeItem() {} }; +const NEW = '6e479b7a5671f58a7a5d04ecedb00c1345b8918a8f8e270dc807ddb2818dba28'; +const OLD = '3f770d65d3a764a9c5cb503ae123e62ec7598ad035d836e2a810f3877a745b24'; +const FAKE = '1419ab45e0bdf22b51aeb0ddf2435b568e530b8ecf6f6f82172b181302f076ee'; +// Primal's answer for "derekross": the impostor first +class FakeWS { + constructor() { this.readyState = 0; setTimeout(() => { this.readyState = 1; this._open?.(); }, 5); } + addEventListener(t, f) { if (t === 'open') this._open = f; } + send(raw) { + const [, sid, { cache: [, args] }] = JSON.parse(raw); + const evs = args.query === 'derekross' ? [{ kind: 0, pubkey: FAKE, content: JSON.stringify({ name: 'Derek Ross' }) }] : []; + setTimeout(() => { for (const e of evs) this.onmessage({ data: JSON.stringify(['EVENT', sid, e]) }); this.onmessage({ data: JSON.stringify(['EOSE', sid]) }); }, 5); + } + close() {} +} +globalThis.WebSocket = FakeWS; +globalThis.fetch = async () => ({ json: async () => ({ results: [] }) }); +const { searchRecipients, setLocalPeople } = await import('../src/recipient-search.js'); + +let fails = 0; +const check = (name, ok, extra = '') => { console.log(`${ok ? ' ✓' : ' ✗'} ${name}${extra ? ' — ' + extra : ''}`); if (!ok) fails++; }; + +let partial = true; +setLocalPeople(() => { + const out = [ + { pk: NEW, name: 'Derek Ross', nip05: '[email protected]' }, + { pk: OLD, name: 'nobody' }, + { pk: 'a'.repeat(64), name: 'Someone Else' }, + ]; + out.partial = partial; + return out; +}); +let rows = await searchRecipients('derek ross'); +check('a follow named Derek Ross comes first', rows[0]?.pk === NEW, rows.map((r) => r.pk.slice(0, 8)).join(',')); +check('the index result still listed after it', rows.some((r) => r.pk === FAKE)); +check('the renamed old key is not a match', !rows.some((r) => r.pk === OLD)); +partial = false; +setLocalPeople(() => [{ pk: NEW, name: 'Derek Ross (new)', nip05: '[email protected]' }]); +rows = await searchRecipients('derek ross'); +check('a partial answer was not cached (asks again)', rows[0]?.name === 'Derek Ross (new)', rows[0]?.name); +rows = await searchRecipients('derekross.me'); +check('NIP-05 matches too', rows[0]?.pk === NEW); +setLocalPeople(() => []); +rows = await searchRecipients('derek ross'); +check('a complete answer is cached', rows[0]?.pk === NEW); +console.log(fails ? 'FAIL' : 'PASS'); +process.exit(fails ? 1 : 0); diff --git a/tools/search-scope-test.js b/tools/search-scope-test.js new file mode 100644 index 0000000..122fcd0 --- /dev/null +++ b/tools/search-scope-test.js @@ -0,0 +1,96 @@ +// Searching inside one person's posts (Adam, 2026-11-14: "i found him by +// searching franca but then i was wanting some way to search his feed for +// something … i was wanting to search 'franca wildwood'"). On a profile the +// header field carries the person as a chip and Enter searches their posts; +// words that begin with the name of someone whose profile you opened +// ("fiatjaf relay") are offered, and Enter takes them there. Reads real +// relays (relays: 'read'; nothing is published). +// Run: bun tools/search-scope-test.js (WHO=npub… NAME=fiatjaf WORD=relay) +import puppeteer from './puppeteer.js'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const WHO = process.env.WHO || 'npub180cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsyjh6w6'; // fiatjaf +const NAME = process.env.NAME || 'fiatjaf'; +const WORD = process.env.WORD || 'relay'; + +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 0, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) }); +const browser = await puppeteer.launch({ relays: 'read', executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errs = []; +page.on('pageerror', (e) => errs.push(String(e.stack || e).slice(0, 600))); +const until = async (fn, ms = 15000, arg) => { for (let i = 0; i < ms / 200; i++) { const v = await page.evaluate(fn, arg); if (v) return v; await sleep(200); } return null; }; +const feedState = () => page.evaluate((word) => { + const posts = [...document.querySelectorAll('.notes-feed:not(.note-ghosts) > [data-key]')].filter((p) => !/^(hr:|win-)/.test(p.getAttribute('data-key'))); + return { path: location.pathname + location.search, title: document.querySelector('.feed-page h2, .feed-title, .feed-name')?.textContent || '', + n: posts.length, without: posts.filter((p) => !p.textContent.toLowerCase().includes(word)).length }; +}, WORD); +try { + await page.setViewport({ width: 1300, height: 900 }); + await page.goto(server.url.href + WHO, { waitUntil: 'domcontentloaded' }); + check('the profile opens', !!(await until(() => document.querySelector('.prof-tabs')))); + const chip = await until((n) => { const c = document.querySelector('.header-search-scoped .search-scope-chip')?.textContent || ''; return c.toLowerCase().includes(n) && c; }, 15000, NAME.toLowerCase()); + check('the header field carries the person as a chip', !!chip && chip.toLowerCase().includes(NAME.toLowerCase()), chip || ''); + if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT.replace(/(\.png)?$/, '-chip.png'), clip: { x: 0, y: 0, width: 1300, height: 120 } }); + + await page.click('.header-search-field'); + await page.type('.header-search-field', WORD, { delay: 50 }); + const row = await until(() => document.querySelector('.search-scoped-row')?.textContent); + check('the results offer the words in their posts, first', !!row && row.includes(WORD) && /posts/.test(row), row || ''); + const people = await until(() => document.querySelectorAll('.list .item:not(.search-scoped-row)').length > 2); + check('…and still find people', !!people); + await page.keyboard.press('Enter'); + const f1 = await until(async () => document.querySelectorAll('.notes-feed:not(.note-ghosts) > [data-key]').length >= 1 && location.search.includes('p=npub'), 25000); + const s1 = await feedState(); + check('Enter searches only their posts (URL carries the person)', !!f1 && s1.path.includes('q=' + WORD) && s1.path.includes('p=npub'), JSON.stringify(s1)); + check('…every post says the word', s1.n > 0 && s1.without === 0, `${s1.n} posts, ${s1.without} without "${WORD}"`); + const authors = await page.evaluate(() => [...new Set([...document.querySelectorAll('.notes-feed:not(.note-ghosts) > [data-key] .note-author, .notes-feed:not(.note-ghosts) > [data-key] .chat-name')].map((n) => n.textContent.trim()))].slice(0, 5)); + console.log(' authors seen:', authors.join(', ')); + if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT.replace(/(\.png)?$/, '-feed.png') }); + + // the guess: "<name> <word>" from scratch, the profile having been opened + await page.goto(server.url.href + 'feed', { waitUntil: 'domcontentloaded' }); + await sleep(1500); + await page.evaluate((pk) => { /* nothing: a reload forgets the session's profiles */ }, WHO); + check('no chip away from a profile', !(await page.$('.search-scope-chip'))); + // open the profile in this session, then go back and type the combined query + await page.goto(server.url.href + WHO, { waitUntil: 'domcontentloaded' }); + await until(() => document.querySelector('.prof-tabs')); + await page.click('.search-scope-x'); + check('× takes the chip out', !!(await until(() => !document.querySelector('.search-scope-chip')))); + await page.click('input.header-search'); + await page.type('input.header-search', `${NAME} ${WORD}`, { delay: 50 }); + const guess = await until(() => document.querySelector('.search-scoped-row')?.textContent, 15000); + check('"name word" is offered as their posts', !!guess && guess.includes(`“${WORD}”`) && guess.toLowerCase().includes(NAME.toLowerCase()), guess || ''); + check('…as the strong guess (Enter hint)', !!(await page.$('.search-scoped-row .search-enter-hint'))); + await page.keyboard.press('Enter'); + const f2 = await until(() => location.search.includes('p=npub') && location.search.includes('q=' + encodeURIComponent('relay').slice(0, 3)), 15000); + check('Enter takes the guess', !!f2, (await feedState()).path); + + // a query that is someone's whole name is not split + await page.click('input.header-search, .header-search-field'); + await page.evaluate(() => { const f = document.querySelector('input.header-search, .header-search-field'); f.value = ''; }); + await page.type('input.header-search, .header-search-field', 'nobody wordthatmatchesnoone', { delay: 30 }); + await sleep(3000); + check('no guess when no name starts the words', !(await page.$('.search-scoped-row'))); + // a phone: the magnifier on a profile opens search with the chip in it + await page.setViewport({ width: 390, height: 844 }); + await page.goto(server.url.href + WHO, { waitUntil: 'domcontentloaded' }); + await until(() => document.querySelector('.prof-tabs')); + await page.evaluate(() => [...document.querySelectorAll('button')].find((b) => b.getAttribute('aria-label') === 'Search' && b.offsetParent)?.click()); + const mchip = await until(() => document.querySelector('.user-search-main .search-scope-chip')?.textContent); + check('phone: search from a profile carries the chip', !!mchip, mchip || ''); + await page.type('.user-search-input', WORD, { delay: 40 }); + check('phone: …and offers their posts', !!(await until(() => document.querySelector('.search-scoped-row')))); + await page.click('.user-search-input'); + await page.keyboard.press('End'); + for (let i = 0; i < WORD.length; i++) await page.keyboard.press('Backspace'); + await page.keyboard.press('Backspace'); + check('phone: Backspace on the empty field takes the chip out', !!(await until(() => !document.querySelector('.search-scope-chip')))); + if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT.replace(/(\.png)?$/, '-phone.png') }); + check('no page errors', !errs.length, errs.join(' | ')); +} catch (e) { console.error(e); ok = false; } finally { await browser.close(); server.stop(); } +console.log(ok ? '\nPASS' : '\nFAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/send-enter-keys-test.js b/tools/send-enter-keys-test.js index aac95f8..54f2c02 100644 --- a/tools/send-enter-keys-test.js +++ b/tools/send-enter-keys-test.js @@ -45,8 +45,13 @@ const armPrimary = () => page.evaluate(() => { try { await page.setViewport({ width: 390, height: 844 }); await page.goto(server.url.origin, { waitUntil: 'domcontentloaded' }); + // the two-card carousel is the "separately" view now (one balance is the default) + await page.evaluate(() => localStorage.setItem('btc-wallet-separate-balances', '1')); + await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400); - await click('create a new wallet'); await sleep(500); await click('to import'); await sleep(400); + // a seed wallet comes in through the seed-phrase door (Create is a sign-up on mainnet) + await page.waitForSelector('#onb-signin'); await page.click('#onb-signin'); await sleep(400); + await page.click('#onb-restore'); await sleep(400); await page.waitForSelector('textarea'); await page.type('textarea', generateMnemonic(wordlist)); await click('open wallet'); for (let i = 0; i < 80 && !(await page.evaluate(() => [...document.querySelectorAll('button')].some((b) => b.textContent.trim() === 'Send'))); i++) { await page.evaluate(() => [...document.querySelectorAll('button')].find((b) => /^(not now|skip|continue|later)$/i.test(b.textContent.trim()))?.click()); diff --git a/tools/send-lnaddr-advance-test.js b/tools/send-lnaddr-advance-test.js index fd6c1a1..14640ca 100644 --- a/tools/send-lnaddr-advance-test.js +++ b/tools/send-lnaddr-advance-test.js @@ -43,7 +43,8 @@ try { await page.setViewport({ width: 390, height: 844 }); await page.goto(server.url.origin, { waitUntil: 'domcontentloaded' }); await sleep(400); - await click('create a new wallet'); await sleep(500); await click('to import'); await sleep(400); + await page.waitForSelector('#onb-signin'); await page.click('#onb-signin'); await sleep(400); + await page.click('#onb-restore'); await sleep(400); await page.waitForSelector('textarea'); await page.type('textarea', generateMnemonic(wordlist)); await click('open wallet'); // mainnet onboarding: skip the username step (and anything after it) for (let i = 0; i < 80 && !(await page.evaluate(() => [...document.querySelectorAll('button')].some((b) => b.textContent.trim() === 'Send'))); i++) { diff --git a/tools/signup-quick-test.js b/tools/signup-quick-test.js new file mode 100644 index 0000000..5005d6a --- /dev/null +++ b/tools/signup-quick-test.js @@ -0,0 +1,236 @@ +// Signing up is a name and a look, nothing else (Adam, 2026-11-15): "i'd like +// to move away from requiring people to backup and verify a seed phrase to +// sign up. we should just have them claim a name and pick their avatar/cover +// and they should be in. we should also not create a savings account by +// default but let them add it later … adding additional auth methods like +// passkey, nostr, or google should be possible once they've created their +// account." +// +// Mainnet, with the Ark server's info read for real and the names registrar +// mocked (nothing is claimed): Create an account → no twelve words, no check +// → Claim your name (no "Not now") → Choose your look → in, on ONE balance +// (no carousel; on-chain is part of the account, a Bitcoin address a tap away +// on Receive); Settings → Wallet shows "Ways back in" (passkey via a CDP +// virtual authenticator → listed) and one balance row, with "Show Spending +// and Savings separately" (→ the two faces; a reload keeps them). +// Run: bun tools/signup-quick-test.js (NO_BUILD=1 to reuse dist/) +import puppeteer from './puppeteer.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +if (!process.env.NO_BUILD && Bun.spawnSync(['bun', 'build.js']).exitCode !== 0) throw new Error('build failed'); +const server = Bun.serve({ port: 0, fetch: async (req) => { + const path = new URL(req.url).pathname; + const f = Bun.file('dist' + path); + return path.includes('.') && await f.exists() ? new Response(f) : new Response(Bun.file('dist/index.html')); +} }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +const page = await browser.newPage(); +const errs = []; +const registered = []; +const cors = { 'access-control-allow-origin': '*', 'access-control-allow-headers': 'content-type,authorization', 'access-control-allow-methods': 'GET,POST,DELETE,OPTIONS' }; +await page.setRequestInterception(true); +page.on('request', (r) => { + const u = new URL(r.url()); + if (u.origin === server.url.origin || u.hostname === 'ark.coinos.io') return r.continue(); + if (u.hostname !== 'names.coinos.io') return r.abort(); + if (r.method() === 'OPTIONS') return r.respond({ status: 200, headers: cors, body: '{}' }); + const reply = (j, status = 200) => r.respond({ status, headers: { ...cors, 'content-type': 'application/json' }, body: JSON.stringify(j) }); + if (u.pathname === '/register' && r.method() === 'POST') { const j = JSON.parse(r.postData() || '{}'); registered.push(j.name); return reply({ ok: true, name: j.name }); } + if (u.pathname.startsWith('/name/')) return reply({ taken: false }); + if (u.pathname.startsWith('/pubkey/')) return reply({}); + return reply({}); +}); +page.on('pageerror', (e) => errs.push(String(e))); +const click = (x) => page.evaluate((s) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(s)); if (e) e.click(); return !!e; }, x); +const text = () => page.evaluate(() => document.body.innerText); +const waitText = async (x, ms = 20000) => { for (let i = 0; i < ms / 250; i++) { if ((await text()).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; +const openWalletPage = async () => { + await page.evaluate(() => [...document.querySelectorAll('button')].find((e) => e.getAttribute('aria-label') === 'Settings').click()); await sleep(500); + await page.evaluate(() => [...document.querySelectorAll('.settings-tile')].find((e) => /^Wallet/.test(e.textContent.trim())).click()); await sleep(600); +}; +try { + await page.setViewport({ width: 390, height: 844 }); + const cdp = await page.createCDPSession(); + await cdp.send('WebAuthn.enable'); + await cdp.send('WebAuthn.addVirtualAuthenticator', { options: { + protocol: 'ctap2', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true, hasPrf: true, automaticPresenceSimulation: true } }); + await page.goto(server.url.href, { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'mainnet')); + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.waitForSelector('#onb-create', { timeout: 15000 }); + check('the front door says Create an account', (await page.$eval('#onb-create', (e) => e.textContent.trim())) === 'Create an account'); + await page.click('#onb-create'); + check('no seed screens: straight to Claim your name', await waitText('claim your name', 20000)); + const t1 = await text(); + check('no twelve words or check on the way', !(await page.$('.words')) && !/which word/i.test(t1)); + check('no "Not now" on a sign-up\'s name step', !/not now/i.test(t1)); + await page.waitForSelector('.onb input[type=text]', { timeout: 20000 }); + await page.type('.onb input[type=text]', 'quicktester'); + await click('claim'); + check('the name goes to the registrar', await (async () => { for (let i = 0; i < 80 && !registered.length; i++) await sleep(250); return registered.includes('quicktester'); })(), registered.join()); + check('then the look: avatar and cover', await (async () => { for (let i = 0; i < 80; i++) { if (await page.$('.onb-cover')) return true; await sleep(250); } return false; })()); + await click('continue'); await sleep(800); + if (await waitText("you're all set", 8000)) await click('enter'); + await page.waitForSelector('.balance-face', { timeout: 20000 }); + await sleep(1500); + const shape = async () => page.evaluate(() => ({ + faces: document.querySelectorAll('.balance-face').length, + carousel: !!document.querySelector('.bal-carousel'), + label: document.querySelector('.balance-face .small.faint')?.textContent.trim(), + body: document.body.innerText, + })); + let s = await shape(); + check('in, on one balance (no carousel, no name on it)', s.faces === 1 && !s.carousel && !s.label && !!(await page.$('.balance-one')), JSON.stringify({ faces: s.faces, carousel: s.carousel, label: s.label })); + // asked once, and only with money in the account (2026-11-15): not on an empty one + check('no way-back-in prompt on an empty account', !/add a way back into your account/i.test(s.body) && !(await page.$('.ways-back-prompt'))); + // money arrives in Spending (the ark feature, found on the heap, made to + // report a balance; then a repaint) + const giveBalance = async () => { + const protoH = await page.evaluateHandle(() => Object.prototype); + const all = await page.queryObjects(protoH); + const found = await page.evaluate((objs) => { + const f = objs.find((o) => { try { return o && o.id === 'ark' && typeof o.spendingSat === 'function'; } catch { return false; } }); + if (!f) return false; + f.spendingSat = () => 5000; + window.dispatchEvent(new Event('resize')); + document.querySelector('.tabs button')?.click(); document.querySelector('.tabs button')?.click(); + return true; + }, all); + await all.dispose(); await protoH.dispose(); + await sleep(800); + return found; + }; + check('(test: found the ark feature)', await giveBalance()); + check('with a balance, it asks once for a way back in', !!(await page.$('.ways-back-prompt')), (await text()).slice(0, 300).replace(/\n/g, ' | ')); + await page.evaluate(() => [...document.querySelectorAll('.ways-back-prompt button')].find((b) => /not now/i.test(b.textContent)).click()); await sleep(400); + check('Not now puts it away', !(await page.$('.ways-back-prompt'))); + await page.reload({ waitUntil: 'domcontentloaded' }); await page.waitForSelector('.balance-face', { timeout: 20000 }); await sleep(1500); + await giveBalance(); + check('...and never again, not after a reload', !(await page.$('.ways-back-prompt'))); + // the breakdown (Ark / On-chain / Gifts) folds away under the total; a + // gift line stands in for it here (the ark feature made to report one) + { + const protoH = await page.evaluateHandle(() => Object.prototype); + const all = await page.queryObjects(protoH); + await page.evaluate((objs) => { + const f = objs.find((o) => { try { return o && o.id === 'ark' && typeof o.balanceLines === 'function'; } catch { return false; } }); + f.balanceLines = () => [{ label: 'Gifts', sat: 700, side: 'savings', part: true }]; + document.querySelector('.tabs button')?.click(); document.querySelector('.tabs button')?.click(); + }, all); + await all.dispose(); await protoH.dispose(); await sleep(600); + const face = () => page.evaluate(() => ({ t: document.querySelector('.balance-one')?.innerText || '', btn: document.querySelector('.balance-one .breakdown-toggle')?.textContent || '' })); + let f = await face(); + check('breakdown folded by default, with a way to open it', !/GIFTS/i.test(f.t.replace(f.btn, '')) && /breakdown/i.test(f.btn), JSON.stringify(f)); + await page.click('.balance-one .breakdown-toggle'); await sleep(400); + f = await face(); + check('opened, it shows the Gifts line', /Gifts/i.test(f.t.replace(f.btn, '')) && /hide/i.test(f.btn), JSON.stringify(f)); + if (process.env.SHOT3) await page.screenshot({ path: process.env.SHOT3 }); + check('remembered on this device', await page.evaluate(() => localStorage.getItem('btc-wallet-balance-breakdown') === '1')); + await page.evaluate(() => localStorage.removeItem('btc-wallet-balance-breakdown')); + } + for (let i = 0; i < 60 && !(await page.$('#recv-amount')); i++) await sleep(250); + check('Receive has an Amount button', !!(await page.$('#recv-amount'))); + check('no History heading on an empty wallet', !/\bHISTORY\b/.test(await page.evaluate(() => document.body.innerText))); + if (process.env.SHOT3) await page.screenshot({ path: process.env.SHOT3 }); + await page.click('#recv-amount'); await sleep(500); + check('Amount opens the amount pad', !!(await page.$('.pos-amount')) && /request an amount/i.test(await text())); + if (process.env.SHOT4) await page.screenshot({ path: process.env.SHOT4 }); + await click('back'); await sleep(500); + check('Back returns to Receive', !(await page.$('.pos-amount')) && !!(await page.$('#recv-amount'))); + // one account takes on-chain payments too: its address under the payment one + check('Receive offers a Bitcoin address', !!(await page.$('#recv-onchain'))); + await page.click('#recv-onchain'); await sleep(400); + const oc = await page.evaluate(() => document.querySelector('.addr-box')?.textContent.trim() || ''); + check('...an on-chain address', /^bc1q/.test(oc), oc); + await page.click('#recv-payaddr'); await sleep(400); + check('...and back to the payment address', !!(await page.$('#recv-amount')) && !(await page.$('#recv-payaddr'))); + const acct = await page.evaluate(() => JSON.parse(sessionStorage.getItem('btc-wallet-accounts') || '{}')); + const a0 = (acct.accounts || [])[0] || {}; + check('the account: one balance (no kind), phrase unseen, saved to the device', !a0.kind && !a0.savingsLater && !!a0.spendingSetup && a0.seedSeen === false && a0.persisted, JSON.stringify({ kind: a0.kind, later: a0.savingsLater, seen: a0.seedSeen, persisted: a0.persisted })); + + await openWalletPage(); + check('Settings → Wallet opens with Ways back in', !!(await page.$('.ways-back')) && /ways back in/i.test(await text())); + const views = await page.$$eval('.balance-settings-row[data-view]', (l) => l.map((e) => e.dataset.view)); + check('the ways back in read as auth buttons', (await page.$$eval('.ways-back-add', (l) => l.map((e) => e.textContent.trim()))).join('|') === 'Passkey auth|Google auth|Nostr auth|Pen and paper', (await page.$$eval('.ways-back-add', (l) => l.map((e) => e.textContent.trim()))).join('|')); + check('one balance row, nothing to add', views.join() === 'all' && !(await page.$('#add-savings')), views.join()); + if (process.env.SHOT2) { await page.evaluate(() => document.documentElement.setAttribute('data-theme', 'dark')); await page.evaluate(() => document.querySelector('.balance-settings-row').closest('.card').scrollIntoView()); await sleep(300); await page.screenshot({ path: process.env.SHOT2 }); await page.evaluate(() => document.documentElement.removeAttribute('data-theme')); } + if (process.env.SHOT) { await page.evaluate(() => document.querySelector('.ways-back').scrollIntoView()); await page.screenshot({ path: process.env.SHOT }); } + // a passkey: the relays are stubbed, so the publish fails offline — the + // error says so and nothing is listed + await page.evaluate(() => document.querySelector('.ways-back-add[data-way="passkey"]')?.click()); + await sleep(4000); + const pk = await page.evaluate(() => ({ rows: [...document.querySelectorAll('.ways-back-row')].map((e) => e.dataset.way), err: document.querySelector('.ways-back .notice.err')?.textContent || '' })); + check('adding a passkey lists it', pk.rows.includes('passkey') && !pk.err, JSON.stringify(pk)); + const backups = await page.evaluate(() => (window.__relayGuard.events || []).filter((e) => e.kind === 30078 && e.tags.some((t) => t[0] === 'd' && t[1] === 'coinos:wallet:v1'))); + // the list and the reminder, as the app sees them (record a method directly) + check('the phrase card waits behind Pen and paper', !(await page.$('.recovery-card'))); + await page.evaluate(() => document.querySelector('.ways-back-add[data-way="phrase"]')?.click()); + await sleep(500); + check('Pen and paper opens the recovery phrase card', !!(await page.$('.recovery-card .words'))); + + await page.evaluate(() => document.getElementById('separate-balances')?.click()); await sleep(800); + const views2 = await page.$$eval('.balance-settings-row[data-view]', (l) => l.map((e) => e.dataset.view)); + check('Show separately lists Spending and Savings', views2.join() === 'spending,savings', views2.join()); + await page.goBack(); await page.goBack(); await sleep(800); + s = await shape(); + check('...and the wallet has both faces', s.carousel && s.faces === 2, JSON.stringify({ faces: s.faces, carousel: s.carousel })); + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.waitForSelector('.balance-face', { timeout: 20000 }); await sleep(1500); + s = await shape(); + check('a reload keeps them apart', s.carousel && s.faces === 2); + await openWalletPage(); + await page.evaluate(() => document.getElementById('separate-balances')?.click()); await sleep(800); + await page.goBack(); await page.goBack(); await sleep(800); + s = await shape(); + check('unticked, one balance again', !s.carousel && s.faces === 1 && !!(await page.$('.balance-one'))); + + // A new device: everything here wiped, the relays holding only what the + // passkey published. Sign in → Passkey opens THIS account, as itself. + const before = await page.evaluate(() => { + const st = JSON.parse(sessionStorage.getItem('btc-wallet-accounts') || '{}'); + const a = (st.accounts || [])[0] || {}; + return { mnemonic: a.mnemonic, nostrPk: a.nostrPk }; + }); + before.backups = backups; + check('the passkey published one encrypted seed copy', before.backups.length >= 1 && !before.backups[0].content.includes(before.mnemonic.split(' ')[0] + ' '), String(before.backups.length)); + const backup = before.backups[before.backups.length - 1]; + await page.evaluateOnNewDocument((ev) => { + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (d) { + try { + const m = JSON.parse(d); + if (m[0] === 'REQ' && m.slice(2).some((f) => (f.kinds || []).includes(30078) && (f.authors || []).includes(ev.pubkey))) { + const ws = this; + setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', m[1], ev]) })), 1); + } + } catch {} + return send.call(this, d); + }; + }, backup); + await page.evaluate(async () => { + localStorage.clear(); sessionStorage.clear(); + for (const d of (await indexedDB.databases?.() || [])) if (d.name) indexedDB.deleteDatabase(d.name); + localStorage.setItem('btc-wallet-network', 'mainnet'); + }); + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.waitForSelector('#onb-signin', { timeout: 15000 }); + await page.click('#onb-signin'); await sleep(500); + await click('passkey'); + for (let i = 0; i < 120 && !(await page.$('.balance-face')); i++) await sleep(250); + if (!(await page.$('.balance-face'))) console.log((await text()).slice(0, 800), errs); + const after = await page.evaluate(() => { + const st = JSON.parse(sessionStorage.getItem('btc-wallet-accounts') || '{}'); + const a = (st.accounts || [])[0] || {}; + const login = Object.keys(localStorage).concat([]).filter((k) => /:nostrlogin$/.test(k)).map((k) => localStorage.getItem(k)); + return { mnemonic: a.mnemonic, nostrPk: a.nostrPk, kind: a.kind, login, onb: localStorage.getItem('btc-wallet-onb-step') }; + }); + check('the passkey opened the same account', after.mnemonic === before.mnemonic); + check('as itself: same identity, the passkey key not adopted', after.nostrPk === before.nostrPk && !after.login.some((v) => v && v.includes(backup.pubkey)), JSON.stringify({ was: before.nostrPk?.slice(0, 8), now: after.nostrPk?.slice(0, 8) })); + check('no wizard on the way back in', !after.onb && !(await page.$('.onb'))); + check('no page errors', errs.length === 0, errs.join(' | ')); +} finally { + await browser.close(); server.stop(true); +} +console.log(ok ? 'PASS' : 'FAIL'); +process.exit(ok ? 0 : 1); diff --git a/tools/sw-push-quota.test.js b/tools/sw-push-quota.test.js index 544c72e..798b913 100644 --- a/tools/sw-push-quota.test.js +++ b/tools/sw-push-quota.test.js @@ -82,8 +82,33 @@ test('elsewhere: quiet stays quiet', async () => { let asked = 0; respond = async () => { asked++; return true; }; expect(await push(nwc)).toEqual([]); - expect(asked).toBe(0); // the open (if hidden) window answers on Android + expect(asked).toBe(0); // on a computer the open (if hidden) window answers windows = []; respond = async () => false; expect(await push(nwc)).toEqual(['Spend request']); }); + +// An Android phone freezes an app behind another one, minutes in: its relay +// sockets are dead and the worker's nudge sits unread until it is opened, so +// a zap sent from another app spun until then (wake to payment: 15 s at the +// median on Android, 2026-11-10). On a phone only a window on screen is +// handed the request; behind another app, the worker answers (and nudges the +// window anyway — the request's lock decides if it is still awake). +test('an Android phone: the app behind another one does not swallow the request', async () => { + endpoint = 'https://fcm.googleapis.com/fcm/send/abc'; + self.navigator = { userAgent: 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Mobile Safari/537.36' }; + try { + let asked = 0, nudged = 0; + respond = async () => { asked++; return true; }; + windows = [{ visibilityState: 'hidden', postMessage: () => { nudged++; } }]; + expect(await push(nwc)).toEqual([]); + expect(asked).toBe(1); + expect(nudged).toBe(1); + // on screen, it answers itself with everything it knows + asked = 0; nudged = 0; + windows = [{ visibilityState: 'visible', postMessage: () => { nudged++; } }]; + expect(await push(nwc)).toEqual([]); + expect(asked).toBe(0); + expect(nudged).toBe(1); + } finally { delete self.navigator; } +}); diff --git a/tools/unified-balance-test.js b/tools/unified-balance-test.js new file mode 100644 index 0000000..c349368 --- /dev/null +++ b/tools/unified-balance-test.js @@ -0,0 +1,127 @@ +// One balance (Adam, 2026-11-15: "combine the Ark and savings Bitcoin +// accounts into a single account … a combined history … the balance would be +// unified"). The Ark feature's side of it, without a browser: +// - the combined timeline tells a move between the two halves once: a board +// (its on-chain Sent + its Boarded) and an offboard to our own address +// (its Moved to Savings + the on-chain Received) are one row each, worth +// what the move cost; a board still confirming is one pending row; an +// offboard to someone else stays a payment +// - the separate Spending timeline is untouched +// - an on-chain address is paid from on-chain coins when there are any, and +// leaves Ark (offboard) only when there aren't +// Run: bun tools/unified-balance-test.js +import { buildFeatures } from '../src/features/index.js'; +import { getArkConfig } from '../src/api.js'; + +let fails = 0; +const check = (name, ok, detail = '') => { + console.log(` ${ok ? '✓' : '✗'} ${name}${detail ? ' — ' + String(detail).slice(0, 240) : ''}`); + if (!ok) fails++; +}; + +globalThis.fetch = async () => { throw new Error('offline (test)'); }; +globalThis.window = undefined; +globalThis.localStorage = { + _d: {}, getItem(k) { return this._d[k] ?? null; }, setItem(k, v) { this._d[k] = String(v); }, + removeItem(k) { delete this._d[k]; }, key(i) { return Object.keys(this._d)[i] ?? null; }, + get length() { return Object.keys(this._d).length; }, +}; +const cfg = getArkConfig(); +localStorage.setItem('btc-wallet-arkinfo:' + cfg.ark, JSON.stringify({ info: { minBoardAmountSat: 1000, boardFees: {} }, tip: 1, at: Date.now() })); + +const T = Date.now() - 3600_000; +const A = 'a'.repeat(64), B = 'b'.repeat(64), C = 'c'.repeat(64), D = 'd'.repeat(64), E = 'e'.repeat(64); +const arkState = { + _rev: 1, + vtxos: [{ id: 'v1', amountSat: 20000, state: 'spendable' }], + movements: [ + { id: 'm-board', type: 'board', amountSat: 9000, status: 'complete', txid: A, ts: T }, + { id: 'm-off', type: 'offboard', amountSat: 5000, feeSat: 300, status: 'complete', txid: B, to: 'bc1qown', ts: T + 1000 }, + { id: 'm-off-ext', type: 'offboard', amountSat: 7000, feeSat: 300, status: 'complete', txid: D, to: 'bc1qsomeoneelse', ts: T + 2000 }, + { id: 'm-recv', type: 'receive', amountSat: 1234, status: 'complete', vtxoId: 'v1', ts: T + 3000 }, + ], + actions: [ + { id: `board-${T + 4000}`, type: 'board', step: 'funded', amountSat: 3000, feeSat: 0, fundingTxid: C }, + ], +}; +// the on-chain wallet's view: board fundings out, the own offboard in +const txs = [ + { txid: A, net: -9200, confirmed: true, blockTime: T / 1000 }, + { txid: B, net: 5000, confirmed: true, blockTime: (T + 1000) / 1000 }, + { txid: C, net: -3150, confirmed: false }, + { txid: E, net: 40000, confirmed: true, blockTime: (T + 5000) / 1000 }, +]; + +const store = {}; +const wallet = { + watchOnly: false, offline: false, spendable: 0, feeRates: { halfHourFee: 1 }, + utxos: [], txs, history: txs, receive: [], change: [], + account: () => ({}), + isOnchainAddress: (a) => /^bc1q/.test(a), + loadFeatureState: (n, fb) => JSON.parse(store[n] || 'null') || fb, + saveFeatureState: (n, st) => { store[n] = JSON.stringify(st); }, + _cacheKey: () => 'test', saveCache: () => {}, + nostrPubkey: () => 'ab'.repeat(32), + registerCacheExtension: () => {}, registerRealtimeHook: () => {}, registerLoadHook: () => {}, + registerScanHook: () => {}, registerCacheSavedHook: () => {}, registerCoinLock: () => {}, + loadArkState: () => arkState, peekArkState: () => arkState, saveArkState: () => {}, + _arkNs: () => 'ns', _arkKey: () => 'k', _arkHoldKey: () => 'h', _arkVtxoOwner: () => null, adoptArkState: () => null, + freshReceive: () => ({ address: 'bc1qtest' }), freshChange: () => ({ address: 'bc1qchange' }), + balance: () => ({ spendableSat: 0 }), emit: () => {}, on: () => {}, +}; +let unified = true; +const ui = { account: 'spending', send: { recipients: [{ address: '' }] } }; +let features = []; +const ctx = { + h: (tag, attrs, ...kids) => ({ tag, attrs: attrs || {}, kids: kids.flat().filter((k) => k != null && k !== false) }), + ui, render: () => {}, wallet, + hook: (name, ...args) => { for (const f of features) if (f[name]) { const v = f[name](...args); if (v) return v; } return null; }, + getAccount: () => ui.account, setAccount: (a) => { ui.account = a; }, unifiedBalance: () => unified, + goHome: () => {}, openMnemonic: async () => {}, + fmtAmount: (n) => Number(n).toLocaleString('en-US'), unitLabel: () => 'sats', unitTag: () => 'sats', getUnit: () => 'sats', + parseAmount: (v) => parseInt(v, 10) || 0, amountField: (n) => String(n), + copyBtn: () => null, pasteBtn: () => null, toast: () => {}, blankSend: () => ({ recipients: [{ address: '' }] }), + openExternal: () => {}, +}; +features = buildFeatures(ctx); +const ark = features.find((f) => f.id === 'ark'); +const text = (n) => typeof n === 'string' || typeof n === 'number' ? String(n) : n && n.kids ? n.kids.map(text).join(' ') : ''; + +console.log('[one timeline]'); +{ + const rows = ark.historyEntries(txs, 'all'); + const replaced = rows.map((e) => e.replacesTxid).filter(Boolean).sort(); + check('the board, the own offboard and the confirming board stand in for their on-chain rows', replaced.join() === [A, B, C].sort().join(), replaced.map((x) => x[0]).join()); + check('the offboard to someone else is not a move', !replaced.includes(D)); + const byTx = Object.fromEntries(rows.filter((e) => e.replacesTxid).map((e) => [e.replacesTxid, text(e.render())])); + check('the board reads Made instant, worth its cost (9,200 out, 9,000 in)', /Made instant/.test(byTx[A]) && /\b200\b/.test(byTx[A]) && /9,000/.test(byTx[A]), byTx[A]); + check('the own offboard reads Moved on-chain, worth its fee', /Moved on-chain/.test(byTx[B]) && /\b300\b/.test(byTx[B]), byTx[B]); + check('the confirming board is one pending row', /Making instant/.test(byTx[C]) && /Pending/.test(byTx[C]) && /\b150\b/.test(byTx[C]), byTx[C]); + const others = rows.filter((e) => !e.replacesTxid).map((e) => text(e.render())).join(' | '); + check('the other Ark rows are as they were', /Received/.test(others) && !/Boarded/.test(others), others); + check('the offboard to someone else reads Sent, not Moved to Savings', /Sent/.test(others) && !/Savings/.test(others), others); +} + +console.log('[the Spending timeline, shown apart]'); +{ + const rows = ark.historyEntries([], 'spending'); + check('no row stands in for an on-chain one', rows.every((e) => !e.replacesTxid), rows.length); + check('the board is still its own Boarded row', rows.some((e) => /Boarded/.test(text(e.render())))); + check('Savings gets no Ark rows', ark.historyEntries(txs, 'savings').length === 0); +} + +console.log('[paying an on-chain address]'); +{ + ui.arkOffboardSend = null; wallet.spendable = 50000; + ark.matchSendText('bc1qrecipient'); + check('with on-chain coins it is an ordinary on-chain send', !ui.arkOffboardSend); + ui.arkOffboardSend = null; wallet.spendable = 0; + ark.matchSendText('bc1qrecipient'); + check('without them it leaves Ark', !!ui.arkOffboardSend && ui.arkOffboardSend.address === 'bc1qrecipient'); + ui.arkOffboardSend = null; wallet.spendable = 50000; unified = false; + ark.matchSendText('bc1qrecipient'); + check('shown apart, Spending still pays it from Ark (as before)', !!ui.arkOffboardSend); +} + +console.log(fails ? `FAIL (${fails})` : 'PASS'); +process.exit(fails ? 1 : 0); diff --git a/tools/youtube-tap-test.js b/tools/youtube-tap-test.js index e08058b..bf2832f 100644 --- a/tools/youtube-tap-test.js +++ b/tools/youtube-tap-test.js @@ -3,6 +3,8 @@ // sound, full screen. The player's own taps never reach the page, so a layer // over the picture takes them; YouTube's control bar along the bottom is // left to YouTube, and full screen the layer steps aside. +// Full screen, YouTube's own full-screen button leaves it. Under a mouse +// there is no layer: the player takes its own clicks (pause, full screen). // Run: bun tools/youtube-tap-test.js import puppeteer, { seedWords, skipSeedCheck } from './puppeteer.js'; import { cacheKeyFor } from '../src/wallet.js'; @@ -26,7 +28,7 @@ const server = Bun.serve({ port: 0, fetch: (req) => { return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); // YouTube, stood in for: the player page notes every command it is sent -const PLAYER = '<!doctype html><html><body style="margin:0;background:#222;height:100vh"><script>window.__cmds=[];addEventListener("message",(e)=>{try{const m=JSON.parse(e.data);if(m.event==="command")window.__cmds.push(m.func)}catch{}});</script></body></html>'; +const PLAYER = '<!doctype html><html><body style="margin:0;background:#222;height:100vh"><script>window.__cmds=[];addEventListener("message",(e)=>{try{const m=JSON.parse(e.data);if(m.event==="command")window.__cmds.push(m.func)}catch{}});window.__clicks=0;addEventListener("click",()=>{window.__clicks++;if(!window.__fsButton)return;if(document.fullscreenElement)document.exitFullscreen();else document.documentElement.requestFullscreen().catch(()=>{})});</script></body></html>'; const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox', '--autoplay-policy=no-user-gesture-required'] }); async function run(saveData) { @@ -55,7 +57,8 @@ async function run(saveData) { const st = () => page.evaluate(() => { const b = document.querySelector('.yt-embed'); const f = b && b.querySelector('iframe'); const sh = b && b.querySelector('.yt-shield'); return { fs: !!b && document.fullscreenElement === b, iframe: !!f, muted: !!f && /mute=1/.test(f.src), shield: !!sh && getComputedStyle(sh).display !== 'none', thread: !!document.querySelector('.thread-card') }; }); const cmds = async () => { const f = page.frames().find((x) => x.url().startsWith('https://www.youtube-nocookie.com/')); return f ? f.evaluate(() => window.__cmds.slice()) : null; }; try { - await page.setViewport({ width: 390, height: 844 }); + // a phone: a finger, no hover (a mouse is run apart, below) + await page.setViewport({ width: 390, height: 844, hasTouch: true, isMobile: true }); await page.goto(server.url.href, { waitUntil: 'domcontentloaded' }); await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400); @@ -85,13 +88,13 @@ async function run(saveData) { await sleep(500); // YouTube's control bar along the bottom is YouTube's let b = await box(); - await page.mouse.click(b.x + b.w * 0.3, b.y + b.h - 20); await sleep(500); + await page.touchscreen.tap(b.x + b.w * 0.3, b.y + b.h - 20); await sleep(500); check('a tap on YouTube\'s control bar stays YouTube\'s', !(await st()).fs && !(await st()).thread, JSON.stringify(await st())); } else { check('with Data Saver, the still and a play button', !s.iframe && await page.evaluate(() => !!document.querySelector('.yt-embed .yt-play')), JSON.stringify(s)); } const b = await box(); - await page.mouse.click(b.x + b.w * 0.3, b.y + b.h * 0.35); + await page.touchscreen.tap(b.x + b.w * 0.3, b.y + b.h * 0.35); check('one tap on the picture: full screen', await waitFor(() => document.fullscreenElement === document.querySelector('.yt-embed'), null, 3000), JSON.stringify(await st())); s = await st(); check('…the player there', s.iframe); @@ -102,9 +105,82 @@ async function run(saveData) { await page.evaluate(() => document.exitFullscreen()); await sleep(500); s = await st(); check('out of full screen, the layer is back', s.shield && !s.fs, JSON.stringify(s)); + // YouTube's own full-screen button, pressed while we hold the screen: + // the frame asks for full screen from inside — that press means "out" + const b2 = await box(); + await page.touchscreen.tap(b2.x + b2.w * 0.3, b2.y + b2.h * 0.35); + await waitFor(() => document.fullscreenElement === document.querySelector('.yt-embed'), null, 3000); + await page.frames().find((x) => x.url().startsWith('https://www.youtube-nocookie.com/')).evaluate(() => { window.__fsButton = true; }); + await page.touchscreen.tap(200, 400); // inside the frame now + check('full screen, the player\'s own full-screen button leaves it', await waitFor(() => !document.fullscreenElement, null, 3000), await page.evaluate(() => String(document.fullscreenElement && document.fullscreenElement.tagName))); check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); } finally { await ctx.close(); } } -try { await run(false); await run(true); } finally { await browser.close(); server.stop(true); } +// A mouse reaches the player's own buttons, so its clicks are the player's: +// the middle one pauses, the corner one goes full screen and back. +async function runMouse() { + console.log('\n[a mouse: the player takes its own clicks]'); + const ctx = await browser.createBrowserContext(); + const page = await ctx.newPage(); + await page.setRequestInterception(true); + page.on('request', (r) => { + const u = r.url(); + if (u.startsWith('https://www.youtube-nocookie.com/embed/')) return r.respond({ status: 200, contentType: 'text/html', body: PLAYER }); + if (u.startsWith('https://i.ytimg.com/')) return r.respond({ status: 200, contentType: 'image/png', body: png }); + return r.continue(); + }); + await page.evaluateOnNewDocument(() => { + const Real = window.WebSocket; + window.WebSocket = function (...a) { const ws = new Real(...a); const send = ws.send.bind(ws); ws.send = (d) => { try { const m = JSON.parse(d); if (m[0] === 'REQ') { setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) })), 0); return; } if (m[0] === 'EVENT') return; } catch {} return send(d); }; return ws; }; + window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real); + }); + const errs = []; + page.on('pageerror', (e) => errs.push(String(e))); + const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); + const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; + const waitFor = async (fn, arg, ms = 10000) => { for (let i = 0; i < ms / 100; i++) { if (await page.evaluate(fn, arg)) return true; await sleep(100); } return false; }; + const box = () => page.evaluate(() => { const b = document.querySelector('.notes-feed .yt-embed').getBoundingClientRect(); return { x: b.x, y: b.y, w: b.width, h: b.height }; }); + const fsTag = () => page.evaluate(() => (document.fullscreenElement ? document.fullscreenElement.tagName : '')); + const player = () => page.frames().find((x) => x.url().startsWith('https://www.youtube-nocookie.com/')); + try { + await page.setViewport({ width: 1280, height: 900 }); + await page.goto(server.url.href, { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400); + await click('create a new wallet'); await sleep(600); + await seedWords(page); + const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' '); + await skipSeedCheck(page); + await waitText('receive', 20000); + const base = cacheKeyFor(mn + '\n'); + await page.evaluate(([k, pk, ns]) => { + localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', pk]], c: '', at: Math.floor(Date.now() / 1000) })); + localStorage.setItem(k + ':feedNotes', JSON.stringify(ns)); + localStorage.setItem(k + ':profiles', JSON.stringify({ [pk]: { name: 'Tuber', t: Date.now() } })); + localStorage.setItem('btc-wallet-feed:' + k, 'following'); + }, [base, AUTHOR, POSTS]); + await page.reload({ waitUntil: 'domcontentloaded' }); + await waitText('receive', 20000); + await page.evaluate(() => { const n = document.querySelector('.app-nav-button[aria-label="Feed"]') || [...document.querySelectorAll('a,button')].find((x) => /^feed$/i.test((x.getAttribute('aria-label') || x.textContent || '').trim())); if (n) n.click(); }); + await page.waitForSelector('.notes-feed .yt-embed', { timeout: 20000 }); + await page.evaluate(() => document.querySelector('.notes-feed .yt-embed').scrollIntoView({ block: 'center' })); + await waitFor(() => !!document.querySelector('.yt-embed iframe'), null, 6000); + await sleep(800); + const b = await box(); + await page.mouse.move(b.x + b.w * 0.4, b.y + b.h * 0.4); await sleep(200); + check('under a mouse, no layer over the player', await page.evaluate(() => { const sh = document.querySelector('.yt-embed .yt-shield'); return !sh || getComputedStyle(sh).display === 'none'; })); + await player().evaluate(() => { window.__fsButton = true; }); // from here every click is the corner button + await page.mouse.click(b.x + b.w * 0.5, b.y + b.h * 0.5); await sleep(600); + check('a click in the middle reaches the player', (await player().evaluate(() => window.__clicks)) === 1); + check('…and the page does not take the box full screen', (await fsTag()) !== 'DIV', await fsTag()); + check('…nor open the thread', !(await page.evaluate(() => !!document.querySelector('.thread-card')))); + // (the stand-in goes full screen on a click, as YouTube's corner button does) + check('the player\'s own full screen is left to it', (await fsTag()) === 'IFRAME', await fsTag()); + await page.mouse.click(400, 300); await sleep(600); + check('…and its button brings it back', (await fsTag()) === '', await fsTag()); + check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); + } finally { await ctx.close(); } +} +try { await run(false); await run(true); await runMouse(); } finally { await browser.close(); server.stop(true); } console.log(ok ? '\n✅ a YouTube clip: one tap, full screen, with sound' : '\n❌ failed'); process.exit(ok ? 0 : 1); |
