nostr-bray 3.13.0 → 3.14.0

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]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nostr-bray",
3
- "version": "3.13.0",
3
+ "version": "3.14.0",
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",