aboutsummaryrefslogtreecommitdiffstats
path: root/extension
diff options
context:
space:
mode:
Diffstat (limited to 'extension')
-rw-r--r--extension/build.js23
-rw-r--r--extension/manifest.json27
-rw-r--r--extension/src/background.js305
-rw-r--r--extension/src/content.js15
-rw-r--r--extension/src/popup.html49
-rw-r--r--extension/src/popup.js81
-rw-r--r--extension/src/prompt.html17
-rw-r--r--extension/src/prompt.js20
-rw-r--r--extension/src/provider.js53
-rw-r--r--extension/src/ui.css49
10 files changed, 639 insertions, 0 deletions
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; }