aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2026-10-16 12:32:28 -0700
committerAdam Soltys <[email protected]>2026-10-16 12:32:28 -0700
commit294a49598e43e3e6f9e34f0246bbea41837359f9 (patch)
tree0fe376316626a9b27330ecbba15740d14ec4c825 /src
parent38ce0b441505d0bdd048d38c82ac95afe4d3b407 (diff)
downloadcoinosv3-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
Diffstat (limited to 'src')
-rw-r--r--src/ark/manager.js14
-rw-r--r--src/features/ark.js6
-rw-r--r--src/features/nwc.js94
-rw-r--r--src/i18n.js13
-rw-r--r--src/nwc-bg.js12
-rw-r--r--src/nwc-budget.js54
-rw-r--r--src/nwc-respond.js85
-rw-r--r--src/sw-nwc.js11
8 files changed, 247 insertions, 42 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;