aboutsummaryrefslogtreecommitdiffstats
path: root/src/clink.js
blob: 9f381c1e53421ee7fdefa021f924b2fd183636e6 (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
// CLINK payer — ask an offer code's service for an invoice over nostr.
// The counterpart of src/noffer.js (the codec) and the responder in
// features/nwc.js: a NIP-44-encrypted kind-21001 request goes to the service
// pubkey on the relay the code names, and {bolt11} (or {error}) comes back.

import {
  nip44, finalizeEvent, generateSecretKey, publishOn, subscribeOn,
} from './nostr.js';

const OFFER_KIND = 21001;

// dest: a decoded noffer ({ pubkey, relay, offerId }). Signs with a throwaway
// key, so paying reveals no identity to the service. amountSat may be omitted
// for offers that price themselves (the returned invoice carries the amount).
// Resolves the bolt11 string; rejects on a service error or silence.
export function requestOfferInvoice(dest, { amountSat, description, timeoutMs = 12000 } = {}) {
  return new Promise((resolve, reject) => {
    const relays = [dest.relay].filter(Boolean);
    if (!relays.length) return reject(new Error('offer code names no relay'));
    const sk = generateSecretKey();
    const key = nip44.getConversationKey(sk, dest.pubkey);
    const payload = { offer: dest.offerId || '' };
    if (amountSat) payload.amount_sats = Math.floor(amountSat);
    if (description) payload.description = String(description).slice(0, 100);
    const req = finalizeEvent({
      kind: OFFER_KIND, created_at: Math.floor(Date.now() / 1000),
      tags: [['p', dest.pubkey], ['clink_version', '1']],
      content: nip44.encrypt(JSON.stringify(payload), key),
    }, sk);
    let done = false;
    let close = () => {};
    const finish = (err, bolt11) => {
      if (done) return;
      done = true;
      clearTimeout(timer);
      close();
      err ? reject(err) : resolve(bolt11);
    };
    const timer = setTimeout(() => finish(new Error('the recipient’s service did not answer')), timeoutMs);
    // subscribe before publishing — a fast service can answer within the RTT
    close = subscribeOn(relays, { kinds: [OFFER_KIND], '#e': [req.id], since: Math.floor(Date.now() / 1000) - 5 }, (ev) => {
      try {
        const body = JSON.parse(nip44.decrypt(ev.content, key));
        if (body.bolt11) return finish(null, body.bolt11);
        if (body.error) return finish(new Error(body.error));
      } catch {}
    });
    publishOn(relays, req).catch(() => {});
  });
}
Inboxes() { try { return await tx('readonly', (s) => new Promise((res, rej) => { const out = []; const cur = s.openCursor(); cur.onsuccess = () => { const c = cur.result; if (!c) return res(out); out.push(c.value); c.continue(); }; cur.onerror = () => rej(cur.error); })); } catch { return []; } } const unhex = (h) => Uint8Array.from(h.match(/.{2}/g).map((b) => parseInt(b, 16))); // Open a wrap against every identity we hold a key for. Returns // { author, followed, name, mine } for the first one that opens it, or null // if none can — which includes every remote-signer wallet, so a null means // "we don't know", never "it's a stranger". export async function classifyDm(wrap, inboxes) { for (const rec of inboxes) { if (!rec || !rec.sk) continue; let sk; try { sk = unhex(rec.sk); } catch { continue; } const opened = await unwrapDM(wrap, sk); if (!opened) continue; const author = opened.author; return { author, mine: author === rec.pubkey, followed: (rec.follows || []).includes(author), muted: (rec.muted || []).includes(author), // Someone you're already talking to is not a stranger, whether or not // you ever followed them. known: (rec.known || []).includes(author), // No contact list published at all: there's nothing to filter against, // and silence would be worse than noise. hasList: !!rec.hasList, name: (rec.names || {})[author] || null, content: opened.rumor && opened.rumor.kind === 14 ? opened.rumor.content : '', }; } return null; } // Should this DM interrupt someone? Our own sent-copy never should — every // NIP-17 message is wrapped to the sender too, and being notified about what // you just typed is pure noise. Anything we couldn't open stays notifiable: // better a generic buzz than a silent drop. export function shouldNotifyDm(verdict) { if (!verdict) return true; if (verdict.mine) return false; if (verdict.muted) return false; // muted in the app: no buzz either if (verdict.followed || verdict.known) return true; return !verdict.hasList; }