aboutsummaryrefslogtreecommitdiffstats
path: root/src/features/nwc.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/features/nwc.js')
-rw-r--r--src/features/nwc.js94
1 files changed, 69 insertions, 25 deletions
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')));
}