diff options
| -rw-r--r-- | .gitignore | 3 | ||||
| -rw-r--r-- | extension/build.js | 23 | ||||
| -rw-r--r-- | extension/manifest.json | 27 | ||||
| -rw-r--r-- | extension/src/background.js | 305 | ||||
| -rw-r--r-- | extension/src/content.js | 15 | ||||
| -rw-r--r-- | extension/src/popup.html | 49 | ||||
| -rw-r--r-- | extension/src/popup.js | 81 | ||||
| -rw-r--r-- | extension/src/prompt.html | 17 | ||||
| -rw-r--r-- | extension/src/prompt.js | 20 | ||||
| -rw-r--r-- | extension/src/provider.js | 53 | ||||
| -rw-r--r-- | extension/src/ui.css | 49 | ||||
| -rw-r--r-- | tools/extension-test.js | 198 |
12 files changed, 840 insertions, 0 deletions
@@ -16,3 +16,6 @@ tools/.*.tmp.js # Local runtime session store (server side, not part of the wallet build) /db/ + +# Browser extension build (rebuild with `bun extension/build.js`) +/extension/dist diff --git a/extension/build.js b/extension/build.js new file mode 100644 index 0000000..e9013e0 --- /dev/null +++ b/extension/build.js @@ -0,0 +1,23 @@ +// Builds the browser extension into extension/dist (load that folder +// unpacked at chrome://extensions, Developer mode on). +// bun extension/build.js +import { rm, mkdir, cp } from 'node:fs/promises'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = dirname(fileURLToPath(import.meta.url)); +const out = join(here, 'dist'); +await rm(out, { recursive: true, force: true }); +await mkdir(out, { recursive: true }); + +const r = await Bun.build({ + entrypoints: ['background.js', 'popup.js', 'prompt.js'].map((f) => join(here, 'src', f)), + outdir: out, target: 'browser', format: 'esm', minify: false, +}); +if (!r.success) { for (const l of r.logs) console.error(l); process.exit(1); } + +for (const f of ['content.js', 'provider.js', 'popup.html', 'prompt.html', 'ui.css']) await cp(join(here, 'src', f), join(out, f)); +await cp(join(here, 'manifest.json'), join(out, 'manifest.json')); +await cp(join(here, '..', 'static', 'icon-192.png'), join(out, 'icon-192.png')); +await cp(join(here, '..', 'static', 'PublicSans.woff2'), join(out, 'PublicSans.woff2')); +console.log('extension built →', out); diff --git a/extension/manifest.json b/extension/manifest.json new file mode 100644 index 0000000..1035476 --- /dev/null +++ b/extension/manifest.json @@ -0,0 +1,27 @@ +{ + "manifest_version": 3, + "name": "Coinos", + "version": "0.1.0", + "description": "Sign in to nostr sites with your key and pay from your Coinos wallet. Approve a site once and it never asks again.", + "minimum_chrome_version": "116", + "icons": { "16": "icon-192.png", "48": "icon-192.png", "128": "icon-192.png" }, + "action": { "default_popup": "popup.html", "default_title": "Coinos", "default_icon": "icon-192.png" }, + "options_ui": { "page": "popup.html", "open_in_tab": true }, + "background": { "service_worker": "background.js", "type": "module" }, + "permissions": ["storage"], + "content_scripts": [ + { + "matches": ["http://*/*", "https://*/*"], + "js": ["content.js"], + "run_at": "document_start", + "all_frames": true + }, + { + "matches": ["http://*/*", "https://*/*"], + "js": ["provider.js"], + "run_at": "document_start", + "all_frames": true, + "world": "MAIN" + } + ] +} diff --git a/extension/src/background.js b/extension/src/background.js new file mode 100644 index 0000000..dcefa18 --- /dev/null +++ b/extension/src/background.js @@ -0,0 +1,305 @@ +// The extension's background worker. It holds the nostr key and the wallet +// connection, decides which sites may use them, and answers the calls a +// page makes through window.nostr and window.webln. +// +// A site is asked about once: "Always allow" is remembered for good (until +// the site is removed in the popup), so signing never prompts again. Signing +// and paying are separate permissions. +// +// The wallet is the person's Coinos wallet, reached over Nostr Wallet Connect +// (NIP-47): the extension holds a connection string, never the wallet's keys, +// and the wallet enforces that connection's budget. + +import { finalizeEvent, getPublicKey, nip04, nip19, nip44 } from 'nostr-tools'; +import { Relay } from 'nostr-tools/relay'; +import { HDKey } from '@scure/bip32'; +import { mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english.js'; +import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'; + +const store = { + get: async (k) => (await chrome.storage.local.get(k))[k], + set: (k, v) => chrome.storage.local.set({ [k]: v }), + del: (k) => chrome.storage.local.remove(k), +}; + +// ── the key ──────────────────────────────────────────────────────────────── +// Kept in the extension's own storage, unencrypted: signing without a prompt +// means the key has to be readable whenever a site asks. No page can read it. +async function secretKey() { + const k = await store.get('key'); + if (!k || !k.sk) throw new Error('The Coinos extension has no key yet. Click its icon to set it up.'); + return hexToBytes(k.sk); +} + +// "nsec1…", 64 hex characters, or twelve/twenty-four words (NIP-06, the key +// Coinos derives for a wallet: m/44'/1237'/0'/0/0). +function parseKey(input) { + const s = String(input || '').trim(); + if (/^nsec1/i.test(s)) { + const d = nip19.decode(s.toLowerCase()); + if (d.type !== 'nsec') throw new Error('That is not an nsec'); + return { sk: bytesToHex(d.data), source: 'nsec' }; + } + if (/^[0-9a-f]{64}$/i.test(s)) return { sk: s.toLowerCase(), source: 'hex' }; + const words = s.toLowerCase().split(/\s+/).join(' '); + if (validateMnemonic(words, wordlist)) { + const sk = HDKey.fromMasterSeed(mnemonicToSeedSync(words)).derive("m/44'/1237'/0'/0/0").privateKey; + return { sk: bytesToHex(sk), source: 'seed' }; + } + throw new Error('Enter an nsec, or the twelve words of a Coinos wallet'); +} + +// ── sites ────────────────────────────────────────────────────────────────── +// sites[origin] = { sign: true|false, pay: true|false, at } — true is "always +// allow", false is "never", absent means ask. +const sitesOf = async () => (await store.get('sites')) || {}; + +const asks = new Map(); // `${origin} ${kind}` → { promise, resolve, reject, windowId } +let askSeq = 0; + +// A worker with nothing to do is stopped after 30 s; one waiting on a prompt +// or on the wallet has to stay. Any extension API call resets that clock. +let busy = 0; +let beat = null; +function hold() { + busy++; + if (!beat) beat = setInterval(() => { chrome.runtime.getPlatformInfo(() => {}); }, 20_000); + return () => { if (--busy <= 0) { busy = 0; clearInterval(beat); beat = null; } }; +} + +async function allowed(origin, kind) { + const site = (await sitesOf())[origin]; + if (site && site[kind] === true) return; + if (site && site[kind] === false) throw new Error('This site is blocked in the Coinos extension'); + const key = `${origin} ${kind}`; + let ask = asks.get(key); + if (!ask) { + ask = { id: `${Date.now().toString(36)}${++askSeq}` }; + ask.promise = new Promise((resolve, reject) => { ask.resolve = resolve; ask.reject = reject; }); + asks.set(key, ask); + const release = hold(); + ask.promise.catch(() => {}).finally(() => { asks.delete(key); release(); }); + const url = chrome.runtime.getURL(`prompt.html?id=${ask.id}&kind=${kind}&origin=${encodeURIComponent(origin)}`); + try { + const w = await chrome.windows.create({ url, type: 'popup', width: 400, height: 330, focused: true }); + ask.windowId = w.id; + } catch (err) { + ask.reject(new Error('Could not open the approval window')); + } + } + return ask.promise; +} + +// the prompt closed without an answer: this request is refused, the site is +// asked again next time +chrome.windows.onRemoved.addListener((windowId) => { + for (const ask of asks.values()) if (ask.windowId === windowId) ask.reject(new Error('Request was dismissed')); +}); + +async function answerAsk({ id, origin, kind, choice }) { + const ask = [...asks.values()].find((a) => a.id === id); + if (choice === 'always' || choice === 'never') { + const sites = await sitesOf(); + sites[origin] = { ...(sites[origin] || {}), [kind]: choice === 'always', at: Date.now() }; + await store.set('sites', sites); + } + if (!ask) return; + if (choice === 'always') ask.resolve(); + else ask.reject(new Error(choice === 'never' ? 'This site is blocked in the Coinos extension' : 'Request was denied')); +} + +// ── the wallet (NIP-47 client) ───────────────────────────────────────────── +function parseNwc(uri) { + const s = String(uri || '').trim(); + if (!/^nostr\+walletconnect:/i.test(s)) throw new Error('Paste a connection string that starts with nostr+walletconnect://'); + const u = new URL(s.replace(/^nostr\+walletconnect:(\/\/)?/i, 'http://')); + const walletPk = u.hostname.toLowerCase(); + const secret = (u.searchParams.get('secret') || '').toLowerCase(); + const relays = u.searchParams.getAll('relay').filter((r) => /^wss?:\/\//.test(r)); + if (!/^[0-9a-f]{64}$/.test(walletPk) || !/^[0-9a-f]{64}$/.test(secret) || !relays.length) throw new Error('That connection string is incomplete'); + return { walletPk, secret, relays }; +} + +// One request, one answer. The request goes to every relay in the connection +// and the first reply wins; a relay that is down is skipped. +async function wallet(method, params = {}, timeout = 60_000) { + const c = await store.get('nwc'); + if (!c) throw new Error('No wallet is connected. Click the Coinos extension to connect one.'); + const sk = hexToBytes(c.secret); + const content = await nip04.encrypt(sk, c.walletPk, JSON.stringify({ method, params })); + const req = finalizeEvent({ kind: 23194, created_at: Math.floor(Date.now() / 1000), tags: [['p', c.walletPk]], content }, sk); + const release = hold(); + const open = []; + try { + return await new Promise((resolve, reject) => { + let done = false; + let sent = 0; + let failed = 0; + const finish = (fn, v) => { if (!done) { done = true; clearTimeout(timer); fn(v); } }; + const timer = setTimeout(() => finish(reject, new Error(sent ? 'The wallet did not answer in time' : 'Could not reach the wallet\'s relays')), timeout); + const onevent = async (ev) => { + if (done || ev.pubkey !== c.walletPk) return; + try { + const res = JSON.parse(await nip04.decrypt(sk, c.walletPk, ev.content)); + if (res.error) finish(reject, new Error(res.error.message || res.error.code || 'The wallet refused')); + else finish(resolve, res.result || {}); + } catch (_) { /* not ours to read */ } + }; + for (const url of c.relays) { + (async () => { + try { + const relay = await Relay.connect(url); + open.push(relay); + if (done) return; + relay.subscribe([{ kinds: [23195], authors: [c.walletPk], '#e': [req.id] }], { onevent }); + await relay.publish(req); + sent++; + } catch (_) { + if (++failed === c.relays.length) finish(reject, new Error('Could not reach the wallet\'s relays')); + } + })(); + } + }); + } finally { + for (const r of open) { try { r.close(); } catch (_) {} } + release(); + } +} + +// ── what a page may call ─────────────────────────────────────────────────── +const SIGN = new Set(['nostr.getPublicKey', 'nostr.signEvent', 'nostr.getRelays', 'nostr.nip04.encrypt', 'nostr.nip04.decrypt', 'nostr.nip44.encrypt', 'nostr.nip44.decrypt']); +const PAY = new Set(['webln.enable', 'webln.getInfo', 'webln.sendPayment', 'webln.makeInvoice', 'webln.getBalance']); +const hex64 = (s) => typeof s === 'string' && /^[0-9a-f]{64}$/i.test(s); + +async function pageCall(origin, method, p = {}) { + if (SIGN.has(method)) { + const sk = await secretKey(); // "set me up" before "allow this site?" + await allowed(origin, 'sign'); + switch (method) { + case 'nostr.getPublicKey': return getPublicKey(sk); + case 'nostr.getRelays': return {}; + case 'nostr.signEvent': { + const e = p.event || {}; + if (!Number.isInteger(e.kind) || typeof e.content !== 'string') throw new Error('Not a nostr event'); + return finalizeEvent({ + kind: e.kind, + content: e.content, + tags: Array.isArray(e.tags) ? e.tags : [], + created_at: Number.isInteger(e.created_at) ? e.created_at : Math.floor(Date.now() / 1000), + }, sk); + } + } + if (!hex64(p.pubkey)) throw new Error('Not a public key'); + const pk = p.pubkey.toLowerCase(); + switch (method) { + case 'nostr.nip04.encrypt': return nip04.encrypt(sk, pk, String(p.plaintext)); + case 'nostr.nip04.decrypt': return nip04.decrypt(sk, pk, String(p.ciphertext)); + case 'nostr.nip44.encrypt': return nip44.encrypt(String(p.plaintext), nip44.getConversationKey(sk, pk)); + case 'nostr.nip44.decrypt': return nip44.decrypt(String(p.ciphertext), nip44.getConversationKey(sk, pk)); + } + } + if (PAY.has(method)) { + if (!(await store.get('nwc'))) throw new Error('No wallet is connected. Click the Coinos extension to connect one.'); + await allowed(origin, 'pay'); + switch (method) { + case 'webln.enable': return { enabled: true }; + case 'webln.getInfo': return { node: { alias: 'Coinos' }, methods: ['enable', 'getInfo', 'sendPayment', 'makeInvoice', 'getBalance'], supports: ['lightning'] }; + case 'webln.sendPayment': { + const invoice = String(p.paymentRequest || '').trim().replace(/^lightning:/i, ''); + if (!/^ln/i.test(invoice)) throw new Error('Not a Lightning invoice'); + const r = await wallet('pay_invoice', { invoice }, 90_000); + return { preimage: r.preimage || '' }; + } + case 'webln.makeInvoice': { + const a = p.args; + const o = a && typeof a === 'object' ? a : { amount: a }; + const sats = Number(o.amount ?? o.defaultAmount ?? 0); + if (!Number.isFinite(sats) || sats <= 0) throw new Error('An invoice needs an amount'); + const r = await wallet('make_invoice', { amount: Math.round(sats * 1000), description: String(o.defaultMemo || o.memo || '') }); + return { paymentRequest: r.invoice, rHash: r.payment_hash || '' }; + } + case 'webln.getBalance': { + const r = await wallet('get_balance', {}, 20_000); + return { balance: Math.floor((r.balance || 0) / 1000), currency: 'sats' }; + } + } + } + throw new Error(`${method} is not supported by the Coinos extension`); +} + +// ── what the extension's own pages (popup, prompt) may call ──────────────── +async function profileOf(pk) { + // the name and picture for the popup's header, when a relay has them + const cached = await store.get('profile'); + if (cached && cached.pk === pk && Date.now() - cached.at < 6 * 3600_000) return cached; + let relay; + try { + relay = await Relay.connect('wss://relay.coinos.io'); + const ev = await new Promise((resolve) => { + let best = null; + const t = setTimeout(() => resolve(best), 3000); + relay.subscribe([{ kinds: [0], authors: [pk], limit: 1 }], { + onevent: (e) => { if (!best || e.created_at > best.created_at) best = e; }, + oneose: () => { clearTimeout(t); resolve(best); }, + }); + }); + const m = ev ? JSON.parse(ev.content) : {}; + const out = { pk, at: Date.now(), name: String(m.display_name || m.name || '').slice(0, 60), picture: /^https:\/\//.test(m.picture || '') ? m.picture : '', nip05: String(m.nip05 || '').slice(0, 80) }; + await store.set('profile', out); + return out; + } catch (_) { return cached && cached.pk === pk ? cached : null; } + finally { try { relay && relay.close(); } catch (_) {} } +} + +async function ownCall(m) { + switch (m.type) { + case 'state': { + const k = await store.get('key'); + const pk = k ? getPublicKey(hexToBytes(k.sk)) : null; + const c = await store.get('nwc'); + return { pubkey: pk, npub: pk ? nip19.npubEncode(pk) : null, source: k ? k.source : null, wallet: c ? { relays: c.relays } : null, sites: await sitesOf() }; + } + case 'profile': { + const k = await store.get('key'); + return k ? profileOf(getPublicKey(hexToBytes(k.sk))) : null; + } + case 'setKey': await store.set('key', parseKey(m.input)); await store.del('profile'); return true; + case 'removeKey': await store.del('key'); await store.del('profile'); return true; + case 'setWallet': await store.set('nwc', parseNwc(m.uri)); return true; + case 'removeWallet': await store.del('nwc'); return true; + case 'removeSite': { + const sites = await sitesOf(); + delete sites[m.origin]; + await store.set('sites', sites); + return true; + } + case 'balance': { + const r = await wallet('get_balance', {}, 20_000); + return Math.floor((r.balance || 0) / 1000); + } + case 'transactions': { + const r = await wallet('list_transactions', { limit: 12 }, 20_000); + return (r.transactions || []).map((t) => ({ + type: t.type, sats: Math.floor((t.amount || 0) / 1000), at: t.settled_at || t.created_at || 0, memo: String(t.description || '').slice(0, 80), + })); + } + case 'answer': await answerAsk(m); return true; + } + throw new Error('Unknown message'); +} + +chrome.runtime.onMessage.addListener((m, sender, respond) => { + if (!m || typeof m !== 'object') return; + const own = !!sender.url && sender.url.startsWith(chrome.runtime.getURL('')) && sender.id === chrome.runtime.id; + let work; + if (m.type === 'request' && !own) { + let origin = sender.origin; + if (!origin || origin === 'null') { try { origin = new URL(sender.url).origin; } catch (_) { origin = ''; } } + work = /^https?:\/\//.test(origin) ? pageCall(origin, String(m.method), m.params || {}) : Promise.reject(new Error('This page cannot use the Coinos extension')); + } else if (own) { + work = ownCall(m); + } else return; + work.then((result) => respond({ result }), (err) => respond({ error: String((err && err.message) || err) })); + return true; // answered later +}); diff --git a/extension/src/content.js b/extension/src/content.js new file mode 100644 index 0000000..bf1ca65 --- /dev/null +++ b/extension/src/content.js @@ -0,0 +1,15 @@ +// The bridge between a page's window.nostr / window.webln (provider.js, in +// the page's own world) and the extension's background worker. +window.addEventListener('message', async (e) => { + if (e.source !== window || !e.data || e.data.__coinos !== 'req') return; + const { id, method, params } = e.data; + let res; + try { + res = await chrome.runtime.sendMessage({ type: 'request', method, params }); + if (!res) res = { error: 'The Coinos extension did not answer' }; + } catch (err) { + // the extension was reloaded or updated under this page + res = { error: /context invalidated/i.test(String(err && err.message)) ? 'The Coinos extension was updated. Reload this page.' : String((err && err.message) || err) }; + } + window.postMessage({ __coinos: 'res', id, result: res.result, error: res.error }, '*'); +}); diff --git a/extension/src/popup.html b/extension/src/popup.html new file mode 100644 index 0000000..331b838 --- /dev/null +++ b/extension/src/popup.html @@ -0,0 +1,49 @@ +<!doctype html> +<html lang="en"> +<head><meta charset="utf-8"><title>Coinos</title><link rel="stylesheet" href="ui.css"></head> +<body> + <section id="setup" hidden> + <div class="card"> + <h1>Set up your key</h1> + <p class="muted" style="margin-top:6px">Paste your nsec, or the twelve words of a Coinos wallet. It stays in this browser and is never shown to a site.</p> + <textarea id="key-input" spellcheck="false" autocomplete="off" aria-label="nsec or twelve words"></textarea> + <p class="err" id="key-err"></p> + <button id="key-save" class="primary" style="width:100%">Save key</button> + </div> + </section> + + <section id="main" hidden> + <div class="head"> + <img id="pic" src="icon-192.png" alt=""> + <div class="who"> + <div id="name" style="font-weight:650"></div> + <div class="mono muted" id="npub"></div> + </div> + <button id="copy">Copy</button> + </div> + + <div class="card" id="wallet-on" hidden> + <h2>Wallet</h2> + <div class="balance" id="balance">…</div> + <p class="err" id="wallet-err"></p> + <ul id="txs"></ul> + <p class="small" style="margin:10px 0 0"><button id="wallet-remove" class="link">Disconnect wallet</button></p> + </div> + <div class="card" id="wallet-off" hidden> + <h2>Wallet</h2> + <p class="muted">To pay from sites, open Coinos, go to Settings and add a connection under Nostr Wallet Connect, then paste its connection string here.</p> + <textarea id="nwc-input" spellcheck="false" autocomplete="off" aria-label="Connection string" placeholder="nostr+walletconnect://…"></textarea> + <p class="err" id="nwc-err"></p> + <button id="nwc-save" class="primary" style="width:100%">Connect wallet</button> + </div> + + <div class="card"> + <h2>Sites</h2> + <p class="muted small" id="no-sites">No site has asked yet. The first time one does, you choose once.</p> + <ul id="sites"></ul> + </div> + <p class="small" style="text-align:center"><button id="key-remove" class="link">Remove key from this browser</button></p> + </section> + <script type="module" src="popup.js"></script> +</body> +</html> diff --git a/extension/src/popup.js b/extension/src/popup.js new file mode 100644 index 0000000..8d9f8cf --- /dev/null +++ b/extension/src/popup.js @@ -0,0 +1,81 @@ +// The extension's popup (and, opened in a tab, its settings page): the key, +// the connected wallet's balance and recent payments, and the sites that +// were allowed or blocked. +const $ = (id) => document.getElementById(id); +const send = async (m) => { + const r = await chrome.runtime.sendMessage(m); + if (!r || r.error) throw new Error((r && r.error) || 'No answer'); + return r.result; +}; +if (new URLSearchParams(location.search).has('tab') || window.innerWidth > 500) document.body.classList.add('tab'); +const sats = (n) => Number(n).toLocaleString('en-US'); +const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }; + +async function render() { + const s = await send({ type: 'state' }); + $('setup').hidden = !!s.pubkey; + $('main').hidden = !s.pubkey; + if (!s.pubkey) { $('key-input').focus(); return; } + + $('npub').textContent = s.npub.slice(0, 14) + '…' + s.npub.slice(-6); + $('name').textContent = 'Your key'; + $('copy').onclick = async () => { await navigator.clipboard.writeText(s.npub); $('copy').textContent = 'Copied'; setTimeout(() => { $('copy').textContent = 'Copy'; }, 1200); }; + send({ type: 'profile' }).then((p) => { + if (!p) return; + if (p.name) $('name').textContent = p.name; + if (p.picture) $('pic').src = p.picture; + }).catch(() => {}); + + $('wallet-on').hidden = !s.wallet; + $('wallet-off').hidden = !!s.wallet; + if (s.wallet) { + $('wallet-err').textContent = ''; + send({ type: 'balance' }).then((b) => { + $('balance').textContent = sats(b); + $('balance').append(el('span', '', 'sats')); + }).catch((e) => { $('balance').textContent = '—'; $('wallet-err').textContent = e.message; }); + send({ type: 'transactions' }).then((txs) => { + $('txs').replaceChildren(...txs.map((t) => { + const li = el('li'); + li.append(el('span', 'grow', t.memo || (t.type === 'incoming' ? 'Received' : 'Sent'))); + li.append(el('span', t.type === 'incoming' ? 'in' : '', (t.type === 'incoming' ? '+' : '−') + sats(t.sats))); + return li; + })); + }).catch(() => {}); + } + + const sites = Object.entries(s.sites).sort((a, b) => (b[1].at || 0) - (a[1].at || 0)); + $('no-sites').hidden = sites.length > 0; + $('sites').replaceChildren(...sites.map(([origin, p]) => { + const li = el('li'); + li.append(el('span', 'grow', origin.replace(/^https:\/\//, ''))); + if (p.sign === true) li.append(el('span', 'tag', 'signs')); + if (p.pay === true) li.append(el('span', 'tag', 'pays')); + if (p.sign === false || p.pay === false) li.append(el('span', 'tag', 'blocked')); + const rm = el('button', 'link', 'Remove'); + rm.setAttribute('aria-label', 'Remove ' + origin); + rm.onclick = async () => { await send({ type: 'removeSite', origin }); render(); }; + li.append(rm); + return li; + })); +} + +$('key-save').onclick = async () => { + $('key-err').textContent = ''; + try { await send({ type: 'setKey', input: $('key-input').value }); $('key-input').value = ''; render(); } + catch (e) { $('key-err').textContent = e.message; } +}; +$('nwc-save').onclick = async () => { + $('nwc-err').textContent = ''; + try { await send({ type: 'setWallet', uri: $('nwc-input').value }); $('nwc-input').value = ''; render(); } + catch (e) { $('nwc-err').textContent = e.message; } +}; +$('wallet-remove').onclick = async () => { await send({ type: 'removeWallet' }); render(); }; +$('key-remove').onclick = async () => { + const b = $('key-remove'); + if (b.dataset.sure !== '1') { b.dataset.sure = '1'; b.textContent = 'Click again to remove the key'; return; } + await send({ type: 'removeKey' }); + b.dataset.sure = ''; b.textContent = 'Remove key from this browser'; + render(); +}; +render(); diff --git a/extension/src/prompt.html b/extension/src/prompt.html new file mode 100644 index 0000000..bca4f82 --- /dev/null +++ b/extension/src/prompt.html @@ -0,0 +1,17 @@ +<!doctype html> +<html lang="en"> +<head><meta charset="utf-8"><title>Coinos</title><link rel="stylesheet" href="ui.css"></head> +<body class="prompt"> + <div class="card"> + <h2 id="what"></h2> + <p class="origin" id="origin"></p> + <p class="muted" id="detail"></p> + <div class="buttons"> + <button id="deny">Not now</button> + <button id="allow" class="primary">Always allow</button> + </div> + </div> + <p class="small" style="text-align:center"><button id="never" class="link">Never for this site</button></p> + <script type="module" src="prompt.js"></script> +</body> +</html> diff --git a/extension/src/prompt.js b/extension/src/prompt.js new file mode 100644 index 0000000..6637f70 --- /dev/null +++ b/extension/src/prompt.js @@ -0,0 +1,20 @@ +// The one question a site ever gets asked: may it use the key (or the +// wallet)? "Always allow" is remembered; the site is not asked again. +const q = new URLSearchParams(location.search); +const origin = q.get('origin') || ''; +const kind = q.get('kind') === 'pay' ? 'pay' : 'sign'; +const $ = (id) => document.getElementById(id); +$('origin').textContent = origin.replace(/^https:\/\//, ''); +$('what').textContent = kind === 'pay' ? 'Let this site use your wallet?' : 'Let this site use your nostr key?'; +$('detail').textContent = kind === 'pay' + ? 'It will be able to see your balance, create invoices and send payments without asking, within the limit you set on the wallet connection.' + : 'It will be able to see your public key, sign as you and read your private messages, without asking again.'; +const answer = async (choice) => { + for (const b of document.querySelectorAll('button')) b.disabled = true; + await chrome.runtime.sendMessage({ type: 'answer', id: q.get('id'), origin, kind, choice }); + window.close(); +}; +$('allow').onclick = () => answer('always'); +$('deny').onclick = () => answer('deny'); +$('never').onclick = () => answer('never'); +$('allow').focus(); diff --git a/extension/src/provider.js b/extension/src/provider.js new file mode 100644 index 0000000..d662212 --- /dev/null +++ b/extension/src/provider.js @@ -0,0 +1,53 @@ +// Runs in the page itself: window.nostr (NIP-07) and window.webln. Every call +// is a message to the content script, which hands it to the extension; the +// key and the wallet connection never enter the page. +(() => { + if (window.nostr && window.nostr._coinos) return; + const pending = new Map(); + let n = 0; + window.addEventListener('message', (e) => { + if (e.source !== window || !e.data || e.data.__coinos !== 'res') return; + const p = pending.get(e.data.id); + if (!p) return; + pending.delete(e.data.id); + if (e.data.error) p.reject(new Error(e.data.error)); + else p.resolve(e.data.result); + }); + const call = (method, params) => new Promise((resolve, reject) => { + const id = `${Date.now().toString(36)}-${++n}-${Math.random().toString(36).slice(2)}`; + pending.set(id, { resolve, reject }); + window.postMessage({ __coinos: 'req', id, method, params }, '*'); + }); + + window.nostr = { + _coinos: true, + getPublicKey: () => call('nostr.getPublicKey'), + signEvent: (event) => call('nostr.signEvent', { event }), + getRelays: () => call('nostr.getRelays'), + nip04: { + encrypt: (pubkey, plaintext) => call('nostr.nip04.encrypt', { pubkey, plaintext }), + decrypt: (pubkey, ciphertext) => call('nostr.nip04.decrypt', { pubkey, ciphertext }), + }, + nip44: { + encrypt: (pubkey, plaintext) => call('nostr.nip44.encrypt', { pubkey, plaintext }), + decrypt: (pubkey, ciphertext) => call('nostr.nip44.decrypt', { pubkey, ciphertext }), + }, + }; + + const unsupported = (what) => () => Promise.reject(new Error(`${what} is not supported by the Coinos extension`)); + window.webln = { + _coinos: true, + enabled: false, + isEnabled: () => Promise.resolve(window.webln.enabled), + enable: async () => { const r = await call('webln.enable'); window.webln.enabled = true; return r; }, + getInfo: () => call('webln.getInfo'), + sendPayment: (paymentRequest) => call('webln.sendPayment', { paymentRequest }), + makeInvoice: (args) => call('webln.makeInvoice', { args }), + getBalance: () => call('webln.getBalance'), + keysend: unsupported('keysend'), + signMessage: unsupported('signMessage'), + verifyMessage: unsupported('verifyMessage'), + lnurl: unsupported('lnurl'), + }; + window.dispatchEvent(new Event('webln:ready')); +})(); diff --git a/extension/src/ui.css b/extension/src/ui.css new file mode 100644 index 0000000..26c183b --- /dev/null +++ b/extension/src/ui.css @@ -0,0 +1,49 @@ +@font-face { font-family: "Public Sans"; font-weight: 100 900; font-display: swap; src: url("PublicSans.woff2") format("woff2"); } +:root { + --bg: #eef0f3; --paper: #fff; --ink: #15171a; --muted: #6b7280; --line: #e6e8ec; --line-strong: #d4d8de; + --fill: #15171a; --fill-fg: #fff; --soft: #f7f8fa; --green: #14935a; --red: #c43b3b; + --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace; + --sans: "Public Sans", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} +@media (prefers-color-scheme: dark) { + :root { --bg: #15171a; --paper: #1d2024; --ink: #eceef1; --muted: #9aa1ac; --line: #2a2e34; --line-strong: #3a3f47; --fill: #34383f; --fill-fg: #fff; --soft: #24272c; --green: #3ecf8e; --red: #ef6b6b; } +} +* { box-sizing: border-box; } +html, body { margin: 0; background: var(--bg); color: var(--ink); font: 14px/1.45 var(--sans); } +body { width: 360px; padding: 14px; } +body.prompt { width: auto; } +body.tab { width: auto; max-width: 440px; margin: 0 auto; padding: 32px 14px; } +h1 { font-size: 15px; font-weight: 650; margin: 0; } +h2 { font-size: 12px; font-weight: 600; color: var(--muted); margin: 0 0 8px; } +p { margin: 0 0 10px; } +.muted { color: var(--muted); } +.small { font-size: 12px; } +.card { background: var(--paper); border: 1px solid var(--line); border-radius: 14px; padding: 14px; margin-bottom: 10px; } +.head { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; } +.head img { width: 36px; height: 36px; border-radius: 50%; object-fit: cover; background: var(--soft); flex: none; } +.head .who { min-width: 0; flex: 1; } +.head .who div { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.mono { font-family: var(--mono); font-size: 12px; } +button { font: inherit; font-weight: 600; border-radius: 10px; border: 1px solid var(--line-strong); background: var(--paper); color: var(--ink); padding: 9px 12px; cursor: pointer; } +button:hover { background: var(--soft); } +button.primary { background: var(--fill); border-color: var(--fill); color: var(--fill-fg); } +button.primary:hover { filter: brightness(1.15); } +button.link { border: 0; background: none; padding: 0; font-weight: 500; color: var(--muted); text-decoration: underline; } +button.link:hover { color: var(--ink); background: none; } +button:disabled { opacity: .55; cursor: default; } +button:focus-visible, textarea:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; } +textarea { width: 100%; font: 13px/1.4 var(--mono); color: var(--ink); background: var(--soft); border: 1px solid var(--line-strong); border-radius: 10px; padding: 10px; resize: vertical; min-height: 68px; margin-bottom: 8px; } +.row { display: flex; align-items: center; gap: 8px; } +.grow { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.balance { font-size: 26px; font-weight: 650; letter-spacing: -0.01em; } +.balance span { font-size: 13px; font-weight: 500; color: var(--muted); margin-left: 4px; } +ul { list-style: none; margin: 0; padding: 0; } +li { display: flex; align-items: center; gap: 8px; padding: 7px 0; border-top: 1px solid var(--line); } +li:first-child { border-top: 0; } +.in { color: var(--green); } +.err { color: var(--red); font-size: 12px; min-height: 16px; margin: 0 0 6px; } +.tag { font-size: 11px; color: var(--muted); border: 1px solid var(--line-strong); border-radius: 999px; padding: 1px 7px; } +.buttons { display: flex; gap: 8px; } +.buttons button { flex: 1; } +.origin { font-weight: 650; font-size: 16px; word-break: break-all; margin: 0 0 8px; } +[hidden] { display: none !important; } 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); |
