nostr-bray 3.14.0 → 3.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -44,7 +44,15 @@ export interface ServiceWallet {
44
44
  }): Promise<ServiceInvoice | null>;
45
45
  }
46
46
  export interface ServiceTransport {
47
- subscribe(relays: string[], filter: Filter, onEvent: (event: NostrEvent) => void): Promise<() => void>;
47
+ /**
48
+ * `onclose`, if the transport supports it, is called when the relays end the
49
+ * subscription themselves, with each relay's reason; the service then
50
+ * subscribes again. A transport without it cannot report that.
51
+ */
52
+ subscribe(relays: string[], filter: Filter, onEvent: (event: NostrEvent) => void, onclose?: (reasons: Array<{
53
+ url: string;
54
+ reason: string;
55
+ }>) => void): Promise<() => void>;
48
56
  publish(relays: string[], event: NostrEvent): Promise<void>;
49
57
  }
50
58
  export interface Grant {
@@ -93,6 +101,16 @@ export interface ServiceOptions {
93
101
  persist?: () => Promise<void>;
94
102
  log?: (message: string) => void;
95
103
  now?: () => number;
104
+ /**
105
+ * Milliseconds before subscribing again once the relays end a subscription
106
+ * (default 5000), doubling up to a minute while they refuse a new one.
107
+ */
108
+ resubscribeDelayMs?: number;
109
+ /**
110
+ * Asked before subscribing again: false stops the grant instead, for when
111
+ * the service should no longer answer (the active identity changed).
112
+ */
113
+ shouldServe?: () => boolean;
96
114
  }
97
115
  export declare class WalletService {
98
116
  #private;
@@ -168,6 +168,7 @@ function invoiceResult(view) {
168
168
  ...(view.feesPaidMsat === undefined ? {} : { fees_paid: view.feesPaidMsat }),
169
169
  };
170
170
  }
171
+ const MAX_RESUBSCRIBE_DELAY_MS = 60_000;
171
172
  // The fields another process may change while this one serves.
172
173
  function adopt(target, source) {
173
174
  target.methods = source.methods;
@@ -193,6 +194,10 @@ export class WalletService {
193
194
  #stops = new Map();
194
195
  #queues = new Map();
195
196
  #grants = new Map();
197
+ // One per grant while it is served: a subscription ending belongs to the
198
+ // session it was opened in, so a late close from an old one is ignored.
199
+ #sessions = new Map();
200
+ #retries = new Map();
196
201
  constructor(opts) {
197
202
  this.#opts = opts;
198
203
  this.#now = opts.now ?? (() => Date.now());
@@ -205,19 +210,77 @@ export class WalletService {
205
210
  return;
206
211
  this.stop(grant.id);
207
212
  this.#grants.set(grant.id, grant);
213
+ const session = {};
214
+ this.#sessions.set(grant.id, session);
208
215
  await this.#opts.transport.publish(grant.relays, infoEvent(grant));
216
+ await this.#listen(grant, session);
217
+ this.#opts.log?.(`serving ${grant.name} on ${grant.relays.join(', ')}`);
218
+ }
219
+ // Subscribe for the grant's requests. It starts MAX_REQUEST_AGE_SECS back,
220
+ // here as on a resubscription; a request seen before is in grant.seen, and
221
+ // a spending one is written there before it runs, so it is not paid twice.
222
+ async #listen(grant, session) {
209
223
  const since = Math.floor(this.#now() / 1000) - MAX_REQUEST_AGE_SECS;
210
- const stop = await this.#opts.transport.subscribe(grant.relays, { kinds: [NWC_REQUEST_KIND], '#p': [grant.servicePubkey], since }, (event) => this.#enqueue(grant.id, event));
224
+ let ended = false;
225
+ const stop = await this.#opts.transport.subscribe(grant.relays, { kinds: [NWC_REQUEST_KIND], '#p': [grant.servicePubkey], since }, (event) => this.#enqueue(grant.id, event), (reasons) => {
226
+ if (ended)
227
+ return;
228
+ ended = true;
229
+ this.#ended(grant, session, reasons);
230
+ });
231
+ if (this.#sessions.get(grant.id) !== session) {
232
+ stop();
233
+ return;
234
+ }
211
235
  this.#stops.set(grant.id, stop);
212
- this.#opts.log?.(`serving ${grant.name} on ${grant.relays.join(', ')}`);
236
+ }
237
+ // The relays ended the subscription (not this service: stop() ends the
238
+ // session first). Subscribe again rather than go quiet while serving.
239
+ #ended(grant, session, reasons) {
240
+ if (this.#sessions.get(grant.id) !== session)
241
+ return;
242
+ this.#stops.delete(grant.id);
243
+ const why = reasons.map(({ url, reason }) => `${url}: ${reason}`).join('; ') || 'no reason given';
244
+ this.#opts.log?.(`subscription for ${grant.name} ended (${why})`);
245
+ this.#retry(grant, session, this.#opts.resubscribeDelayMs ?? 5_000);
246
+ }
247
+ #retry(grant, session, delayMs) {
248
+ const timer = setTimeout(() => { void this.#resubscribe(grant, session, delayMs); }, delayMs);
249
+ this.#retries.set(grant.id, timer);
250
+ }
251
+ async #resubscribe(grant, session, delayMs) {
252
+ this.#retries.delete(grant.id);
253
+ if (this.#sessions.get(grant.id) !== session)
254
+ return;
255
+ if (this.#opts.shouldServe && !this.#opts.shouldServe()) {
256
+ this.stop(grant.id);
257
+ this.#opts.log?.(`stopped serving ${grant.name}: it should no longer be served here (the identity changed)`);
258
+ return;
259
+ }
260
+ try {
261
+ await this.#listen(grant, session);
262
+ this.#opts.log?.(`serving ${grant.name} again`);
263
+ }
264
+ catch (err) {
265
+ const next = Math.min(delayMs * 2, MAX_RESUBSCRIBE_DELAY_MS);
266
+ this.#opts.log?.(`could not subscribe again for ${grant.name}: ${err.message}; trying again in ${next} ms`);
267
+ this.#retry(grant, session, next);
268
+ }
213
269
  }
214
270
  stop(grantId) {
271
+ // End the session first, so the subscription closing below is not taken
272
+ // for the relays ending it.
273
+ this.#sessions.delete(grantId);
274
+ const retry = this.#retries.get(grantId);
275
+ if (retry)
276
+ clearTimeout(retry);
277
+ this.#retries.delete(grantId);
215
278
  this.#stops.get(grantId)?.();
216
279
  this.#stops.delete(grantId);
217
280
  this.#grants.delete(grantId);
218
281
  }
219
282
  close() {
220
- for (const id of [...this.#stops.keys()])
283
+ for (const id of new Set([...this.#stops.keys(), ...this.#sessions.keys()]))
221
284
  this.stop(id);
222
285
  }
223
286
  // The grant as the store has it now. False when it is gone or revoked.
@@ -75,12 +75,15 @@ export function registerWalletServiceTools(server, deps, options = {}) {
75
75
  service = new WalletService({
76
76
  wallet: upstreamWallet({ uri, alias: deps.ctx.activeNpub, guard: defaultPaymentGuard() }),
77
77
  transport: {
78
- subscribe: (relays, filter, onEvent) => deps.pool.subscribe(relays, filter, onEvent),
78
+ // With onclose the service subscribes again when a relay ends it.
79
+ subscribe: (relays, filter, onEvent, onclose) => deps.pool.subscribe(relays, filter, onEvent, { onclose }),
79
80
  publish: async (relays, event) => {
80
81
  await deps.pool.publishDirect(relays, event);
81
82
  },
82
83
  },
83
84
  store: fileGrantStore(grantsFile, pubkey),
85
+ // An identity switch is a different wallet: do not subscribe again for it.
86
+ shouldServe: () => identity() === servingFor,
84
87
  });
85
88
  return service;
86
89
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nostr-bray",
3
- "version": "3.14.0",
3
+ "version": "3.14.1",
4
4
  "mcpName": "dev.forgesworn/bray",
5
5
  "description": "Trust-aware Nostr MCP server, CLI and TypeScript SDK for AI agents and humans. Three dimensions of trust -- verification, proximity, and access -- woven into every interaction.",
6
6
  "type": "module",