diff options
| author | Adam Soltys <[email protected]> | 2026-10-16 12:32:28 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-10-16 12:32:28 -0700 |
| commit | 294a49598e43e3e6f9e34f0246bbea41837359f9 (patch) | |
| tree | 0fe376316626a9b27330ecbba15740d14ec4c825 | |
| parent | 38ce0b441505d0bdd048d38c82ac95afe4d3b407 (diff) | |
| download | coinosv3-294a49598e43e3e6f9e34f0246bbea41837359f9.tar.gz coinosv3-294a49598e43e3e6f9e34f0246bbea41837359f9.zip | |
NWC: budgets reset by the day, week or month; a revoked connection says so; a closed wallet keeps its coins renewed. Three asks from a subscription service builder (PullCap, by DM, 2026-10-16) testing a 1-sat-an-hour pull against a locked phone. (1) "For a monthly subscription a monthly cap would be tighter": a connection's budget now resets every day, week (Monday) or month, in UTC (nwc-budget.js: the window key stamps the spent counter; both the app and the worker count by it), chosen on the form, read on the card ("21,000 a month · 0 spent this month"); the worker now also counts what the APP spent this window (the counter rides the mirror) — it only ever counted its own log before, so a daily budget could be exceeded across the two; get_budget answers used/total/renews_at/renewal_period (NIP-47), in get_info's method list and the 13194 event. (2) "Does V3 reply with an NWC error when a connection is revoked, or just stop answering?" — it stopped: the open app dropped the request, the mirror forgot the key, the device even de-registered it from the push notifier, so a revocation looked exactly like a phone that is off. Now a revoked connection is kept for 30 days (revokedAt; the earlier date wins in a merge): still subscribed, still registered for pushes, still in the mirror flagged, and every request on it — from the app or the worker, in the asker's scheme — is answered UNAUTHORIZED "this connection was revoked"; no capability event for it; after the grace it is forgotten. (3) "If a user is only woken once a month by an NWC request, will V3 renew the coins on its own?" — only for one cycle: the app registers a standing order per coin, but a coin the worker SPENDS voids its order and the change had none until the app next opened, and a renewed coin sat unclaimed until then too. Now every NWC wake, after the answer and inside what is left of the push budget (tendRenewals, sw-nwc.js): claim orders whose round has run — and drive a claim left in flight on, since one takes several round trips and confirmations — then register an order for every coin without one (backstopMargin shared with the app; limited to the output keys the mirror carries; the mirror now also carries the output key a standing order or a claim in flight burned, which was below the window). Standing orders merge by unlock hash when the app returns (mergeScheduled, in mergeArkStates), so it adopts the worker's. tools/ark/bg-renewal-test.js on regtest, end to end: the worker registers from the mirror alone, a worker spend kills the order and the next wake covers the change, the round runs with nobody online and the next wake claims the renewed coin — and covers it in the same wake — then the app merges it all (fresh coin, right balance, the order adopted, not busy, one history row). tools/nwc-budget-test.js (windows, renews_at, counting with the worker's unabsorbed spends); nwc-sw-test.js (monthly budget over app+worker spends, last month's not counted, get_budget, UNAUTHORIZED in both schemes, the mirror's keys and flags, tending: claim/drive/register and their limits); nwc-test.js (monthly refusal naming the period, get_budget, a counter from last month reads as nothing, the revoked connection answered UNAUTHORIZED, no 13194, revokedAt in the snapshot, forgotten after 31 days, the earlier date wins); nwc-settings-ui-test.js (the form's period choice, the card's wording, Revoke dates it); ark-renewal-sync, sync-blob, sync-outbox and spending-restore tests pass.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J1Kon8bxJoHRpJdSzshCkp
| -rw-r--r-- | src/ark/manager.js | 14 | ||||
| -rw-r--r-- | src/features/ark.js | 6 | ||||
| -rw-r--r-- | src/features/nwc.js | 94 | ||||
| -rw-r--r-- | src/i18n.js | 13 | ||||
| -rw-r--r-- | src/nwc-bg.js | 12 | ||||
| -rw-r--r-- | src/nwc-budget.js | 54 | ||||
| -rw-r--r-- | src/nwc-respond.js | 85 | ||||
| -rw-r--r-- | src/sw-nwc.js | 11 | ||||
| -rw-r--r-- | tools/ark/bg-renewal-test.js | 135 | ||||
| -rw-r--r-- | tools/nwc-budget-test.js | 52 | ||||
| -rw-r--r-- | tools/nwc-settings-ui-test.js | 80 | ||||
| -rw-r--r-- | tools/nwc-sw-test.js | 131 | ||||
| -rw-r--r-- | tools/nwc-test.js | 66 |
13 files changed, 710 insertions, 43 deletions
diff --git a/src/ark/manager.js b/src/ark/manager.js index 703d341..d5ae2b0 100644 --- a/src/ark/manager.js +++ b/src/ark/manager.js @@ -171,6 +171,12 @@ export function pruneArkState(state, now = Date.now()) { return state; } +// How close to expiry the server-side backstop renewal is aimed: well inside +// the free fee bracket (under 96 blocks of life left on our ASPs), and far +// enough out — 36 blocks, six hourly rounds — for the round to run in time. +// Shared by the app (features/ark.js) and the worker tending a closed wallet. +export const backstopMargin = (network) => (network === 'regtest' ? 6 : 36); + export class ArkManager { constructor({ account, storage, arkUrl, esploraUrl, network = 'regtest', onUpdate, lnQuoteUrl, statusHint }) { this.account = account; // HDKey node; ark keys derived beneath it @@ -2419,6 +2425,14 @@ export class ArkManager { scheduledRefreshes() { return (this.state.scheduled || []).slice(); } + // Union of two devices' standing orders (the app's and the worker's, or + // two devices'), keyed by unlock hash; dead ones are dropped on the next + // _driveScheduled, so an order for a coin the other side spent is harmless. + static mergeScheduled(a = [], b = []) { + const seen = new Set(a.map((s) => s.unlockHash)); + return [...a, ...b.filter((s) => s.unlockHash && !seen.has(s.unlockHash))]; + } + // Keep every coin covered by a standing order, `marginBlocks` before its // expiry. Coins arrive, get spent, get renewed — each new one needs its own // backstop while it still has the lifetime to register one. Caller owns the 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/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/i18n.js b/src/i18n.js index 2b33a47..cdbcfeb 100644 --- a/src/i18n.js +++ b/src/i18n.js @@ -1444,6 +1444,19 @@ const STR = { nwcRevoke: 'Revoke', nwcRevoked: 'Revoked {name}', nwcLimits: 'Max {max}/payment · {day}/day · {spent} spent today', + nwcLimitsPer: 'Max {max}/payment · {budget} a {per} · {spent} {spentWhen}', + nwcSpentDay: 'spent today', + nwcSpentWeek: 'spent this week', + nwcSpentMonth: 'spent this month', + nwcBudget: 'Budget (sats)', + nwcPeriod: 'Budget resets', + nwcPerDay: 'Every day', + nwcPerWeek: 'Every week', + nwcPerMonth: 'Every month', + nwcDay: 'day', + nwcWeek: 'week', + nwcMonth: 'month', + nwcPeriodHint: 'Resets at midnight UTC: at the start of the day, the week (Monday) or the month.', arkLnFundsPending: 'Your money is settling from a previous payment. Retrying…', lnZapOffer: 'Zap {addr}', arkLnInvoiceIntro: 'Or take a Lightning payment, straight into Spending.', diff --git a/src/nwc-bg.js b/src/nwc-bg.js index 92786c0..3bdef08 100644 --- a/src/nwc-bg.js +++ b/src/nwc-bg.js @@ -88,6 +88,11 @@ export function buildBg({ ark, mgrState, keyFor, connections, offer, autowithdra const keys = {}; const idx = new Set((mgrState.vtxos || []).filter((v) => v.state !== 'spent').map((v) => v.keyIndex)); for (let i = 0; i < BG_KEY_LOOKAHEAD; i++) idx.add((mgrState.nextKeyIndex || 1) + i); + // A standing renewal order (and a renewal in flight) burned its output key + // when it was registered, below the counter by now: the worker needs that + // key to claim the renewed coin while the app is closed. + for (const e of mgrState.scheduled || []) if (e.outKeyIndex != null) idx.add(e.outKeyIndex); + for (const a of mgrState.actions || []) if (a.type === 'refresh' && a.step !== 'done' && a.outKeyIndex != null) idx.add(a.outKeyIndex); idx.add(0); // the receive-address key: mailbox/refund defaults land on it for (const i of idx) keys[String(i)] = keyFor(3, i); const keys5 = {}; @@ -107,9 +112,14 @@ export function buildBg({ ark, mgrState, keyFor, connections, offer, autowithdra // { on, threshold, keep, target: { kind, address, url?, spkHex? } } — the // destination is resolved by the app, so the worker never needs a relay autowithdraw: autowithdraw || null, + // The budget's spent counter rides along (stamped with its window) so the + // worker counts what the app spent; a revoked one rides along flagged, to + // be refused rather than ignored. connections: (connections || []).map((c) => ({ id: c.id, servicePk: c.servicePk, serviceSk: c.serviceSk, clientPk: c.clientPk, - maxSat: c.maxSat, dailySat: c.dailySat, + maxSat: c.maxSat, dailySat: c.dailySat, period: c.period || 'day', + spentDate: c.spentDate || null, spentToday: c.spentToday || 0, + revoked: !!c.revoked, })), }; } diff --git a/src/nwc-budget.js b/src/nwc-budget.js new file mode 100644 index 0000000..a16e068 --- /dev/null +++ b/src/nwc-budget.js @@ -0,0 +1,54 @@ +// An NWC connection's spending budget resets on a calendar boundary — a day, +// a week or a month — in UTC, so every device of a wallet (and the service +// worker answering while the app is closed) agrees on which window a spend +// fell in without a timezone in the picture. The window key is what the +// connection's spent counter is stamped with: a counter stamped with another +// key is from a window that has passed. + +export const PERIODS = ['day', 'week', 'month']; + +const pad = (n) => String(n).padStart(2, '0'); + +// The week runs Monday to Sunday (ISO), keyed by its Monday. +function mondayOf(d) { + const m = new Date(d); + const dow = (m.getUTCDay() + 6) % 7; // Monday = 0 + m.setUTCDate(m.getUTCDate() - dow); + m.setUTCHours(0, 0, 0, 0); + return m; +} + +export function budgetWindow(period, ts = Date.now()) { + const d = new Date(ts); + if (period === 'month') return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}`; + if (period === 'week') { const m = mondayOf(d); return `W${m.getUTCFullYear()}-${pad(m.getUTCMonth() + 1)}-${pad(m.getUTCDate())}`; } + return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`; +} + +// When the current window ends, in unix seconds (NIP-47's renews_at). +export function budgetRenewsAt(period, ts = Date.now()) { + const d = new Date(ts); + let end; + if (period === 'month') end = Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1); + else if (period === 'week') { const m = mondayOf(d); end = m.getTime() + 7 * 86_400_000; } + else end = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + 1); + return Math.floor(end / 1000); +} + +// NIP-47 names the period as an adverb. +export const renewalPeriod = (period) => (period === 'month' ? 'monthly' : period === 'week' ? 'weekly' : 'daily'); + +// What a connection has spent in the window that is on now: the counter +// carried on the connection (stamped with its window) plus, for the worker, +// its own spends the app has not yet folded into that counter. +export function spentInWindow(conn, extraSpends = [], ts = Date.now()) { + const period = conn.period || 'day'; + const win = budgetWindow(period, ts); + let spent = conn.spentDate === win ? (conn.spentToday || 0) : 0; + for (const s of extraSpends) { + if (s.absorbed || s.connId !== conn.id) continue; + if (budgetWindow(period, s.ts) !== win) continue; + spent += (s.amountSat || 0) + (s.feeSat || 0); + } + return { window: win, period, spent, left: Math.max(0, (conn.dailySat || 0) - spent) }; +} diff --git a/src/nwc-respond.js b/src/nwc-respond.js index 27699e7..ec19923 100644 --- a/src/nwc-respond.js +++ b/src/nwc-respond.js @@ -20,6 +20,8 @@ import { finalizeEvent } from 'nostr-tools/pure'; import { ArkManager } from './ark/manager.js'; import { maybeBolt11 } from './ark/lightning.js'; import { allBgs, saveBg } from './nwc-bg.js'; +import { budgetRenewsAt, renewalPeriod, spentInWindow } from './nwc-budget.js'; +import { backstopMargin } from './ark/manager.js'; const MAX_AGE_SEC = 120; const PAY_WAIT_MS = 20_000; // inside the SW's ~30s budget, with reply margin @@ -160,11 +162,6 @@ export async function respondFromBg(data, { if (ev.pubkey !== conn.clientPk) return false; const scheme = ev.tags?.find((x) => x[0] === 'encryption')?.[1] === 'nip44_v2' ? 'nip44_v2' : 'nip04'; - let req; - try { req = JSON.parse(await decrypt(scheme, conn.serviceSk, ev.pubkey, ev.content)); } catch { return false; } - const method = req?.method; - const params = req?.params || {}; - const publish = async (payload) => { const evt = await buildReply(conn, ev, scheme, payload); const r = await fetchFn(`${notifier}/publish`, { @@ -174,6 +171,17 @@ export async function respondFromBg(data, { if (!r.ok) throw new Error(`publish refused: ${r.status}`); return true; }; + let req; + try { req = JSON.parse(await decrypt(scheme, conn.serviceSk, ev.pubkey, ev.content)); } catch { return false; } + const method = req?.method; + const params = req?.params || {}; + // Revoked, lately: refuse out loud — a silent worker looks like a phone + // that is off, which is the one thing the other app cannot tell apart. + if (conn.revoked) { + await publish(errRes(method || 'error', 'UNAUTHORIZED', 'this connection was revoked')); + log('refused a request on a revoked connection'); + return true; + } // Another device (an open tab elsewhere) may have answered already — a // paid zap must never be shouted over with a late error, and paying twice // wastes funds-in-flight. The notifier tracks recent reply e-tags. @@ -204,7 +212,7 @@ export async function respondFromBg(data, { alias: 'Coinos', color: '#15171a', network: rec.ark.network === 'mainnet' ? 'mainnet' : rec.ark.network, block_height: 0, block_hash: '', - methods: ['get_info', 'get_balance', 'pay_invoice', 'make_invoice', 'lookup_invoice', 'list_transactions'], + methods: ['get_info', 'get_balance', 'get_budget', 'pay_invoice', 'make_invoice', 'lookup_invoice', 'list_transactions'], }, }); return true; @@ -265,6 +273,14 @@ export async function respondFromBg(data, { await publish({ result_type: 'get_balance', result: { balance: spendableSat(rec) * 1000 } }); return true; } + if (method === 'get_budget') { + const { spent } = spentInWindow(conn, rec.spends || []); + await publish({ result_type: 'get_budget', result: { + used_budget: spent * 1000, total_budget: (conn.dailySat || 0) * 1000, + renews_at: budgetRenewsAt(conn.period || 'day'), renewal_period: renewalPeriod(conn.period), + } }); + return true; + } if (method === 'list_transactions') { // the mirrored wallet's Lightning history, both ways, as the open app reports it const txs = ((rec.mgr && rec.mgr.movements) || []) @@ -309,12 +325,11 @@ export async function respondFromBg(data, { await publish(errRes('pay_invoice', 'QUOTA_EXCEEDED', `over the ${conn.maxSat} sat per-payment limit`)); return true; } - const today = new Date().toISOString().slice(0, 10); - const spentToday = (rec.spends || []) - .filter((s) => s.connId === conn.id && new Date(s.ts).toISOString().slice(0, 10) === today) - .reduce((n, s) => n + (s.amountSat || 0) + (s.feeSat || 0), 0); - if (spentToday + dec.amountSat > conn.dailySat) { - await publish(errRes('pay_invoice', 'QUOTA_EXCEEDED', `over the remaining daily budget (${Math.max(0, conn.dailySat - spentToday)} sat)`)); + // What the app spent this window rides on the mirrored connection; the + // worker's own spends the app has not yet folded in are counted from its log. + const { left } = spentInWindow(conn, rec.spends || []); + if (dec.amountSat > left) { + await publish(errRes('pay_invoice', 'QUOTA_EXCEEDED', `over the remaining ${renewalPeriod(conn.period)} budget (${left} sat)`)); return true; } if (spendableSat(rec) < dec.amountSat) return false; // stale/empty mirror: wake the user @@ -411,3 +426,49 @@ export async function respondFromBg(data, { }, }; } + +// Renewals while the app is closed. The app registers a standing order with +// the ASP for every coin (a round it runs on its own, margin blocks before +// expiry) — but a coin spent by this worker voids its order, and the change +// left behind has none until the app next opens. A wallet only ever woken by +// NWC requests would lose cover one spend after its last open. So each wake +// tends the mirror's coins the way the app does: claim any order whose round +// has run (the output waits 'unclaimed' until someone forfeits the inputs), +// and register an order for every coin without one. Both need only what the +// mirror carries — the coins' keys and a window of upcoming indices. +// Bounded: the push handler has a budget, and anything left over waits for +// the next wake or the app. +export async function tendRenewals({ recordsFn = allBgs, saveFn = saveBg, log = () => {}, deadline = Date.now() + 8000, margin = null } = {}) { + let n = 0; + for (const { walletKey, rec } of await recordsFn()) { + if (!rec || rec.v < 3 || !rec.mgr || !rec.ark || !rec.key4) continue; + if (Date.now() > deadline - 1500) break; + const timeLeft = () => Math.max(0, deadline - Date.now()); + const bounded = (p) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error('out of time')), timeLeft()))]); + try { + const mgr = await bounded(bgManager(rec, walletKey, saveFn)); + await bounded(mgr._tipMemo()); + // orders whose round has run: claim them (the output becomes spendable + // here, and merges into the app's state on its next open). A claim is + // several round trips — the funding tx must confirm, then leaf cosign, + // forfeit, adopt — so one that ran out of time (or confirmations) last + // wake sits as a refresh action in flight: drive it on, every wake. + await bounded(mgr._driveScheduled()).catch((e) => log('renewal claim: ' + e.message)); + for (const a of mgr.state.actions || []) { + if (a.type !== 'refresh' || ['done', 'failed'].includes(a.step)) continue; + await bounded(mgr._driveRefresh(a)).catch((e) => log('renewal claim: ' + e.message)); + if (a.step === 'done') { n++; log('claimed a renewal while closed'); } + } + // coins without an order: register one, as long as the output key the + // order burns is inside the mirrored window (the worker can't derive) + let room = 0; + while (rec.keys[String((mgr.state.nextKeyIndex || 1) + room)] && room < 4) room++; + if (room) { + const got = await bounded(mgr.ensureScheduledRefreshes(margin ?? backstopMargin(rec.ark.network), room)).catch((e) => { log('renewal order: ' + e.message); return 0; }); + if (got) { n += got; log(`registered ${got} renewal order(s) while closed`); } + } + await saveFn(walletKey, rec); + } catch (e) { log('renewals: ' + e.message); } + } + return n; +} diff --git a/src/sw-nwc.js b/src/sw-nwc.js index ddcdbb5..3dac246 100644 --- a/src/sw-nwc.js +++ b/src/sw-nwc.js @@ -4,7 +4,7 @@ // nwc-respond.js), and only falls back to the wake-the-user notification // when it can't. -import { respondFromBg } from './nwc-respond.js'; +import { respondFromBg, tendRenewals } from './nwc-respond.js'; import { withRequestLock } from './nwc-lock.js'; import { bgAutoWithdraw } from './bg-autowithdraw.js'; import { allInboxes, classifyDm, shouldNotifyDm } from './dm-inbox.js'; @@ -70,6 +70,7 @@ self.addEventListener('push', (e) => { return; } if (data.type !== 'nwc') return; + const startedAt = Date.now(); e.waitUntil((async () => { // An open window handles requests itself with full wallet state — nudge // it and stay out of the way. @@ -78,6 +79,11 @@ self.addEventListener('push', (e) => { for (const c of clients) c.postMessage({ type: 'nwc-wake', servicePubkey: data.servicePubkey }); return; } + // A wake is the only moment a closed wallet gets to look after its coins: + // claim renewals whose round has run, cover coins without one. After the + // answer, inside what is left of the push budget. + const tend = () => tendRenewals({ deadline: startedAt + 27_000, log: (m) => console.log('[sw-renew]', m) }) + .catch((err) => console.warn('[sw-renew] failed:', err && err.message)); // an NWC wake-up may also have moved money in; check the rule after setTimeout(() => { bgAutoWithdraw({ log: (m) => console.log('[sw-aw]', m) }).catch(() => {}); }, 0); let handled = false; @@ -97,9 +103,10 @@ self.addEventListener('push', (e) => { tag: handled.notify.tag || 'nwc-incoming', renotify: true, data: { url: './' }, }); + await tend(); return; } - if (handled) return; + if (handled) { await tend(); return; } // A kind-21001 offer request is money coming IN (someone asking us to // mint an invoice) — "an app wants to pay" would read as the opposite. const incoming = data.event && data.event.kind === 21001; diff --git a/tools/ark/bg-renewal-test.js b/tools/ark/bg-renewal-test.js new file mode 100644 index 0000000..0a85816 --- /dev/null +++ b/tools/ark/bg-renewal-test.js @@ -0,0 +1,135 @@ +// The service worker tends a closed wallet's renewals, on regtest, end to end: +// +// the app receives a coin and writes the background mirror -> "closes" -> +// the worker (tendRenewals over the mirror, keys from the mirror alone) +// registers a standing order for the coin -> the worker SPENDS from the +// mirror (an NWC pay) which voids that order; the next wake covers the +// change coin -> the scheduled height passes, the server runs the round +// with nobody online -> the next wake claims the renewed coin into the +// mirror -> the app returns and merges the worker's state: fresh coin, +// old one spent, the order gone. +// +// Usage: bun tools/ark/bg-renewal-test.js +// Needs the ark-regtest stack (bc, ark-electrs, captaind on :3535). + +import { execSync } from 'node:child_process'; +import { hex } from '@scure/base'; +import { generateMnemonic, mnemonicToSeedSync } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; +import { HDKey } from '@scure/bip32'; + +import { ArkManager } from '../../src/ark/manager.js'; +import { buildBg } from '../../src/nwc-bg.js'; +import { tendRenewals, bgManager } from '../../src/nwc-respond.js'; +import { mergeArkStates } from '../../src/features/ark.js'; +import { ALICE, aliceReady } from './alice.js'; + +const ARK = process.env.ARK_URL || 'http://127.0.0.1:3535'; +const ESPLORA = process.env.ESPLORA_URL || 'http://127.0.0.1:30002'; +const BCLI = `docker exec bc bitcoin-cli -rpcwallet=coinos`; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const sh = (cmd) => execSync(cmd, { shell: '/bin/bash' }).toString().trim(); +const mine = (n = 1) => sh(`${BCLI} generatetoaddress ${n} $(${BCLI} getnewaddress) >/dev/null`); +const tipHeight = () => Number(sh(`${BCLI} getblockcount`)); + +let ok = true; +const check = (name, cond, detail = '') => { + console.log(` ${cond ? '✓' : '✗'} ${name}${detail ? ' — ' + detail : ''}`); + if (!cond) ok = false; +}; + +// --- the app's wallet --- +const store = { raw: null }; +const storage = { load: () => (store.raw ? JSON.parse(store.raw) : null), save: (s) => { store.raw = JSON.stringify(s); } }; +const mnemonic = generateMnemonic(wordlist); +const account = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic)).derive("m/86'/0'/9'"); +const app = await new ArkManager({ account, storage, arkUrl: ARK, esploraUrl: ESPLORA }).init(); +await aliceReady(); + +const receive = async (sat) => { + const before = app.balance().spendableSat; + sh(`${ALICE} -q send ${app.address()} "${sat} sat"`); + for (let i = 0; i < 15 && app.balance().spendableSat < before + sat; i++) { await app.sync(); await sleep(1000); } + return app.balance().spendableSat - before; +}; + +// --- the mirror the worker answers from (what writeBgMirror writes) --- +let rec = null; +const writeMirror = () => { + rec = buildBg({ + ark: { arkUrl: ARK, esploraUrl: ESPLORA, network: 'regtest', serverPubkey: app.info.serverPubkey }, + mgrState: JSON.parse(JSON.stringify(app.state)), + keyFor: (chain, i) => hex.encode(account.deriveChild(chain).deriveChild(i).privateKey), + connections: [], + }); +}; +const recs = async () => [{ walletKey: 'w1', rec }]; +const saveFn = async (k, r) => { rec = r; }; +const log = (m) => console.log(' [sw-renew] ' + m); +const tend = (margin) => tendRenewals({ recordsFn: recs, saveFn, log, deadline: Date.now() + 60_000, margin }); +const mirrorCoins = () => (rec.mgr.vtxos || []).filter((v) => v.state === 'spendable'); + +console.log('\n[1] the app receives a coin, mirrors it, and closes'); +check('received 20000 sat', (await receive(20000)) === 20000, JSON.stringify(app.balance())); +writeMirror(); +const coin = mirrorCoins()[0]; +check('the mirror holds the coin and its key', !!coin && !!rec.keys[String(coin.keyIndex)] && !!rec.key4); +check('no standing order yet, on either side', !(app.state.scheduled || []).length && !(rec.mgr.scheduled || []).length); + +console.log('\n[2] a wake: the worker registers a standing order from the mirror alone'); +// aim the order a few blocks out so the test needn't mine a month +const n1 = await tend(coin.expiryHeight - (tipHeight() + 3)); +const order1 = (rec.mgr.scheduled || [])[0]; +check('one order registered', n1 === 1 && (rec.mgr.scheduled || []).length === 1); +check('with the server\'s unlock hash', !!order1?.unlockHash, order1?.unlockHash?.slice(0, 16)); +check('the coin stays spendable in the mirror', mirrorCoins().some((v) => v.id === coin.id)); +check('the output key it burned is in the mirror', !!rec.keys[String(order1?.outKeyIndex)]); +check('the app knows nothing of it yet', !(app.state.scheduled || []).length); +check('a second wake registers nothing more', (await tend(coin.expiryHeight - (tipHeight() + 3))) === 0 && rec.mgr.scheduled.length === 1); + +console.log('\n[3] the worker spends from the mirror (an NWC pay): the order dies, the change gets its own'); +const worker = await bgManager(rec, 'w1', saveFn); +await worker.send(sh(`${ALICE} -q address`), 5000); +await worker.sync(); +const change = mirrorCoins().find((v) => v.id !== coin.id); +check('change coin in the mirror', !!change, change && `${change.amountSat} sat`); +check('the spent coin\'s order is gone', !(rec.mgr.scheduled || []).some((s) => s.inputIds.includes(coin.id))); +const n2 = await tend(change.expiryHeight - (tipHeight() + 3)); +const order2 = (rec.mgr.scheduled || []).find((s) => s.inputIds.includes(change.id)); +check('the next wake covers the change coin', n2 === 1 && !!order2, JSON.stringify((rec.mgr.scheduled || []).map((s) => s.inputIds))); +check('scheduled a few blocks out', order2?.scheduledHeight === tipHeight() + 3, `${order2?.scheduledHeight} vs ${tipHeight() + 3}`); + +console.log('\n[4] the round runs with nobody online; the next wake claims it into the mirror'); +mine(3 + 2); +await sleep(15_000); +const claimed = () => (rec.mgr.actions || []).some((a) => a.type === 'refresh' && a.step === 'done'); +for (let i = 0; i < 25 && !claimed(); i++) { await tend(change.expiryHeight - (tipHeight() + 3)); mine(1); await sleep(1500); } +if (!claimed()) console.log(' actions:', JSON.stringify((rec.mgr.actions || []).map((a) => [a.type, a.step, a.lastError]))); +const renewed = mirrorCoins().find((v) => v.id !== change.id && v.id !== coin.id); +const renewedId = mirrorCoins().find((v) => v.id !== change.id && v.id !== coin.id)?.id; +check('the consumed order is replaced by one for the fresh coin, in the same wake', (rec.mgr.scheduled || []).length === 1 && !!renewedId && rec.mgr.scheduled[0].inputIds.includes(renewedId), JSON.stringify((rec.mgr.scheduled || []).map((s) => s.inputIds))); +check('the change coin is spent', rec.mgr.vtxos.find((v) => v.id === change.id)?.state === 'spent'); +check('a fresh coin sits in the mirror', !!renewed, renewed && `${renewed.amountSat} sat`); +check('worth the change minus the scheduled fee', !!renewed && renewed.amountSat === change.amountSat - order2.feeSat, `${renewed?.amountSat} vs ${change?.amountSat} - ${order2?.feeSat}`); +check('with its expiry clock restarted', !!renewed && renewed.expiryHeight > change.expiryHeight, renewed && `${change.expiryHeight} -> ${renewed.expiryHeight}`); +check('the renewal is in the mirror\'s history', (rec.mgr.movements || []).some((m) => m.type === 'refresh' && m.status === 'complete')); + +console.log('\n[5] the app returns and merges the worker\'s state'); +// what mergeBgWorkerState does on connect: additive merge, the worker's spent flips win, reconcile +const merged = mergeArkStates(app.state, rec.mgr); +const workerState = new Map(rec.mgr.vtxos.map((v) => [v.id, v.state])); +for (const v of merged.vtxos) if (workerState.get(v.id) === 'spent') v.state = 'spent'; +merged.nextKeyIndex = Math.max(merged.nextKeyIndex || 1, rec.mgr.nextKeyIndex || 1); +app.state = merged; app._save(); +await app.reconcile().catch((e) => console.log(' reconcile:', e.message)); +await app.sync(); +const appCoins = app.vtxos().filter((v) => v.state === 'spendable'); +check('the app holds the fresh coin and nothing stale', appCoins.length === 1 && appCoins[0].id === renewed?.id, JSON.stringify(appCoins.map((v) => [v.id.slice(0, 8), v.amountSat, v.state]))); +check('balance is the change minus the renewal fee', app.balance().spendableSat === change.amountSat - order2.feeSat, JSON.stringify(app.balance())); +check('the app adopts the worker\'s order for the fresh coin', (app.state.scheduled || []).length === 1 && app.state.scheduled[0].inputIds.includes(renewed?.id) && app.state.scheduled[0].unlockHash === rec.mgr.scheduled[0].unlockHash, JSON.stringify((app.state.scheduled || []).map((s) => s.inputIds))); +check('the app is not busy', app.pendingActions().length === 0, JSON.stringify(app.pendingActions().map((a) => [a.type, a.step]))); +check('the renewal shows in the app\'s history once', app.movements().filter((m) => m.type === 'refresh' && m.status === 'complete').length === 1); + +console.log(ok ? '\nALL GREEN\n' : '\nFAILURES\n'); +process.exit(ok ? 0 : 1); diff --git a/tools/nwc-budget-test.js b/tools/nwc-budget-test.js new file mode 100644 index 0000000..780f5ea --- /dev/null +++ b/tools/nwc-budget-test.js @@ -0,0 +1,52 @@ +// The NWC budget window: a UTC day, week (Monday) or month; what a +// connection spent in the window on now, counting the app's counter and the +// worker's unabsorbed spends; when it renews. Run: bun tools/nwc-budget-test.js +import { budgetWindow, budgetRenewsAt, renewalPeriod, spentInWindow } from '../src/nwc-budget.js'; + +let fails = 0; +const check = (name, ok, detail = '') => { console.log(` ${ok ? '✓' : '✗'} ${name}${detail ? ' — ' + detail : ''}`); if (!ok) fails++; }; + +// Wednesday 2026-10-14 23:30 UTC +const T = Date.UTC(2026, 9, 14, 23, 30); +check('day window is the UTC date', budgetWindow('day', T) === '2026-10-14', budgetWindow('day', T)); +check('day: half an hour later is the next day', budgetWindow('day', T + 3600_000) === '2026-10-15'); +check('week window is keyed by its Monday', budgetWindow('week', T) === 'W2026-10-12', budgetWindow('week', T)); +check('week: Sunday night is still that week', budgetWindow('week', Date.UTC(2026, 9, 18, 23, 59)) === 'W2026-10-12'); +check('week: Monday 00:00 starts the next', budgetWindow('week', Date.UTC(2026, 9, 19, 0, 0)) === 'W2026-10-19'); +check('month window is the UTC month', budgetWindow('month', T) === '2026-10'); +check('month: Nov 1 00:00 is the next', budgetWindow('month', Date.UTC(2026, 10, 1)) === '2026-11'); +check('unknown period counts as a day', budgetWindow(undefined, T) === '2026-10-14'); + +check('day renews at next midnight', budgetRenewsAt('day', T) === Date.UTC(2026, 9, 15) / 1000); +check('week renews next Monday', budgetRenewsAt('week', T) === Date.UTC(2026, 9, 19) / 1000); +check('month renews on the 1st', budgetRenewsAt('month', T) === Date.UTC(2026, 10, 1) / 1000); +check('December rolls into January', budgetRenewsAt('month', Date.UTC(2026, 11, 20)) === Date.UTC(2027, 0, 1) / 1000); +check('NIP-47 period words', renewalPeriod('day') === 'daily' && renewalPeriod('week') === 'weekly' && renewalPeriod('month') === 'monthly' && renewalPeriod(undefined) === 'daily'); + +console.log('\n[spent in the window]'); +const conn = { id: 'c1', dailySat: 10000, period: 'month', spentDate: '2026-10', spentToday: 3000 }; +{ + const r = spentInWindow(conn, [], T); + check('the app counter counts when stamped with this window', r.spent === 3000 && r.left === 7000, JSON.stringify(r)); +} +{ + const r = spentInWindow({ ...conn, spentDate: '2026-09' }, [], T); + check('a counter from last month does not', r.spent === 0 && r.left === 10000); +} +{ + const spends = [ + { connId: 'c1', amountSat: 500, feeSat: 2, ts: Date.UTC(2026, 9, 2) }, // this month, unabsorbed + { connId: 'c1', amountSat: 400, feeSat: 0, ts: Date.UTC(2026, 9, 3), absorbed: true }, // already in the counter + { connId: 'c1', amountSat: 900, feeSat: 0, ts: Date.UTC(2026, 8, 30) }, // last month + { connId: 'c2', amountSat: 800, feeSat: 0, ts: Date.UTC(2026, 9, 5) }, // another connection + ]; + const r = spentInWindow(conn, spends, T); + check('the worker adds only its own, unabsorbed spends from this window', r.spent === 3502, String(r.spent)); +} +{ + const r = spentInWindow({ id: 'c1', dailySat: 100, spentDate: '2026-10-14', spentToday: 80 }, [{ connId: 'c1', amountSat: 30, ts: T - 60_000 }], T); + check('a day budget, over: left is 0 not negative', r.spent === 110 && r.left === 0); +} + +console.log(fails ? `\n❌ ${fails} failure(s)` : '\n✅ budget windows behave'); +process.exit(fails ? 1 : 0); diff --git a/tools/nwc-settings-ui-test.js b/tools/nwc-settings-ui-test.js new file mode 100644 index 0000000..b88f9f7 --- /dev/null +++ b/tools/nwc-settings-ui-test.js @@ -0,0 +1,80 @@ +// Settings → Nostr → Nostr Wallet Connect: a connection is made with a +// budget that resets every day, week or month; the card says so, and +// Revoke keeps it (greyed out of the list) answering for a while. +// Run: bun tools/nwc-settings-ui-test.js (needs the regtest ark stack on :3535 for the card to show) +import puppeteer from './puppeteer.js'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 0, fetch: (req) => { + const path = new URL(req.url).pathname; + if (path.startsWith('/punks')) return new Response(Bun.file('dist' + path)); + return new Response(html, { headers: { 'content-type': 'text/html' } }); +} }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +await browser.defaultBrowserContext().overridePermissions(server.url.origin, ['notifications']); +const page = await browser.newPage(); +// a headless Chrome has no push service: make notifications look allowed so +// the connection is created (the app creates it anyway when permission is +// granted and the plumbing fails), without the real notifier in the picture +await page.evaluateOnNewDocument(() => { + try { Object.defineProperty(Notification, 'permission', { get: () => 'granted' }); Notification.requestPermission = async () => 'granted'; } catch {} + // no service worker in this build: 'ready' would never resolve and the + // Create button would hang on it. Stand in one whose push subscribe fails + // the way a browser without a push service does. + try { + Object.defineProperty(navigator.serviceWorker, 'ready', { get: () => Promise.resolve({ + pushManager: { subscribe: async () => { throw new Error('Registration failed - push service error'); }, getSubscription: async () => null }, + showNotification: async () => {}, + }) }); + } catch {} + const f = window.fetch; + window.fetch = (u, o) => (String(u).includes('nwcpush') ? Promise.reject(new Error('no notifier in the test')) : f(u, o)); +}); +const errs = []; +page.on('pageerror', (e) => errs.push(String(e))); +const logs = []; +page.on('console', (m) => logs.push(m.text())); +const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); +const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; +const text = () => page.evaluate(() => document.body.innerText); +try { + await page.setViewport({ width: 390, height: 844, hasTouch: true }); + await page.goto(server.url.href, { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); + await sleep(400); + await click('create a new wallet'); await sleep(600); + await page.waitForSelector('.words .w .t'); + await click('skip verification'); + await waitText('receive', 20000); + await page.evaluate(() => { const b = [...document.querySelectorAll('button')].find((e) => e.getAttribute('aria-label') === 'Settings'); b.click(); }); await sleep(600); + await page.evaluate(() => { const b = [...document.querySelectorAll('.settings-tile')].find((e) => [...e.querySelectorAll('span')].some((x) => x.textContent.trim() === 'Nostr')); if (b) b.click(); }); await sleep(800); + check('the Wallet Connect card is there', await waitText('nostr wallet connect', 15000)); + await click('add a connection'); await sleep(400); + check('the form offers a budget period', await page.evaluate(() => { const s = document.querySelector('select.nwc-period'); return !!s && [...s.options].map((o) => o.value).join() === 'day,week,month' && s.value === 'day'; })); + check('…and says when it resets', (await text()).includes('midnight UTC')); + await page.type('input[placeholder*="App name"]', 'PullCap'); + await page.evaluate(() => { const s = document.querySelector('select.nwc-period'); s.value = 'month'; s.dispatchEvent(new Event('change', { bubbles: true })); }); + await page.evaluate(() => { const i = [...document.querySelectorAll('label.field')].find((l) => l.textContent.includes('Budget (sats)')).querySelector('input'); i.value = ''; i.dispatchEvent(new Event('input', { bubbles: true })); }); + await page.evaluate(() => { const i = [...document.querySelectorAll('label.field')].find((l) => l.textContent.includes('Budget (sats)')).querySelector('input'); i.value = '21000'; i.dispatchEvent(new Event('input', { bubbles: true })); }); + await click('create connection'); + const created = await waitText('pullcap', 10000); + if (!created) console.log('DEBUG env:', await page.evaluate(() => ({ push: 'PushManager' in window, sw: 'serviceWorker' in navigator, perm: Notification.permission, toast: document.querySelector('.toast, [class*=toast]')?.textContent })), '\nDEBUG logs:', logs.slice(-10).join('\n')); + check('the connection is created', created); + const line = (await text()).split('\n').find((l) => /\/payment/.test(l)) || ''; + check('the card reads the budget as monthly', /21,000 a month · 0 spent this month/.test(line), line); + const st = await page.evaluate(() => { const k = Object.keys(localStorage).find((x) => x.endsWith(':nwc') || x.includes('nwc')); return k; }); + const conn = await page.evaluate(() => { for (const k of Object.keys(localStorage)) { try { const v = JSON.parse(localStorage.getItem(k)); const c = v && v.conns && v.conns[0]; if (c && c.name === 'PullCap') return c; } catch {} } return null; }); + check('stored with period month and the budget', conn && conn.period === 'month' && conn.dailySat === 21000, JSON.stringify(conn && { period: conn.period, dailySat: conn.dailySat })); + await page.evaluate(() => { const e = [...document.querySelectorAll('.linklike')].find((n) => n.textContent.trim() === 'Revoke'); e.click(); }); await sleep(600); + const after = await page.evaluate(() => { for (const k of Object.keys(localStorage)) { try { const v = JSON.parse(localStorage.getItem(k)); const c = v && v.conns && v.conns[0]; if (c && c.name === 'PullCap') return c; } catch {} } return null; }); + check('Revoke dates the revocation', after && after.revoked === true && typeof after.revokedAt === 'number' && Date.now() - after.revokedAt < 60_000, JSON.stringify(after && { revoked: after.revoked, revokedAt: after.revokedAt })); + check('…and the connection leaves the list', await page.evaluate(() => ![...document.querySelectorAll('.linklike')].some((n) => n.textContent.trim() === 'Revoke') && ![...document.querySelectorAll('button')].some((b) => b.textContent.includes('Show connection string')))); + await page.screenshot({ path: process.env.SHOT || '/tmp/claude-1000/-home-adam-coinosv3/a8722639-d1b4-4c63-af48-8537d47913b1/scratchpad/nwc-settings.png' }); + check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); +} catch (e) { console.error(e); ok = false; } finally { await browser.close(); server.stop(true); } +console.log(ok ? '\n✅ budget periods in the settings card' : '\n❌ failed'); +process.exit(ok ? 0 : 1); diff --git a/tools/nwc-sw-test.js b/tools/nwc-sw-test.js index 62248a4..e3bdb7b 100644 --- a/tools/nwc-sw-test.js +++ b/tools/nwc-sw-test.js @@ -239,5 +239,136 @@ console.log('\n[sibling record hygiene]'); check('stale record keeps its coin state', saved.wStale.mgr.vtxos.length === 1); } + +console.log('\n[period budgets + get_budget]'); +{ + const { budgetWindow } = await import('../src/nwc-budget.js'); + // a monthly budget: the app's counter (mirrored, stamped with this month) plus the worker's own spends count + const rec = baseRec(); + rec.connections = [{ ...conn, period: 'month', dailySat: 2000, spentDate: budgetWindow('month'), spentToday: 1500 }]; + rec.spends = [{ connId: 'c1', amountSat: 490, feeSat: 0, ts: Date.now() }]; + const { deps, published, decryptReply } = harness({ rec }); + const handled = await respondFromBg({ type: 'nwc', event: ev(makeReq('pay_invoice', { invoice: INV21 })) }, deps); + const r = decryptReply(published[0]); + check('app counter + worker spends over the monthly budget → refused, naming the period', handled && r.error?.code === 'QUOTA_EXCEEDED' && /monthly budget \(10 sat\)/.test(r.error.message), JSON.stringify(r.error)); +} +{ + const { budgetWindow } = await import('../src/nwc-budget.js'); + const rec = baseRec(); + // a counter from LAST month and a worker spend from last month: neither counts this month + const lastMonth = new Date(); lastMonth.setUTCMonth(lastMonth.getUTCMonth() - 1); + rec.connections = [{ ...conn, period: 'month', dailySat: 2000, spentDate: budgetWindow('month', lastMonth.getTime()), spentToday: 1999 }]; + rec.spends = [{ connId: 'c1', amountSat: 1999, feeSat: 0, ts: lastMonth.getTime() }]; + rec.mgr.vtxos = []; // so the pay stops at "empty mirror" right after the budget check + const { deps, published } = harness({ rec }); + const handled = await respondFromBg({ type: 'nwc', event: ev(makeReq('pay_invoice', { invoice: INV21 })) }, deps); + check('last month\'s spending does not count this month (budget passed, mirror empty → wake)', handled === false && published.length === 0); +} +{ + const { budgetWindow, budgetRenewsAt } = await import('../src/nwc-budget.js'); + const rec = baseRec(); + rec.connections = [{ ...conn, period: 'week', dailySat: 7000, spentDate: budgetWindow('week'), spentToday: 1000 }]; + rec.spends = [{ connId: 'c1', amountSat: 200, feeSat: 1, ts: Date.now() }]; + const { deps, published, decryptReply } = harness({ rec }); + const handled = await respondFromBg({ type: 'nwc', event: ev(makeReq('get_budget')) }, deps); + const r = decryptReply(published[0]); + check('get_budget: used, total, renews_at and the period, in msat', handled && r.result?.used_budget === 1201000 && r.result?.total_budget === 7000000 && r.result?.renewal_period === 'weekly' && r.result?.renews_at === budgetRenewsAt('week'), JSON.stringify(r)); + const { deps: d2, published: p2, decryptReply: dr2 } = harness(); + await respondFromBg({ type: 'nwc', event: ev(makeReq('get_info')) }, d2); + check('get_info lists get_budget', dr2(p2[0]).result.methods.includes('get_budget')); +} + +console.log('\n[revoked connection]'); +{ + const rec = baseRec(); + rec.connections = [{ ...conn, revoked: true }]; + const { deps, published, decryptReply } = harness({ rec }); + const handled = await respondFromBg({ type: 'nwc', event: ev(makeReq('pay_invoice', { invoice: INV21 })) }, deps); + const r = decryptReply(published[0]); + check('a pay on a revoked connection is refused UNAUTHORIZED, not ignored', handled === true && r.error?.code === 'UNAUTHORIZED' && r.result_type === 'pay_invoice', JSON.stringify(r)); + const { deps: d2, published: p2, decryptReply: dr2 } = harness({ rec }); + await respondFromBg({ type: 'nwc', event: ev(makeReq('get_balance', {}, 'nip04')) }, d2); + check('…so is a balance ask, in the asker\'s scheme', dr2(p2[0]).error?.code === 'UNAUTHORIZED' && p2[0].tags.find((t) => t[0] === 'encryption')[1] === 'nip04'); +} + +console.log('\n[the mirror carries what the worker needs]'); +{ + const { buildBg } = await import('../src/nwc-bg.js'); + const keyFor = (chain, i) => `${chain}:${i}`.padEnd(8, '0'); + const mgrState = { + nextKeyIndex: 40, nextLnRecvIndex: 0, + vtxos: [{ id: 'v1', keyIndex: 7, state: 'spendable' }, { id: 'v0', keyIndex: 3, state: 'spent' }], + scheduled: [{ unlockHash: 'u1', inputIds: ['v1'], outKeyIndex: 12 }], + actions: [{ type: 'refresh', step: 'submitted', outKeyIndex: 15 }, { type: 'refresh', step: 'done', outKeyIndex: 16 }], + }; + const rec = buildBg({ ark: {}, mgrState, keyFor, connections: [{ ...conn, period: 'month', spentDate: '2026-10', spentToday: 77, revoked: true }] }); + check('a standing order\'s output key travels', rec.keys['12'] === keyFor(3, 12)); + check('a renewal in flight\'s output key travels', rec.keys['15'] === keyFor(3, 15)); + check('a finished renewal\'s does not', !rec.keys['16']); + check('the spent coin\'s key does not, the live one\'s does', !rec.keys['3'] && !!rec.keys['7']); + const c = rec.connections[0]; + check('period, the spent counter and the revocation ride along', c.period === 'month' && c.spentDate === '2026-10' && c.spentToday === 77 && c.revoked === true); + check('…and the budget period defaults to a day', buildBg({ ark: {}, mgrState, keyFor, connections: [conn] }).connections[0].period === 'day'); +} +{ + const { ArkManager } = await import('../src/ark/manager.js'); + const m = ArkManager.mergeScheduled([{ unlockHash: 'a' }, { unlockHash: 'b' }], [{ unlockHash: 'b' }, { unlockHash: 'c' }, { inputIds: [] }]); + check('standing orders merge by unlock hash', m.map((s) => s.unlockHash).join() === 'a,b,c', JSON.stringify(m)); +} + +console.log('\n[tending renewals while closed]'); +{ + const { tendRenewals } = await import('../src/nwc-respond.js'); + const { ArkManager } = await import('../src/ark/manager.js'); + const calls = []; + const orig = { init: ArkManager.prototype.init, tip: ArkManager.prototype._tipMemo, drive: ArkManager.prototype._driveScheduled, ensure: ArkManager.prototype.ensureScheduledRefreshes, refresh: ArkManager.prototype._driveRefresh }; + ArkManager.prototype.init = async function () { this.state = this.storage.load(); calls.push(['init', this.network]); return this; }; + ArkManager.prototype._tipMemo = async function () { calls.push(['tip']); return 100; }; + ArkManager.prototype._driveScheduled = async function () { + calls.push(['drive', (this.state.scheduled || []).length]); + // the round for one order ran: it is promoted — out of scheduled, into a refresh action in flight + const ran = (this.state.scheduled || []).find((s) => s.unlockHash === 'ran'); + this.state.scheduled = (this.state.scheduled || []).filter((s) => s !== ran); + if (ran) (this.state.actions ||= []).push({ id: 'r1', type: 'refresh', step: 'submitted', unlockHash: ran.unlockHash }); + }; + ArkManager.prototype._driveRefresh = async function (a) { calls.push(['claim', a.id, a.step]); a.step = 'done'; }; + ArkManager.prototype.ensureScheduledRefreshes = async function (margin, max) { calls.push(['ensure', margin, max]); return 1; }; + try { + const rec = baseRec(); + rec.key4 = 'ff'.repeat(32); + rec.mgr.nextKeyIndex = 5; + rec.keys = { 1: 'aa', 5: 'bb', 6: 'cc' }; // two upcoming indices in the window + rec.mgr.scheduled = [{ unlockHash: 'ran', inputIds: ['v1'], outKeyIndex: 2 }, { unlockHash: 'waiting', inputIds: ['v1'], outKeyIndex: 3 }]; + const saved = []; + const n = await tendRenewals({ recordsFn: async () => [{ walletKey: 'w1', rec }], saveFn: async (k, r) => saved.push(k), log: () => {} }); + check('claims what ran, then covers what is bare: orders limited to the key window', JSON.stringify(calls) === JSON.stringify([['init', 'mainnet'], ['tip'], ['drive', 2], ['claim', 'r1', 'submitted'], ['ensure', 36, 2]]), JSON.stringify(calls)); + check('one claim and one order counted, the record saved', n === 2 && saved.includes('w1')); + check('the claimed order is gone from the mirror, its claim done', rec.mgr.scheduled.length === 1 && rec.mgr.scheduled[0].unlockHash === 'waiting' && rec.mgr.actions[0].step === 'done'); + // a claim left in flight by an earlier wake (out of time, unconfirmed) is driven on by the next + calls.length = 0; + const rec5 = baseRec(); rec5.key4 = 'ff'.repeat(32); rec5.keys = { 1: 'aa' }; + rec5.mgr.actions = [{ id: 'r2', type: 'refresh', step: 'issued' }, { id: 'r3', type: 'refresh', step: 'done' }, { id: 's1', type: 'send', step: 'created' }]; + const n5 = await tendRenewals({ recordsFn: async () => [{ walletKey: 'w5', rec: rec5 }], saveFn: async () => {} }); + check('a renewal claim in flight is driven on; finished ones and other actions are not', JSON.stringify(calls) === JSON.stringify([['init', 'mainnet'], ['tip'], ['drive', 0], ['claim', 'r2', 'issued']]) && n5 === 1, JSON.stringify(calls)); + + calls.length = 0; + const rec2 = baseRec(); rec2.key4 = 'ff'.repeat(32); rec2.ark.network = 'regtest'; rec2.mgr.nextKeyIndex = 9; rec2.keys = { 1: 'aa' }; // no upcoming key + await tendRenewals({ recordsFn: async () => [{ walletKey: 'w2', rec: rec2 }], saveFn: async () => {} }); + check('no key for an order\'s output → claims still, registers nothing (regtest margin would be 6)', JSON.stringify(calls) === JSON.stringify([['init', 'regtest'], ['tip'], ['drive', 0]]), JSON.stringify(calls)); + + calls.length = 0; + const old = baseRec(); // no key4: a mirror from before invoices — can't sign for the mailbox + await tendRenewals({ recordsFn: async () => [{ walletKey: 'w3', rec: old }], saveFn: async () => {} }); + check('an old mirror is left alone', calls.length === 0); + + calls.length = 0; + const rec4 = baseRec(); rec4.key4 = 'ff'.repeat(32); + await tendRenewals({ recordsFn: async () => [{ walletKey: 'w4', rec: rec4 }], saveFn: async () => {}, deadline: Date.now() - 1 }); + check('out of push budget → nothing started', calls.length === 0); + } finally { + Object.assign(ArkManager.prototype, { init: orig.init, _tipMemo: orig.tip, _driveScheduled: orig.drive, ensureScheduledRefreshes: orig.ensure, _driveRefresh: orig.refresh }); + } +} + console.log(fails ? `\n❌ ${fails} failure(s)` : '\n✅ background responder behaves'); process.exit(fails ? 1 : 0); diff --git a/tools/nwc-test.js b/tools/nwc-test.js index 848b2c6..5b0dd10 100644 --- a/tools/nwc-test.js +++ b/tools/nwc-test.js @@ -13,12 +13,13 @@ const store = {}; globalThis.localStorage = { getItem:k=>k in store?store[k]:null, setItem:(k,v)=>{store[k]=v;}, removeItem:k=>{delete store[k];} }; let subHandler = null; +const subFilters = []; // every filter subscribed, in order let priorReplies = []; let claimOk = true; const published = []; // fake relay transport: capture the subscription handler and any replies const nwcTransport = { - subscribe: (relays, filter, on) => { subHandler = on; return () => { subHandler = null; }; }, + subscribe: (relays, filter, on) => { subFilters.push(filter); subHandler = on; return () => { subHandler = null; }; }, publish: async (relays, evt) => { published.push(evt); return true; }, query: async () => priorReplies, // what other devices have answered (none, unless a test says so) errGraceMs: 20, // the sibling-first hold, shortened for the harness @@ -222,5 +223,68 @@ console.log('\n[device sync of connections]'); check('what we publish carries the connections', Array.isArray(ext.save().nwcConns)); } + +// --------------------------------------------------------------------------- +console.log('\n[period budgets + get_budget]'); +{ + const { budgetWindow, budgetRenewsAt } = await import('../src/nwc-budget.js'); + const st = JSON.parse(store['fs:nwc']); + const c = st.conns.find((x) => x.id === 'test1'); + Object.assign(c, { period: 'month', dailySat: 2000, spentDate: budgetWindow('month'), spentToday: 1990 }); + store['fs:nwc'] = JSON.stringify(st); + f.stop(); f.init(); priorReplies = []; claimOk = true; + const wasPaid = paid.length; + r = await request('pay_invoice', { invoice: 'lnbc210n1p4xuk2wpp506wkjr0xk3677nu7je9c55vq4lzlkyd0ztcq2mlvumap0zpe3alqhp5ppg7g8qwpdv34hgpymhw446y37duzwcn388yp3pw05n7tlulyn2scqzysxqrrssrzjqv3dpepm8kfdxrk3sl6wzqdf49s9c0h9ljtjrek6c08r6aejlwcnur0dwyqqvusqqqqqqqlgqqqq86qqjqsp5dc0jrq94ke2f4dzx8c2dwqsc6a65eu56dt2j599l7kxp7q2hs6zq9qxpqysgqdjeft8gkl0uga24e502pvcp5vgsfap3dxuutcpgfaj33fffuqs9psmnrklshp3fg3py7vlnzsea90vj9ahqq5t9xuy67u3pk0sfnheqpn95f2g' }); + check('21 sat over a monthly budget with 10 left → refused, naming the month', r?.error?.code === 'QUOTA_EXCEEDED' && /monthly budget \(10 sat\)/.test(r?.error?.message || ''), JSON.stringify(r?.error)); + check('nothing was paid', paid.length === wasPaid); + r = await request('get_budget', {}); + check('get_budget reports the month', r?.result?.used_budget === 1990000 && r?.result?.total_budget === 2000000 && r?.result?.renewal_period === 'monthly' && r?.result?.renews_at === budgetRenewsAt('month'), JSON.stringify(r)); + r = await request('get_info', {}); + check('get_info lists get_budget', r?.result?.methods?.includes('get_budget')); + // last month's counter is not this month's + const st2 = JSON.parse(store['fs:nwc']); + const lm = new Date(); lm.setUTCMonth(lm.getUTCMonth() - 1); + Object.assign(st2.conns.find((x) => x.id === 'test1'), { spentDate: budgetWindow('month', lm.getTime()), spentToday: 1990 }); + store['fs:nwc'] = JSON.stringify(st2); + f.stop(); f.init(); + r = await request('get_budget', {}); + check('a counter from last month reads as nothing spent', r?.result?.used_budget === 0, JSON.stringify(r?.result)); + r = await request('pay_invoice', { invoice: INV21 }); // the mock seam pays 25 + 1 fee + check('…and a payment goes through, stamped with this month', !!r?.result?.preimage && JSON.parse(store['fs:nwc']).conns.find((x) => x.id === 'test1').spentDate === budgetWindow('month') && JSON.parse(store['fs:nwc']).conns.find((x) => x.id === 'test1').spentToday === 26, JSON.stringify(r?.error || r)); +} + +console.log('\n[revoked: refused out loud, for a while]'); +{ + const st = JSON.parse(store['fs:nwc']); + const c = st.conns.find((x) => x.id === 'test1'); + c.revoked = true; c.revokedAt = Date.now(); + store['fs:nwc'] = JSON.stringify(st); + subFilters.length = 0; + f.stop(); f.init(); + check('a lately revoked connection is still listened for', subFilters.some((x) => x.kinds?.[0] === 23194 && x['#p']?.[0] === conn.servicePk)); + const wasPaid = paid.length; + r = await request('pay_invoice', { invoice: INV21 }); + check('a pay is answered UNAUTHORIZED', r?.error?.code === 'UNAUTHORIZED' && r?.result_type === 'pay_invoice', JSON.stringify(r)); + check('nothing was paid', paid.length === wasPaid); + r = await request('get_balance', {}, 'nip04'); + check('a balance ask too, in nip04', r?.error?.code === 'UNAUTHORIZED' && r?.result_type === 'get_balance', JSON.stringify(r)); + const n = published.filter((e) => e.kind === 13194 && e.pubkey === conn.servicePk).length; + f.stop(); f.init(); await new Promise((r) => setTimeout(r, 100)); + check('no capability event is published for it', published.filter((e) => e.kind === 13194 && e.pubkey === conn.servicePk).length === n); + check('the revocation date travels in the snapshot', wallet.__ext.save().nwcConns.find((x) => x.id === 'test1').revokedAt === c.revokedAt); + // 31 days on: forgotten + const st2 = JSON.parse(store['fs:nwc']); + st2.conns.find((x) => x.id === 'test1').revokedAt = Date.now() - 31 * 86_400_000; + store['fs:nwc'] = JSON.stringify(st2); + subFilters.length = 0; + f.stop(); f.init(); + check('after the grace period it is no longer listened for', !subFilters.some((x) => x.kinds?.[0] === 23194 && x['#p']?.[0] === conn.servicePk)); + // a revocation dated on two devices keeps the earlier date + const ext = wallet.__ext; + const stale = { ...JSON.parse(store['fs:nwc']).conns.find((x) => x.id === 'test1'), revokedAt: Date.now() - 40 * 86_400_000 }; + ext.load({ nwcConns: [stale] }); + check('merge keeps the earlier revocation date', JSON.parse(store['fs:nwc']).conns.find((x) => x.id === 'test1').revokedAt === stale.revokedAt); +} + console.log(ok ? '\n✅ NWC service behaves' : '\n❌ failed'); process.exit(ok?0:1); |
