nostr-bray 3.13.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.
package/dist/cli/index.js CHANGED
@@ -391,7 +391,7 @@ else {
391
391
  ctx = new IdentityContext(config.secretKey, config.secretFormat, { forbidPubkeys: config.forbidPubkeys });
392
392
  }
393
393
  // NIP-42: the pool answers AUTH challenges with the active identity's key.
394
- pool.setAuthSigner(async (evt) => ctx.getSigningFunction()(evt));
394
+ pool.setAuthSigner(async (evt) => ctx.getSigningFunction()(evt), () => ctx.activePublicKeyHex);
395
395
  const globalNwcUri = config.nwcUri;
396
396
  const walletsFile = config.walletsFile;
397
397
  config.secretKey = '';
package/dist/index.js CHANGED
@@ -130,7 +130,7 @@ else {
130
130
  // effect when authMode is not 'off' -- the pool checks the mode per operation.
131
131
  // Read-only mode has no signer, and loadConfig has already set authMode off.
132
132
  if (!config.readOnly) {
133
- pool.setAuthSigner(async (evt) => ctx.getSigningFunction()(evt));
133
+ pool.setAuthSigner(async (evt) => ctx.getSigningFunction()(evt), () => ctx.activePublicKeyHex);
134
134
  }
135
135
  const trust = new TrustContext(ctx, pool, {
136
136
  cacheTtl: config.trustCacheTtl,
@@ -1,4 +1,5 @@
1
1
  import type { SigningContext } from '../signing-context.js';
2
+ import type { RelayPool } from '../relay-pool.js';
2
3
  export interface RelayAuthResult {
3
4
  authenticated: boolean;
4
5
  relay: string;
@@ -8,6 +9,15 @@ export interface RelayAuthResult {
8
9
  /**
9
10
  * Authenticate to a relay that requires NIP-42 AUTH.
10
11
  *
12
+ * Pass the `RelayPool` as the third argument: the pool's own connection to the
13
+ * relay is then authenticated as the active identity, through TOR_PROXY and the
14
+ * relay URL rules, so later queries and publishes to that relay on it are
15
+ * served (see RelayPool.authenticate).
16
+ *
17
+ * The older two-argument form still works but opens a separate WebSocket,
18
+ * ignores TOR_PROXY, and closes that connection once authenticated, so the
19
+ * AUTH applies to nothing else. It only shows that the relay accepts the key.
20
+ *
11
21
  * Flow:
12
22
  * 1. Connect via WebSocket
13
23
  * 2. Wait for ["AUTH", challenge] message
@@ -15,4 +25,4 @@ export interface RelayAuthResult {
15
25
  * 4. Send ["AUTH", signedEvent]
16
26
  * 5. Wait for ["OK", eventId, true, ...] confirmation
17
27
  */
18
- export declare function handleRelayAuth(ctx: SigningContext, relay: string): Promise<RelayAuthResult>;
28
+ export declare function handleRelayAuth(ctx: SigningContext, relay: string, pool?: RelayPool): Promise<RelayAuthResult>;
@@ -2,6 +2,15 @@ import { validateRelayUrl } from './handlers.js';
2
2
  /**
3
3
  * Authenticate to a relay that requires NIP-42 AUTH.
4
4
  *
5
+ * Pass the `RelayPool` as the third argument: the pool's own connection to the
6
+ * relay is then authenticated as the active identity, through TOR_PROXY and the
7
+ * relay URL rules, so later queries and publishes to that relay on it are
8
+ * served (see RelayPool.authenticate).
9
+ *
10
+ * The older two-argument form still works but opens a separate WebSocket,
11
+ * ignores TOR_PROXY, and closes that connection once authenticated, so the
12
+ * AUTH applies to nothing else. It only shows that the relay accepts the key.
13
+ *
5
14
  * Flow:
6
15
  * 1. Connect via WebSocket
7
16
  * 2. Wait for ["AUTH", challenge] message
@@ -9,7 +18,11 @@ import { validateRelayUrl } from './handlers.js';
9
18
  * 4. Send ["AUTH", signedEvent]
10
19
  * 5. Wait for ["OK", eventId, true, ...] confirmation
11
20
  */
12
- export async function handleRelayAuth(ctx, relay) {
21
+ export async function handleRelayAuth(ctx, relay, pool) {
22
+ if (pool) {
23
+ validateRelayUrl(relay, { allowPrivate: pool.allowsPrivateRelays?.() === true });
24
+ return pool.authenticate(relay);
25
+ }
13
26
  validateRelayUrl(relay); // throws on private IPs -- intentionally not caught
14
27
  return new Promise((resolve) => {
15
28
  let settled = false;
@@ -207,13 +207,14 @@ export function registerRelayTools(server, deps) {
207
207
  };
208
208
  });
209
209
  server.registerTool('relay-auth', {
210
- description: 'Authenticate to a relay that requires NIP-42 AUTH. Connects to the relay, waits for an AUTH challenge, signs a kind 22242 event, and sends it back. Returns { authenticated: true/false }. Use this when a relay-query fails due to AUTH requirements, then retry the query.',
210
+ description: 'Authenticate (NIP-42) bray\'s own connection to a relay as the active identity, so later queries and publishes to that relay on it are served. Waits for the relay\'s AUTH challenge, signs a kind 22242 event and sends it back. Returns { authenticated: true/false }. Use this when a relay-query fails due to AUTH requirements, then retry the query. Switching identity drops a connection that authenticated as another identity, so authenticate again after a switch.',
211
211
  inputSchema: {
212
212
  relay: relayUrl.describe('Relay WebSocket URL to authenticate with'),
213
213
  },
214
214
  annotations: { readOnlyHint: false },
215
215
  }, async ({ relay }) => {
216
- const result = await handleRelayAuth(deps.ctx, relay);
216
+ // On the pool's own connection, so the retried query is authenticated.
217
+ const result = await handleRelayAuth(deps.ctx, relay, deps.pool);
217
218
  return {
218
219
  content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
219
220
  };
@@ -72,6 +72,14 @@ export interface PoolLike {
72
72
  }): Promise<AbstractRelay>;
73
73
  /** Install the eager AUTH-challenge responder. Absent on injected test doubles. */
74
74
  setAutomaticAuth?(signer: ((relayUrl: string) => AuthSigner | null) | undefined): void;
75
+ /**
76
+ * Consulted before each use of a relay connection, with nostr-tools'
77
+ * normalised URL and whether a connection is open: true closes the open one
78
+ * so the use starts on a fresh connection. Absent on injected test doubles.
79
+ */
80
+ setReuseCheck?(check: ((url: string, open: boolean) => boolean) | undefined): void;
81
+ /** Close and forget one relay's connection. Absent on injected test doubles. */
82
+ forget?(url: string): void;
75
83
  destroy(): void;
76
84
  }
77
85
  export interface ReconcileDirectResult {
@@ -148,8 +156,13 @@ export declare class RelayPool {
148
156
  * Called once the identity context exists, which is after the pool is
149
157
  * constructed. Passing `undefined` disables authentication again (used when
150
158
  * switching identity, so a challenge is never answered with a stale key).
159
+ *
160
+ * `currentPubkey` returns the active identity's pubkey (hex). With it, a
161
+ * relay connection is not reused across an identity switch when that could
162
+ * tie the two identities together (see #reuse); without it, connections are
163
+ * reused as before.
151
164
  */
152
- setAuthSigner(signer: AuthSigner | undefined): void;
165
+ setAuthSigner(signer: AuthSigner | undefined, currentPubkey?: () => string): void;
153
166
  /** Current NIP-42 policy. */
154
167
  getAuthMode(): AuthMode;
155
168
  /** Change the NIP-42 policy at runtime. */
@@ -200,6 +213,25 @@ export declare class RelayPool {
200
213
  countDirect(relays: string[], filter: Filter, opts?: {
201
214
  timeoutMs?: number;
202
215
  }): Promise<RelayCount[]>;
216
+ /**
217
+ * NIP-42: authenticate the pool's own connection to `url` as the active
218
+ * identity, so later queries and publishes to that relay on it are served.
219
+ *
220
+ * An explicit request, so it works in every auth mode. It waits for the
221
+ * relay's challenge, prompting one with an empty REQ if the relay sends it
222
+ * only after refusing a request (bray's serve --auth does). A connection
223
+ * that carried another identity's traffic is replaced first; after a refusal
224
+ * the connection is dropped, since nostr-tools keeps its first attempt and a
225
+ * second try on it would only repeat the refusal.
226
+ */
227
+ authenticate(url: string, opts?: {
228
+ timeoutMs?: number;
229
+ }): Promise<{
230
+ authenticated: boolean;
231
+ relay: string;
232
+ pubkey?: string;
233
+ error?: string;
234
+ }>;
203
235
  /** Reconcile local event IDs with one relay using NIP-77 Negentropy. */
204
236
  reconcileDirect(relayUrl: string, items: Array<{
205
237
  id: string;
@@ -61,6 +61,18 @@ async function createRealPool(torProxy) {
61
61
  const WebSocketImpl = webSocketFor(torProxy, { maxPayload: WS_MAX_PAYLOAD });
62
62
  useWebSocketImplementation(WebSocketImpl);
63
63
  const pool = new SimplePool({ websocketImplementation: WebSocketImpl });
64
+ const { normalizeURL } = await import('nostr-tools/utils');
65
+ // nostr-tools reaches every relay through ensureRelay, so this is where a
66
+ // connection can be refused reuse. The relay map is protected in its types.
67
+ const relayMap = pool.relays;
68
+ const ensureRelay = pool.ensureRelay.bind(pool);
69
+ let reuseCheck;
70
+ pool.ensureRelay = ((url, params) => {
71
+ const key = normalizeURL(url);
72
+ if (reuseCheck?.(key, relayMap.has(key)))
73
+ pool.close([key]);
74
+ return ensureRelay(url, params);
75
+ });
64
76
  return {
65
77
  // `onauth` is spread straight through to the subscription params by
66
78
  // querySync/subscribeEose, so it works despite not being in querySync's
@@ -71,6 +83,8 @@ async function createRealPool(torProxy) {
71
83
  subscribeEose: (relays, filter, handlers) => pool.subscribeEose(relays, filter, handlers),
72
84
  ensureRelay: (url, params) => pool.ensureRelay(url, params),
73
85
  setAutomaticAuth: signerFor => setAutomaticAuth(pool, signerFor),
86
+ setReuseCheck: check => { reuseCheck = check; },
87
+ forget: url => pool.close([normalizeURL(url)]),
74
88
  destroy: () => pool.destroy(),
75
89
  };
76
90
  }
@@ -89,6 +103,14 @@ export class RelayPool {
89
103
  authSigner;
90
104
  /** Relays we have signed an AUTH event for, for diagnostics. */
91
105
  authedRelays = new Set();
106
+ /** The active identity's pubkey (hex), from the signing context. */
107
+ #currentPubkey;
108
+ /**
109
+ * For each relay connection (nostr-tools' normalised URL): the identity that
110
+ * last used it, and the one whose AUTH event it has seen (accepted or not, the
111
+ * relay has seen the key). See #reuse.
112
+ */
113
+ #connectionOwners = new Map();
92
114
  constructor(config, injectedPool) {
93
115
  this.torProxy = config.torProxy;
94
116
  this.allowClearnet = config.allowClearnet;
@@ -126,6 +148,45 @@ export class RelayPool {
126
148
  else {
127
149
  this.poolReady = createRealPool(config.torProxy).then(p => { this.pool = p; return p; });
128
150
  }
151
+ // Registered before any caller can await poolReady, so no use goes unchecked.
152
+ void this.poolReady.then(p => p.setReuseCheck?.((url, open) => this.#reuse(url, open)));
153
+ }
154
+ /** The active identity's pubkey, or undefined when it is not known (yet). */
155
+ #activePubkey() {
156
+ try {
157
+ return this.#currentPubkey?.();
158
+ }
159
+ catch {
160
+ // A bunker context throws until its key is resolved.
161
+ return undefined;
162
+ }
163
+ }
164
+ /**
165
+ * Whether the open connection to `url` must be replaced before the active
166
+ * identity uses it, so one connection never carries two identities.
167
+ *
168
+ * A NIP-42 AUTH ties a connection to a key, so a relay that has seen one
169
+ * identity's AUTH on a connection could link it to the next identity's
170
+ * traffic there. That connection is replaced in every auth mode. With AUTH on
171
+ * (on-demand or eager), any connection another identity used is replaced
172
+ * too, since the next AUTH on it would link the two. With AUTH off and no AUTH
173
+ * sent, a connection is kept across a switch. The same IP and timing remain
174
+ * either way: this removes the AUTH link only.
175
+ */
176
+ #reuse(url, open) {
177
+ const current = this.#activePubkey();
178
+ if (current === undefined)
179
+ return false;
180
+ const owner = open ? this.#connectionOwners.get(url) : undefined;
181
+ const sawOtherAuth = owner?.authedBy !== undefined && owner.authedBy !== current;
182
+ const usedByOther = this.authMode !== 'off' && owner?.usedBy !== undefined && owner.usedBy !== current;
183
+ if (sawOtherAuth || usedByOther) {
184
+ console.error(`[bray] new connection to ${url} for the active identity: the open one ${sawOtherAuth ? 'authenticated as' : 'was used by'} another identity`);
185
+ this.#connectionOwners.set(url, { usedBy: current });
186
+ return true;
187
+ }
188
+ this.#connectionOwners.set(url, { ...owner, usedBy: current });
189
+ return false;
129
190
  }
130
191
  /** Store relay set for an identity and flush any queued writes */
131
192
  reconfigure(npub, relays) {
@@ -175,9 +236,15 @@ export class RelayPool {
175
236
  * Called once the identity context exists, which is after the pool is
176
237
  * constructed. Passing `undefined` disables authentication again (used when
177
238
  * switching identity, so a challenge is never answered with a stale key).
239
+ *
240
+ * `currentPubkey` returns the active identity's pubkey (hex). With it, a
241
+ * relay connection is not reused across an identity switch when that could
242
+ * tie the two identities together (see #reuse); without it, connections are
243
+ * reused as before.
178
244
  */
179
- setAuthSigner(signer) {
245
+ setAuthSigner(signer, currentPubkey) {
180
246
  this.authSigner = signer;
247
+ this.#currentPubkey = currentPubkey;
181
248
  this.authedRelays.clear();
182
249
  void this.#applyEagerAuth();
183
250
  }
@@ -223,8 +290,11 @@ export class RelayPool {
223
290
  throw new Error('NIP-42 AUTH requested but no signer is configured');
224
291
  const relayTag = evt.tags.find(t => t[0] === 'relay')?.[1];
225
292
  const signed = await this.authSigner(evt);
226
- if (relayTag)
293
+ if (relayTag) {
227
294
  this.authedRelays.add(relayTag);
295
+ // nostr-tools names the relay by the same normalised URL as its map.
296
+ this.#connectionOwners.set(relayTag, { ...this.#connectionOwners.get(relayTag), authedBy: signed.pubkey });
297
+ }
228
298
  return signed;
229
299
  };
230
300
  /**
@@ -443,6 +513,60 @@ export class RelayPool {
443
513
  }
444
514
  }
445
515
  }
516
+ /**
517
+ * NIP-42: authenticate the pool's own connection to `url` as the active
518
+ * identity, so later queries and publishes to that relay on it are served.
519
+ *
520
+ * An explicit request, so it works in every auth mode. It waits for the
521
+ * relay's challenge, prompting one with an empty REQ if the relay sends it
522
+ * only after refusing a request (bray's serve --auth does). A connection
523
+ * that carried another identity's traffic is replaced first; after a refusal
524
+ * the connection is dropped, since nostr-tools keeps its first attempt and a
525
+ * second try on it would only repeat the refusal.
526
+ */
527
+ async authenticate(url, opts = {}) {
528
+ this.#validateDirectRelays([url]);
529
+ if (!this.authSigner)
530
+ return { authenticated: false, relay: url, error: 'NIP-42 AUTH requested but no signer is configured' };
531
+ const pool = await this.poolReady;
532
+ if (!pool.ensureRelay)
533
+ return { authenticated: false, relay: url, error: 'the underlying relay pool cannot authenticate' };
534
+ const timeoutMs = opts.timeoutMs ?? 5_000;
535
+ const { normalizeURL } = await import('nostr-tools/utils');
536
+ const current = this.#activePubkey();
537
+ const owner = this.#connectionOwners.get(normalizeURL(url));
538
+ if (current !== undefined && owner?.usedBy !== undefined && owner.usedBy !== current)
539
+ pool.forget?.(url);
540
+ let relay;
541
+ try {
542
+ relay = await pool.ensureRelay(url, { connectionTimeout: timeoutMs });
543
+ }
544
+ catch (err) {
545
+ return { authenticated: false, relay: url, error: `connection failure: ${reasonOf(err)}` };
546
+ }
547
+ // nostr-tools keeps the latest challenge on the relay; it is private in its types.
548
+ const challenge = () => relay.challenge;
549
+ const deadline = Date.now() + timeoutMs;
550
+ const probeAt = Date.now() + Math.min(500, timeoutMs / 2);
551
+ let probed = false;
552
+ while (!challenge()) {
553
+ if (Date.now() >= deadline)
554
+ return { authenticated: false, relay: url, error: 'AUTH handshake timed out (no challenge received)' };
555
+ if (!probed && Date.now() >= probeAt) {
556
+ probed = true;
557
+ const probe = relay.subscribe([{ limit: 0 }], { onevent: () => { }, oneose: () => probe.close(), onclose: () => { } });
558
+ }
559
+ await new Promise(resolve => setTimeout(resolve, 25));
560
+ }
561
+ try {
562
+ await within(timeoutMs, relay.auth(this.#signAuth), 'AUTH timed out');
563
+ return { authenticated: true, relay: url, pubkey: this.#connectionOwners.get(relay.url)?.authedBy ?? current };
564
+ }
565
+ catch (err) {
566
+ pool.forget?.(url);
567
+ return { authenticated: false, relay: url, error: `AUTH rejected: ${reasonOf(err)}` };
568
+ }
569
+ }
446
570
  /** Reconcile local event IDs with one relay using NIP-77 Negentropy. */
447
571
  async reconcileDirect(relayUrl, items, filter, opts = {}) {
448
572
  this.#validateDirectRelays([relayUrl]);
@@ -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.13.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",