aboutsummaryrefslogtreecommitdiffstats
path: root/tools
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2026-11-19 21:53:03 -0700
committerAdam Soltys <[email protected]>2026-11-19 21:53:03 -0700
commit69997b1cf47470bbe098ca042b5b64ef5e8873e6 (patch)
treefaa48099ca3582bf483bde0273fbe751aabb4219 /tools
parent01c03a199f8aafacfcdbaac30af074dd1d56fc53 (diff)
downloadcoinosv3-69997b1cf47470bbe098ca042b5b64ef5e8873e6.tar.gz
coinosv3-69997b1cf47470bbe098ca042b5b64ef5e8873e6.zip
A browser extension that signs for nostr sites without asking twice, and pays from a Coinos wallet. "I'm using Sidecar right now, and I don't like how I have to reauthorize it. It prompts me too much. I just want it to automatically sign all the time with my key" (Adam, 2026-11-19). The extension (extension/, Chrome, Manifest V3) gives every page window.nostr (NIP-07: getPublicKey, signEvent, nip04, nip44) and window.webln. A site is asked once: "Always allow" is remembered with no expiry until the site is removed in the popup, "Never for this site" blocks it, and closing the window refuses that one call. Signing and paying are separate permissions. The key is an nsec or a wallet's twelve words (NIP-06), kept in the extension's storage unencrypted so it can sign without a prompt. The wallet is the person's own Coinos wallet over Nostr Wallet Connect: the extension holds a connection string, the wallet enforces that connection's budget, and the popup shows the balance and recent payments. Build with `bun extension/build.js` and load extension/dist unpacked. New extension-test loads the built extension into Chrome with its own relay and wallet service and passes (28 checks).HEADmaster
Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_01VMan6WFVA5qCuTtny8PRL6
Diffstat (limited to 'tools')
-rw-r--r--tools/extension-test.js198
1 files changed, 198 insertions, 0 deletions
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);