aboutsummaryrefslogtreecommitdiffstats
path: root/extension/src/background.js
blob: dcefa184e72a789d1f0a2247982b1bc4e748188e (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
});