diff options
Diffstat (limited to 'src/features')
| -rw-r--r-- | src/features/ark.js | 6 | ||||
| -rw-r--r-- | src/features/messages.js | 10 | ||||
| -rw-r--r-- | src/features/nwc.js | 94 | ||||
| -rw-r--r-- | src/features/zaps.js | 75 |
4 files changed, 153 insertions, 32 deletions
diff --git a/src/features/ark.js b/src/features/ark.js index 13481da..cbfd1b9 100644 --- a/src/features/ark.js +++ b/src/features/ark.js @@ -6,7 +6,7 @@ import * as btc from '@scure/btc-signer'; import { HDKey } from '@scure/bip32'; import { hex, base32nopad, bech32 } from '@scure/base'; import { sha256 } from '@noble/hashes/sha256'; -import { ArkManager, remoteRenewalsInFlight, lnFoldedIds } from '../ark/manager.js'; +import { ArkManager, remoteRenewalsInFlight, lnFoldedIds, backstopMargin } from '../ark/manager.js'; export { remoteRenewalsInFlight }; // Coins this device may offer: spendable, and not held by a renewal another @@ -343,6 +343,8 @@ export function mergeArkStates(a, b) { out.remoteRenewals = mergeRemoteRenewals(a, b); delete out.renewals; // a snapshot's own list, adopted above as remote out.nextKeyIndex = Math.max(a.nextKeyIndex || 1, b.nextKeyIndex || 1); + // standing renewal orders registered on the other side (the worker's, say) + out.scheduled = ArkManager.mergeScheduled(a.scheduled, b.scheduled); out.nextLnRecvIndex = Math.max(a.nextLnRecvIndex || 0, b.nextLnRecvIndex || 0); out.receiveAckTs = Math.max(a.receiveAckTs || 0, b.receiveAckTs || 0); out.serverPubkey = a.serverPubkey || b.serverPubkey || null; @@ -3194,7 +3196,7 @@ export function arkFeature(ctx) { // app that IS open still renews first (and the untouched backstop is // dropped), and far enough from expiry — 36 blocks, six hourly rounds — for // the round to actually run in time. Both are in the free fee bracket. - const backstopWindow = () => (getNetwork() === 'regtest' ? 6 : 36); + const backstopWindow = () => backstopMargin(getNetwork()); let arkAutoRefreshAt = 0; let arkBackstopAt = 0; // Set when the balance is too small to renew itself (total minus round fee diff --git a/src/features/messages.js b/src/features/messages.js index d5da326..20cfaa6 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -12279,7 +12279,15 @@ export function messagesFeature(ctx) { ? h('video', { class: 'mp-media', 'data-src': url, loop: true, playsinline: true, preload: 'none', poster: videoThumbs.get(url) || posterOf(ev, url) || (videoInfo.get(url) || {}).image || serverThumb(url) }) : h('img', { class: 'mp-media', 'data-src': quick, 'data-full': url, alt: '', draggable: 'false', decoding: 'async', - onError: (e) => { const m = e.currentTarget; if ((m.getAttribute('src') || '') !== url) { m.setAttribute('data-src', url); m.setAttribute('src', url); } } }); + onError: (e) => { + const m = e.currentTarget; + if ((m.getAttribute('src') || '') !== url) { m.setAttribute('data-src', url); m.setAttribute('src', url); return; } + // the original is gone too (its host down, the file deleted): say + // so, in place of the browser's broken-picture glyph + let host = ''; try { host = new URL(url).hostname; } catch {} + m.closest('.mp-slide').classList.add('mp-gone'); + m.insertAdjacentElement('afterend', h('div', { class: 'mp-missing' }, h('div', { class: 'mp-missing-ico' }, '🖼'), h('div', {}, t('mediaPicGone')), host ? h('div', { class: 'small muted' }, host) : null)); + } }); const caption = mediaCaption(ev); const stop = (fn) => (e) => { e.stopPropagation(); fn(e); }; const slide = h('div', { class: 'mp-slide', 'data-k': mediaKey(it) }, diff --git a/src/features/nwc.js b/src/features/nwc.js index 9cf8d0b..ec79081 100644 --- a/src/features/nwc.js +++ b/src/features/nwc.js @@ -34,13 +34,19 @@ import { loadBg, saveBg, clearBg } from '../nwc-bg.js'; import { encodeNoffer } from '../noffer.js'; import { maybeBolt11 } from '../ark/lightning.js'; import { withRequestLock } from '../nwc-lock.js'; +import { budgetWindow, budgetRenewsAt, renewalPeriod, spentInWindow, PERIODS } from '../nwc-budget.js'; const REQ_KIND = 23194; const RES_KIND = 23195; const INFO_KIND = 13194; // What we can actually honour. No pay_keysend (Ark can't), no multi_pay. -const METHODS = ['get_info', 'get_balance', 'pay_invoice', 'make_invoice', 'lookup_invoice', 'list_transactions']; +const METHODS = ['get_info', 'get_balance', 'get_budget', 'pay_invoice', 'make_invoice', 'lookup_invoice', 'list_transactions']; + +// A revoked connection keeps answering — with UNAUTHORIZED — for this long, +// so the app on the other end can tell "revoked" from "phone is off". After +// that its key is forgotten everywhere: no subscription, no push, no mirror. +const REVOKE_GRACE_MS = 30 * 86_400_000; // Requests older than this are ignored — a relay replaying history must not // re-trigger payments. @@ -88,10 +94,22 @@ export function nwcFeature(ctx) { // ---- persisted connections ------------------------------------------- // { id, name, secret (client sk hex), clientPk, servicePk, serviceSk, - // maxSat, dailySat, spentToday, spentDate, created, lastUsed, revoked } + // maxSat, dailySat (the budget per period — the field predates periods), + // period (day|week|month), spentToday (spent this window), spentDate (the + // window's key), created, lastUsed, revoked, revokedAt } const load = () => wallet.loadFeatureState('nwc', { conns: [] }); const save = (st) => wallet.saveFeatureState('nwc', st); const conns = () => (load().conns || []).filter((c) => !c.revoked); + // Revoked lately: still listened for, still woken for, answered with a + // refusal. One revoked before revocations were dated gets no grace. + const revokedConns = () => (load().conns || []) + .filter((c) => c.revoked && c.revokedAt && Date.now() - c.revokedAt < REVOKE_GRACE_MS); + // Every service key this device must hear requests for. + const watchPks = () => { + const pks = [...conns(), ...revokedConns()].map((c) => c.servicePk); + if (load().offer) pks.push(load().offer.pk); + return pks; + }; function updateConn(id, patch) { const st = load(); @@ -102,11 +120,11 @@ export function nwcFeature(ctx) { return c; } - // Budget accounting, reset on date change. + // Budget accounting: the counter resets when the window (a UTC day, week + // or month — nwc-budget.js) moves on. function spendRoom(c) { - const today = new Date().toISOString().slice(0, 10); - const spent = c.spentDate === today ? (c.spentToday || 0) : 0; - return { today, spent, left: Math.max(0, (c.dailySat || 0) - spent) }; + const { window: today, spent, left } = spentInWindow(c); + return { today, spent, left }; } function recordSpend(c, sat) { const { today, spent } = spendRoom(c); @@ -130,7 +148,7 @@ export function nwcFeature(ctx) { return `nostr+walletconnect://${c.servicePk}?${rs}&secret=${c.secret}`; } - function createConn({ name, maxSat, dailySat }) { + function createConn({ name, maxSat, dailySat, period }) { const st = load(); st.conns = st.conns || []; // A dedicated service key per connection: revoking one can't affect the @@ -146,6 +164,7 @@ export function nwcFeature(ctx) { clientPk: getPublicKey(clientSk), maxSat: maxSat || 10000, dailySat: dailySat || 50000, + period: PERIODS.includes(period) ? period : 'day', spentToday: 0, spentDate: null, created: Date.now(), @@ -179,6 +198,7 @@ export function nwcFeature(ctx) { by.set(c.id, { ...prev, ...c, revoked: !!(prev.revoked || c.revoked), + revokedAt: [prev.revokedAt, c.revokedAt].filter(Boolean).sort((x, y) => x - y)[0], // keep the highest spend seen for the day so a stale device can't // hand a connection back its budget spentDate: (c.spentDate === prev.spentDate) ? c.spentDate : (c.spentDate || prev.spentDate), @@ -311,11 +331,21 @@ export function nwcFeature(ctx) { // from a stale value on every request (spends never accumulate), and a // connection revoked on another device would keep being served here. const cur = (load().conns || []).find((x) => x.id === c.id); - if (!cur || cur.revoked) return dlog('nwc: guard drop — connection gone or revoked', c.id); + if (!cur) return dlog('nwc: guard drop — connection gone', c.id); c = cur; const scheme = ev.tags?.find((x) => x[0] === 'encryption')?.[1] === 'nip44_v2' ? 'nip44_v2' : 'nip04'; + // Revoked: say so. Silence here reads, from the other app's side, exactly + // like a phone that is off — the one thing a subscription service cannot + // tell apart on its own. The method name is read for the result_type + // when the request opens; nothing in it is acted on. + if (c.revoked) { + let rt = 'error'; + try { rt = JSON.parse(await decrypt(scheme, hex.decode(c.serviceSk), ev.pubkey, ev.content))?.method || rt; } catch {} + lastSeen = { at: Date.now(), method: rt, scheme }; + return reply(c, ev, scheme, { result_type: rt, ...errRes('UNAUTHORIZED', 'this connection was revoked') }); + } let req; try { req = JSON.parse(await decrypt(scheme, hex.decode(c.serviceSk), ev.pubkey, ev.content)); @@ -413,6 +443,14 @@ export function nwcFeature(ctx) { return { result: { balance: (hook('arkSpendableSat') || 0) * 1000 } }; } + if (method === 'get_budget') { + const { spent } = spendRoom(c); + return { result: { + used_budget: spent * 1000, total_budget: (c.dailySat || 0) * 1000, + renews_at: budgetRenewsAt(c.period || 'day'), renewal_period: renewalPeriod(c.period), + } }; + } + if (method === 'pay_invoice') { const invoice = params.invoice; if (!invoice) return errRes('OTHER', 'missing invoice'); @@ -434,7 +472,7 @@ export function nwcFeature(ctx) { return errRes('QUOTA_EXCEEDED', `over the ${c.maxSat} sat per-payment limit`); } if (dec.amountSat > left) { - return errRes('QUOTA_EXCEEDED', `over the remaining daily budget (${left} sat)`); + return errRes('QUOTA_EXCEEDED', `over the remaining ${renewalPeriod(c.period)} budget (${left} sat)`); } let res; try { @@ -624,7 +662,7 @@ export function nwcFeature(ctx) { (ev) => { onOfferRequest(ev).catch((e) => console.warn('nwc: offer handler', e.message)); }, )); } - const list = conns(); + const list = [...conns(), ...revokedConns()]; dlog(`nwc: listen() gen ${gen} — ${list.length} connection(s)`); for (const c of list) { dlog(`nwc: gen ${gen} subscribing for conn=${c.id} service=${c.servicePk.slice(0, 8)}`); @@ -643,7 +681,7 @@ export function nwcFeature(ctx) { // re-runs on every sync snapshot and wake, and relays rate-limit // accepted events per IP — repeated republishing eats the budget the // replies need (and once got this IP temp-banned). - if (!infoPublished.has(c.id)) { + if (!c.revoked && !infoPublished.has(c.id)) { infoPublished.add(c.id); publishInfo(c).catch(() => {}); } @@ -682,8 +720,7 @@ export function nwcFeature(ctx) { async function enableBackground() { const up = upEndpoint(); if (up) { - const pksUp = conns().map((c) => c.servicePk); - if (load().offer) pksUp.push(load().offer.pk); + const pksUp = watchPks(); if (pksUp.length) { const r = await fetch(`${NOTIFIER}/register`, { method: 'POST', headers: { 'content-type': 'application/json' }, @@ -716,8 +753,7 @@ export function nwcFeature(ctx) { throw e; } { const st2 = load(); if (st2.pushUnavailable) { delete st2.pushUnavailable; save(st2); } } - const pks1 = conns().map((c) => c.servicePk); - if (load().offer) pks1.push(load().offer.pk); + const pks1 = watchPks(); // Arming can precede the first connection (creation requires it) — the // notifier rejects an empty watch list, so defer that POST to the // refreshRegistration() the creation triggers moments later. @@ -792,8 +828,7 @@ export function nwcFeature(ctx) { clearTimeout(regTimer); regTimer = setTimeout(async () => { try { - const pks = conns().map((c) => c.servicePk); - if (load().offer) pks.push(load().offer.pk); + const pks = watchPks(); if (!pks.length) return; const up2 = upEndpoint(); const sub = up2 ? { endpoint: up2, unifiedpush: true } @@ -835,7 +870,7 @@ export function nwcFeature(ctx) { bgTimer = setTimeout(async () => { try { if (!hook('arkBgReady')) return; - await hook('arkBgWrite', conns(), load().offer || null, + await hook('arkBgWrite', [...conns(), ...revokedConns()], load().offer || null, { paySent: load().paySentNotify !== false }); } catch (e) { console.warn('nwc: could not write background state', e.message); } }, 1500); @@ -888,7 +923,7 @@ export function nwcFeature(ctx) { // No connections means nothing here could have been asked of us: end the // job now rather than hold a WebView open for half a minute on the // strength of a payload we can't act on. - if (!conns().length) { finish(); return; } + if (!conns().length && !revokedConns().length) { finish(); return; } listen(); // the request is on a relay; this is what hears it reconcileBg(); // and make sure the pouch behind it is current // an answer published is the signal we were woken for @@ -921,6 +956,10 @@ export function nwcFeature(ctx) { // ---- UI --------------------------------------------------------------- + const periodKey = (p) => (p === 'month' ? 'nwcMonth' : p === 'week' ? 'nwcWeek' : 'nwcDay'); + const periodEvery = (p) => (p === 'month' ? 'nwcPerMonth' : p === 'week' ? 'nwcPerWeek' : 'nwcPerDay'); + const spentKey = (p) => (p === 'month' ? 'nwcSpentMonth' : p === 'week' ? 'nwcSpentWeek' : 'nwcSpentDay'); + function nwcCard() { if (!hook('arkReady')) return null; const list = conns(); @@ -943,14 +982,15 @@ export function nwcFeature(ctx) { h('div', { class: 'row between' }, h('span', {}, c.name), h('span', { class: 'linklike small', onClick: () => { - updateConn(c.id, { revoked: true }); listen(); - refreshRegistration(); // stop waking this device for a dead key + updateConn(c.id, { revoked: true, revokedAt: Date.now() }); listen(); + refreshRegistration(); // keep hearing it for a while, to refuse it + writeBg(); // the worker refuses it too, from now try { wallet.saveCache(); } catch {} // propagate the revocation render(); toast(t('nwcRevoked', { name: c.name })); } }, t('nwcRevoke'))), h('div', { class: 'small faint' }, - t('nwcLimits', { max: fmtAmount(c.maxSat), day: fmtAmount(c.dailySat), spent: fmtAmount(spent) })), + t('nwcLimitsPer', { max: fmtAmount(c.maxSat), budget: fmtAmount(c.dailySat), per: t(periodKey(c.period)), spent: fmtAmount(spent), spentWhen: t(spentKey(c.period)) })), ui.nwcShow === c.id ? h('div', { class: 'col', style: 'gap:6px;align-items:center' }, h('div', { html: qrSvg(uriFor(c)) }), @@ -992,9 +1032,13 @@ export function nwcFeature(ctx) { h('label', { class: 'field' }, h('span', { class: 'lab' }, t('nwcMaxPayment')), h('input', { type: 'number', min: '1', value: st.maxSat, onInput: (e) => { st.maxSat = e.target.value; } })), - h('label', { class: 'field' }, h('span', { class: 'lab' }, t('nwcDailyBudget')), + h('label', { class: 'field' }, h('span', { class: 'lab' }, t('nwcBudget')), h('input', { type: 'number', min: '1', value: st.dailySat, onInput: (e) => { st.dailySat = e.target.value; } })), + h('label', { class: 'field' }, h('span', { class: 'lab' }, t('nwcPeriod')), + h('select', { class: 'nwc-period', value: st.period || 'day', onChange: (e) => { st.period = e.target.value; } }, + ...PERIODS.map((p) => h('option', { value: p, selected: (st.period || 'day') === p ? 'selected' : undefined }, t(periodEvery(p)))))), + h('div', { class: 'small faint' }, t('nwcPeriodHint')), (typeof Notification === 'undefined' || Notification.permission !== 'granted') ? h('div', { class: 'small faint' }, t('nwcNotifHint')) : null, @@ -1007,12 +1051,12 @@ export function nwcFeature(ctx) { catch (e) { toast(e.message); return; } const c = createConn({ name: st.name, maxSat: parseInt(st.maxSat, 10) || 10000, - dailySat: parseInt(st.dailySat, 10) || 50000, + dailySat: parseInt(st.dailySat, 10) || 50000, period: st.period || 'day', }); ui.nwcNew = null; ui.nwcShow = c.id; render(); } }, t('nwcCreate')))) : h('button', { class: 'btn-ghost btn-block', onClick: () => { - ui.nwcNew = { name: '', maxSat: '10000', dailySat: '50000' }; render(); + ui.nwcNew = { name: '', maxSat: '10000', dailySat: '50000', period: 'day' }; render(); } }, t('nwcAdd'))); } diff --git a/src/features/zaps.js b/src/features/zaps.js index f29fe83..d364738 100644 --- a/src/features/zaps.js +++ b/src/features/zaps.js @@ -13,7 +13,7 @@ import { t } from '../i18n.js'; import { npubOf } from '../nostr.js'; -import { parseZapTarget, zapTargetFromProfile, fetchPayParams, buildZapRequest, requestInvoice, parseLnurlAuth, lnurlAuthKey, lnurlAuthLogin } from '../lnurl.js'; +import { parseZapTarget, zapTargetFromProfile, fetchPayParams, buildZapRequest, requestInvoice, parseLnurlAuth, lnurlAuthKey, lnurlAuthLogin, submitWithdraw } from '../lnurl.js'; import { HDKey } from '@scure/bip32'; import { mnemonicToSeedSync } from '@scure/bip39'; import { decodeNoffer } from '../noffer.js'; @@ -136,7 +136,13 @@ export function zapsFeature(ctx) { z.address = lnTarget.address || z.address; } - const params = await fetchPayParams(target.url); + let params; + try { params = await fetchPayParams(target.url); } + catch (e) { + // not a payment after all: the site wants to pay US (LUD-03) + if (e && e.withdraw) { if (ui.zap === z) beginWithdraw(e.withdraw, z); return; } + throw e; + } if (ui.zap !== z) return; // user navigated away // Name the payee like a human: LNURL metadata usually carries the // lightning address (text/identifier) — show that instead of a bech32 @@ -350,6 +356,67 @@ export function zapsFeature(ctx) { h('button', { class: 'btn-primary btn-block', onClick: () => doLogin(a) }, a.status === 'error' ? t('lnAuthRetry') : t(action === 'register' ? 'lnAuthGoRegister' : 'lnAuthGo')), h('button', { class: 'btn-ghost btn-block', onClick: back }, t('back'))); } + // ---- Lightning withdraw (LNURL-withdraw) ---- + // A site's withdraw lnurl: they will pay an invoice of ours, within their + // range. Ask the amount (their max to start; fixed when min = max), make + // the invoice over Ark, hand it over, and watch for the money. + function beginWithdraw(w, z) { + const maxSat = Math.floor(w.maxMsat / 1000), minSat = Math.ceil(w.minMsat / 1000); + ui.zap = null; ui.sendError = ''; + ui.lnWithdraw = { w, minSat, maxSat, fixed: minSat >= maxSat, amount: ctx.amountField(maxSat), status: 'ask', address: z && z.address }; + render(); + } + async function doWithdraw(d) { + const sats = d.fixed ? d.maxSat : (parseAmount(d.amount, getUnit()) || 0); + if (!(sats >= Math.max(1, d.minSat) && sats <= d.maxSat)) { d.error = t('lnWithdrawRange', { min: fmtAmount(d.minSat), max: fmtAmount(d.maxSat), unit: unitLabel() }); render(); return; } + if (wallet.watchOnly) { d.error = t('lnWithdrawWatchOnly'); render(); return; } + d.sats = sats; d.status = 'busy'; d.error = ''; render(); + try { + const inv = await hook('arkLnInvoice', sats, (d.w.description || t('lnWithdrawMemo', { domain: d.w.domain })).slice(0, 120)); + if (!inv || !inv.invoice) throw new Error(t('lnWithdrawNoInvoice')); + if (ui.lnWithdraw !== d) { hook('arkLnCancel', inv.id); return; } + await submitWithdraw(d.w, inv.invoice); + if (ui.lnWithdraw !== d) return; + d.status = 'sent'; d.lnId = inv.id; + hook('arkLnWatch', inv.id, (a) => { if (ui.lnWithdraw !== d) return; d.status = a && a.step === 'done' ? 'paid' : 'error'; if (d.status === 'error') d.error = t('lnWithdrawNotPaid'); render(); }); + } catch (e) { + if (ui.lnWithdraw !== d) return; + d.status = 'error'; d.error = e.message || String(e); + } + render(); + } + function lnWithdrawView() { + const d = ui.lnWithdraw; + if (!d) return null; + const domain = d.w.domain; + const back = () => { if (d.lnId && d.status !== 'paid') hook('arkLnUnwatch', d.lnId); ui.lnWithdraw = null; ui.sendError = ''; ui.send = blankSend(); render(); }; + const heading = '⚡ ' + t('lnWithdrawTitle'); + if (d.status === 'busy') { + return h('div', { class: 'card col', style: 'align-items:center;gap:14px;padding:32px 14px' }, + h('span', { class: 'spinner' }), h('p', { class: 'muted', style: 'margin:0' }, t('lnWithdrawAsking', { domain }))); + } + if (d.status === 'sent' || d.status === 'paid') { + const paid = d.status === 'paid'; + return h('div', { class: 'card col', style: 'align-items:center;text-align:center;gap:14px;padding:32px 14px' }, + paid ? h('div', { class: 'check-badge' }, '✓') : h('span', { class: 'spinner' }), + h('h3', { style: 'margin:0' }, paid ? t('lnWithdrawPaid', { amount: fmtAmount(d.sats) + ' ' + unitLabel() }) : t('lnWithdrawSent', { amount: fmtAmount(d.sats) + ' ' + unitLabel(), domain })), + paid ? null : h('p', { class: 'small muted', style: 'margin:0' }, t('lnWithdrawSentHint')), + h('button', { class: paid ? 'btn-primary btn-block' : 'btn-ghost btn-block', onClick: back }, paid ? t('done') : t('back'))); + } + return h('div', { class: 'card col', style: 'gap:12px' }, + h('h3', {}, heading), + h('div', { class: 'small', style: 'font-size:18px;font-weight:600;word-break:break-all' }, domain), + d.w.description ? h('p', { class: 'small muted', style: 'margin:0' }, d.w.description) : null, + h('p', { class: 'small muted', style: 'margin:0' }, d.fixed ? t('lnWithdrawFixed', { amount: fmtAmount(d.maxSat) + ' ' + unitLabel(), domain }) + : t('lnWithdrawOffer', { min: fmtAmount(d.minSat), max: fmtAmount(d.maxSat), unit: unitLabel(), domain })), + d.fixed ? null : h('div', { class: 'row gap6', style: 'align-items:center' }, + h('input', { type: 'number', min: '0', inputmode: 'decimal', placeholder: t('lnPayAmount'), value: d.amount, onInput: (e) => { d.amount = e.target.value; d.error = ''; render(); } }), + unitTag(), + h('button', { type: 'button', onClick: () => { d.amount = ctx.amountField(d.maxSat); d.error = ''; render(); } }, t('max'))), + d.error ? h('div', { class: 'notice err' }, d.error) : null, + h('button', { class: 'btn-primary btn-block', onClick: () => doWithdraw(d) }, d.status === 'error' ? t('lnAuthRetry') : t('lnWithdrawGo')), + h('button', { class: 'btn-ghost btn-block', onClick: back }, t('back'))); + } function zapView() { const z = ui.zap; if (!z) return null; @@ -535,8 +602,8 @@ export function zapsFeature(ctx) { begin({ kind: 'npub', pk, eventId: eventId || null }, shortNpub(npub || npubOf(pk))); return true; }, - resetSend() { ui.zap = null; ui.lnAuth = null; }, - sendView() { return lnAuthView() || zapView(); }, + resetSend() { ui.zap = null; ui.lnAuth = null; ui.lnWithdraw = null; }, + sendView() { return lnAuthView() || lnWithdrawView() || zapView(); }, // Settings → Nostr: the one-tap zap amount. nostrSettingsCards() { const cur = ctx.zapDefaultSat ? ctx.zapDefaultSat() : 0; |
