diff options
Diffstat (limited to 'extension/src/background.js')
| -rw-r--r-- | extension/src/background.js | 305 |
1 files changed, 305 insertions, 0 deletions
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 +}); |
