aboutsummaryrefslogtreecommitdiffstats
path: root/tools/extension-test.js
blob: 6ea9e2a377c7cc07f2fd45da222608d5424d1260 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888 } /* Comment */
.highlight .err { color: #A61717; background-color: #E3D2D2 } /* Error */
.highlight .k { color: #080; font-weight: bold } /* Keyword */
.highlight .ch { color: #888 } /* Comment.Hashbang */
.highlight .cm { color: #888 } /* Comment.Multiline */
.highlight .cp { color: #C00; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888 } /* Comment.Single */
.highlight .cs { color: #C00; font-weight: bold; background-color: #FFF0F0 } /* Comment.Special */
.highlight .gd { color: #000; background-color: #FDD } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #A00 } /* Generic.Error */
.highlight .gh { color: #333 } /* Generic.Heading */
.highlight .gi { color: #000; background-color: #DFD } /* Generic.Inserted */
.highlight .go { color: #888 } /* Generic.Output */
.highlight .gp { color: #555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666 } /* Generic.Subheading */
.highlight .gt { color: #A00 } /* Generic.Traceback */
.highlight .kc { color: #080; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #080; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #080; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #080 } /* Keyword.Pseudo */
.highlight .kr { color: #080; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #00D; font-weight: bold } /* Literal.Number */
.highlight .s { color: #D20; background-color: #FFF0F0 } /* Literal.String */
.highlight .na { color: #369 } /* Name.Attribute */
.highlight .nb { color: #038 } /* Name.Builtin */
.highlight .nc { color: #B06; font-weight: bold } /* Name.Class */
.highlight .no { color: #036; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555 } /* Name.Decorator */
.highlight .ne { color: #B06; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #06B; font-weight: bold } /* Name.Function */
.highlight .nl { color: #369; font-style: italic } /* Name.Label */
.highlight .nn { color: #B06; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #369; font-weight: bold } /* Name.Property */
.highlight .nt { color: #B06; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #369 } /* Name.Variable */
.highlight .ow { color: #080 } /* Operator.Word */
.highlight .w { color: #BBB } /* Text.Whitespace */
.highlight .mb { color: #00D; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #00D; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #00D; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #00D; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #00D; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #D20; background-color: #FFF0F0 } /* Literal.String.Affix */
.highlight .sb { color: #D20; background-color: #FFF0F0 } /* Literal.String.Backtick */
.highlight .sc { color: #D20; background-color: #FFF0F0 } /* Literal.String.Char */
.highlight .dl { color: #D20; background-color: #FFF0F0 } /* Literal.String.Delimiter */
.highlight .sd { color: #D20; background-color: #FFF0F0 } /* Literal.String.Doc */
.highlight .s2 { color: #D20; background-color: #FFF0F0 } /* Literal.String.Double */
.highlight .se { color: #04D; background-color: #FFF0F0 } /* Literal.String.Escape */
.highlight .sh { color: #D20; background-color: #FFF0F0 } /* Literal.String.Heredoc */
.highlight .si { color: #33B; background-color: #FFF0F0 } /* Literal.String.Interpol */
.highlight .sx { color: #2B2; background-color: #F0FFF0 } /* Literal.String.Other */
.highlight .sr { color: #080; background-color: #FFF0FF } /* Literal.String.Regex */
.highlight .s1 { color: #D20; background-color: #FFF0F0 } /* Literal.String.Single */
.highlight .ss { color: #A60; background-color: #FFF0F0 } /* Literal.String.Symbol */
.highlight .bp { color: #038 } /* Name.B
// 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);