nostr-bray 3.11.0 → 3.12.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.
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The NIP-42 mode flags, `--auth` and `--eager-auth`.
3
+ *
4
+ * bray reads them only before the command (`nostr-bray --auth req ...`), so
5
+ * they can be stripped before command detection. After the command they belong
6
+ * to it: `relay curl <url> --auth` means NIP-98, and `serve --auth` makes the
7
+ * test relay require AUTH. Anywhere else a mode flag after the command does
8
+ * nothing, which is easy to miss, so it is reported as misplaced.
9
+ */
10
+ export interface AuthFlags {
11
+ /** `on-demand` for a leading --auth, `eager` for a leading --eager-auth. */
12
+ mode?: 'on-demand' | 'eager';
13
+ /** The arguments with the leading mode flags removed. */
14
+ rest: string[];
15
+ /** A mode flag found after a command that has none of its own; it has no effect. */
16
+ misplaced?: '--auth' | '--eager-auth';
17
+ }
18
+ export declare function parseAuthFlags(argv: string[]): AuthFlags;
@@ -0,0 +1,22 @@
1
+ const isModeFlag = (arg) => arg === '--auth' || arg === '--eager-auth';
2
+ /** Commands that give --auth / --eager-auth a meaning of their own. */
3
+ function ownsModeFlags([command, sub]) {
4
+ return command === 'serve' || command === 'relay-curl' || (command === 'relay' && sub === 'curl');
5
+ }
6
+ export function parseAuthFlags(argv) {
7
+ const rest = [...argv];
8
+ let mode;
9
+ while (isModeFlag(rest[0])) {
10
+ if (rest[0] === '--eager-auth')
11
+ mode = 'eager';
12
+ else if (mode !== 'eager')
13
+ mode = 'on-demand';
14
+ rest.shift();
15
+ }
16
+ const misplaced = ownsModeFlags(rest) ? undefined : rest.slice(1).find(isModeFlag);
17
+ return {
18
+ ...(mode ? { mode } : {}),
19
+ rest,
20
+ ...(misplaced ? { misplaced } : {}),
21
+ };
22
+ }
@@ -1,6 +1,7 @@
1
1
  import { handleRelayInfo, handleRelayList, handleRelaySet, handleRelayAdd, handleRelayQuery, handleRelayCurl, handleSubscribe, handleOutboxRelays, handleOutboxPublish } from '../../exports.js';
2
2
  import { TrustContext } from '../../trust-context.js';
3
3
  import * as fmt from '../../format.js';
4
+ import { isNormalRequestEnd } from '../../relay-pool.js';
4
5
  const TRUST_ORDER = ['unknown', 'stranger', 'verified-stranger', 'known', 'trusted'];
5
6
  function meetsTrustThreshold(level, minLevel) {
6
7
  return TRUST_ORDER.indexOf(level) >= TRUST_ORDER.indexOf(minLevel);
@@ -26,7 +27,7 @@ export async function dispatch(cmd, cmdArgs, h, ctx, pool, _activeNpub) {
26
27
  }));
27
28
  break;
28
29
  case 'relay-info':
29
- out(await handleRelayInfo(req(1, 'relay-info <wss://url>')));
30
+ out(await handleRelayInfo(req(1, 'relay-info <wss://url>'), { allowPrivateRelays: pool.allowsPrivateRelays() }));
30
31
  break;
31
32
  case 'req': {
32
33
  // Support a JSON filter on stdin when stdin is a pipe. Not being a TTY
@@ -137,7 +138,16 @@ export async function dispatch(cmd, cmdArgs, h, ctx, pool, _activeNpub) {
137
138
  ...(paginateIntervalMs !== undefined ? { paginateIntervalMs } : {}),
138
139
  ...(maxPages !== undefined ? { maxPages } : {}),
139
140
  };
140
- let events = await handleRelayQuery(pool, ctx.activeNpub, queryArgs);
141
+ if (!relayOverrides.length && pool.getRelays(ctx.activeNpub).read.length === 0) {
142
+ throw new Error('No relays available. Set NOSTR_RELAYS or pass --relay <url>.');
143
+ }
144
+ // Keep each relay's reason for ending a REQ, so a refusal is not
145
+ // mistaken for no matching events.
146
+ const ends = [];
147
+ let events = await handleRelayQuery(pool, ctx.activeNpub, {
148
+ ...queryArgs,
149
+ onRelayClose: (reasons) => { ends.push(reasons); },
150
+ });
141
151
  const minTrust = flag('min-trust');
142
152
  if (minTrust) {
143
153
  if (!TRUST_ORDER.includes(minTrust)) {
@@ -164,6 +174,19 @@ export async function dispatch(cmd, cmdArgs, h, ctx, pool, _activeNpub) {
164
174
  else {
165
175
  out(events);
166
176
  }
177
+ // Relays that refused the REQ or could not be reached, once each, on
178
+ // stderr. With no events and every relay refusing, the query failed.
179
+ const refused = new Set();
180
+ for (const page of ends) {
181
+ for (const { url, reason } of page)
182
+ if (!isNormalRequestEnd(reason))
183
+ refused.add(`${url}: ${reason}`);
184
+ }
185
+ for (const line of refused)
186
+ console.error(line);
187
+ const allRefused = ends.some(page => page.length > 0 && page.every(({ reason }) => !isNormalRequestEnd(reason)));
188
+ if (events.length === 0 && allRefused)
189
+ process.exitCode = 1;
167
190
  break;
168
191
  }
169
192
  case 'relay-curl': {
@@ -196,11 +219,23 @@ export async function dispatch(cmd, cmdArgs, h, ctx, pool, _activeNpub) {
196
219
  ...(until !== undefined ? { until } : {}),
197
220
  ...(limit !== undefined ? { limit } : {}),
198
221
  };
199
- const unsubscribe = await handleSubscribe(pool, ctx.activeNpub, filter, (event) => process.stdout.write(JSON.stringify(event) + '\n'), relayOverrides.length ? relayOverrides : undefined);
200
- // Run until SIGINT
201
- await new Promise(resolve => {
202
- process.once('SIGINT', () => { unsubscribe(); resolve(); });
222
+ // Run until SIGINT, or until every relay has ended the subscription.
223
+ // Stopping on SIGINT closes it too ("closed by caller"); that is not news.
224
+ let stopping = false;
225
+ let ended;
226
+ const closedByRelays = new Promise(resolve => { ended = resolve; });
227
+ const unsubscribe = await handleSubscribe(pool, ctx.activeNpub, filter, (event) => process.stdout.write(JSON.stringify(event) + '\n'), relayOverrides.length ? relayOverrides : undefined, { onclose: reasons => { if (!stopping)
228
+ ended(reasons); } });
229
+ const reasons = await new Promise(resolve => {
230
+ process.once('SIGINT', () => { stopping = true; unsubscribe(); resolve(undefined); });
231
+ void closedByRelays.then(resolve);
203
232
  });
233
+ if (reasons) {
234
+ for (const { url, reason } of reasons)
235
+ console.error(`${url}: ${reason}`);
236
+ console.error('subscription ended: every relay closed it');
237
+ process.exitCode = 1;
238
+ }
204
239
  break;
205
240
  }
206
241
  case 'outbox-relays': {
package/dist/cli/index.js CHANGED
@@ -18,6 +18,7 @@ import * as musig2 from './commands/musig2.js';
18
18
  import * as sync from './commands/sync.js';
19
19
  import * as admin from './commands/admin.js';
20
20
  import * as wallet from './commands/wallet.js';
21
+ import { parseAuthFlags } from './auth-flags.js';
21
22
  const args = process.argv.slice(2);
22
23
  // Strip global flags before command detection so `--bunker <uri> whoami` works.
23
24
  for (const flag of ['--bunker', '--key']) {
@@ -31,14 +32,12 @@ for (const flag of ['--bunker', '--key']) {
31
32
  // Boolean global flags, recognised only in the leading position (`--auth req ...`)
32
33
  // so they can be stripped before command detection. Anything after the command
33
34
  // belongs to that command: `relay curl <url> --auth` means NIP-98, not NIP-42.
34
- let authFlagPresent = false;
35
- let eagerAuthFlagPresent = false;
36
- while (args[0] === '--auth' || args[0] === '--eager-auth') {
37
- if (args[0] === '--eager-auth')
38
- eagerAuthFlagPresent = true;
39
- else
40
- authFlagPresent = true;
41
- args.shift();
35
+ const authFlags = parseAuthFlags(args);
36
+ args.splice(0, args.length, ...authFlags.rest);
37
+ const authFlagPresent = authFlags.mode === 'on-demand';
38
+ const eagerAuthFlagPresent = authFlags.mode === 'eager';
39
+ if (authFlags.misplaced) {
40
+ console.error(`warning: ${authFlags.misplaced} only takes effect before the command (nostr-bray ${authFlags.misplaced} ${args[0]} ...); ignored here`);
42
41
  }
43
42
  const command = args[0];
44
43
  // No command = start MCP server.
@@ -216,7 +215,7 @@ Utility:
216
215
  -k takes a kind number or a registry name, e.g. -k "short text note"
217
216
  validate-event [event-json|--file path] [--validation strict-known|off] Semantic protocol validation (no signature check)
218
217
  publish-raw [--file path] [--report] [--timeout ms] [--quorum n] [--validation strict-known|off] Validate, sign+broadcast event
219
- subscribe [--kinds N,N] [--authors hex] [--relay url] Live-tail events to stdout (JSONL) until SIGINT
218
+ subscribe [--kinds N,N] [--authors hex] [--relay url] Live-tail events to stdout (JSONL) until SIGINT; exits 1 if every relay ends it
220
219
  decode <nip19> Decode npub/nsec/note/nevent/nprofile/naddr
221
220
  encode npub <hex> Encode hex pubkey as npub
222
221
  encode note <hex> Encode hex event ID as note
@@ -281,6 +280,7 @@ Flags:
281
280
  --key <nsec|hex|mnemonic> Use this secret key (overrides env/config)
282
281
  --auth Answer NIP-42 AUTH after an auth-required rejection
283
282
  --eager-auth Answer the NIP-42 AUTH challenge as soon as it arrives
283
+ (both go before the command: nostr-bray --auth req ...)
284
284
  --json Output raw JSON (for piping/scripts)
285
285
  --human Force human-readable output
286
286
  --jsonl | --csv | --tsv Structured list output (line-, comma- or tab-delimited)
@@ -1,6 +1,6 @@
1
1
  import type { Event as NostrEvent, Filter } from 'nostr-tools';
2
2
  import type { SigningContext } from '../signing-context.js';
3
- import type { RelayPool } from '../relay-pool.js';
3
+ import type { RelayPool, SubscriptionClose } from '../relay-pool.js';
4
4
  import type { PublishResult } from '../types.js';
5
5
  export interface RelayHealthEntry {
6
6
  url: string;
@@ -103,6 +103,12 @@ export interface RelayQueryArgs {
103
103
  paginateIntervalMs?: number;
104
104
  /** Safety valve on the number of REQs issued when paginating. Defaults to 20. */
105
105
  maxPages?: number;
106
+ /**
107
+ * Called after each REQ with every relay's reason for ending it (see
108
+ * isNormalRequestEnd). Without it, a relay that refuses the REQ looks the
109
+ * same as one with no matching events.
110
+ */
111
+ onRelayClose?: (reasons: SubscriptionClose[]) => void;
106
112
  }
107
113
  /**
108
114
  * Query events from relays by arbitrary filter. Uses explicit relays if provided, otherwise the active identity's read relays.
@@ -149,6 +155,8 @@ export declare function paginateQuery(runQuery: (filter: Filter) => Promise<Nost
149
155
  * Validate a relay URL — must be wss:// or ws://, no private networks.
150
156
  *
151
157
  * @param url - The relay WebSocket URL to validate.
158
+ * @param opts - `allowPrivate` skips the private-network check, as the relay pool does when
159
+ * BRAY_ALLOW_PRIVATE_RELAYS=1 (local development). Off by default.
152
160
  * @returns `void` if the URL is acceptable.
153
161
  * @throws {Error} If the scheme is not `wss://` or `ws://`, or if the host resolves to a private
154
162
  * or loopback address (localhost, 127.x, 10.x, 172.16–31.x, 192.168.x, 169.254.169.254, ::1).
@@ -157,12 +165,16 @@ export declare function paginateQuery(runQuery: (filter: Filter) => Promise<Nost
157
165
  * validateRelayUrl('wss://localhost') // throws — private address
158
166
  * validateRelayUrl('http://relay.damus.io') // throws — wrong scheme
159
167
  */
160
- export declare function validateRelayUrl(url: string): void;
168
+ export declare function validateRelayUrl(url: string, opts?: {
169
+ allowPrivate?: boolean;
170
+ }): void;
161
171
  /**
162
172
  * Fetch NIP-11 relay information document.
163
173
  *
164
174
  * @param url - WebSocket URL of the relay (`wss://` or `ws://`). The URL is validated before
165
175
  * the HTTP request is made.
176
+ * @param opts - `allowPrivateRelays` accepts a private-network URL, as the relay pool does when
177
+ * BRAY_ALLOW_PRIVATE_RELAYS=1. Off by default.
166
178
  * @returns Parsed JSON object from the relay's NIP-11 information document. Shape varies per relay
167
179
  * but typically includes `name`, `description`, `pubkey`, `supported_nips`, and `software`.
168
180
  * @throws {Error} If the URL is invalid, the HTTP response is not OK, the document exceeds 1 MiB,
@@ -171,7 +183,9 @@ export declare function validateRelayUrl(url: string): void;
171
183
  * const info = await handleRelayInfo('wss://relay.damus.io')
172
184
  * console.log(info.name, info.supported_nips)
173
185
  */
174
- export declare function handleRelayInfo(url: string): Promise<Record<string, unknown>>;
186
+ export declare function handleRelayInfo(url: string, opts?: {
187
+ allowPrivateRelays?: boolean;
188
+ }): Promise<Record<string, unknown>>;
175
189
  export interface SubscribeResult {
176
190
  /** Resolved once the subscription is closed (SIGINT or manual close). */
177
191
  closed: boolean;
@@ -188,10 +202,14 @@ export interface SubscribeResult {
188
202
  * @param filter - Nostr filter object.
189
203
  * @param onEvent - Callback invoked for each matching event.
190
204
  * @param relayOverrides - Optional explicit relay URLs.
205
+ * @param opts - `onclose` is called once every relay has ended the subscription,
206
+ * with each relay's reason. Stopping it yourself also ends it ("closed by caller").
191
207
  * @returns Async cleanup function.
192
208
  * @example
193
209
  * const stop = await handleSubscribe(pool, npub, { kinds: [1] }, ev => console.log(ev))
194
210
  * // later:
195
211
  * stop()
196
212
  */
197
- export declare function handleSubscribe(pool: RelayPool, npub: string | undefined, filter: Filter, onEvent: (event: NostrEvent) => void, relayOverrides?: string[]): Promise<() => void>;
213
+ export declare function handleSubscribe(pool: RelayPool, npub: string | undefined, filter: Filter, onEvent: (event: NostrEvent) => void, relayOverrides?: string[], opts?: {
214
+ onclose?: (reasons: SubscriptionClose[]) => void;
215
+ }): Promise<() => void>;
@@ -178,10 +178,18 @@ export async function handleRelayQuery(pool, npub, args) {
178
178
  filter.search = args.search;
179
179
  }
180
180
  if (args.relays?.length) {
181
+ // Follow the pool's private-relay rule (BRAY_ALLOW_PRIVATE_RELAYS=1); a pool
182
+ // double without the method stays strict.
183
+ const allowPrivate = pool.allowsPrivateRelays?.() === true;
181
184
  for (const url of args.relays)
182
- validateRelayUrl(url);
185
+ validateRelayUrl(url, { allowPrivate });
183
186
  }
184
- const runQuery = (f) => args.relays?.length ? pool.queryDirect(args.relays, f) : pool.query(npub, f);
187
+ const onclose = args.onRelayClose;
188
+ const runQuery = (f) => {
189
+ if (args.relays?.length)
190
+ return onclose ? pool.queryDirect(args.relays, f, { onclose }) : pool.queryDirect(args.relays, f);
191
+ return onclose ? pool.query(npub, f, { onclose }) : pool.query(npub, f);
192
+ };
185
193
  if (!args.paginate)
186
194
  return runQuery(filter);
187
195
  return paginateQuery(runQuery, filter, {
@@ -249,6 +257,8 @@ export async function paginateQuery(runQuery, baseFilter, opts) {
249
257
  * Validate a relay URL — must be wss:// or ws://, no private networks.
250
258
  *
251
259
  * @param url - The relay WebSocket URL to validate.
260
+ * @param opts - `allowPrivate` skips the private-network check, as the relay pool does when
261
+ * BRAY_ALLOW_PRIVATE_RELAYS=1 (local development). Off by default.
252
262
  * @returns `void` if the URL is acceptable.
253
263
  * @throws {Error} If the scheme is not `wss://` or `ws://`, or if the host resolves to a private
254
264
  * or loopback address (localhost, 127.x, 10.x, 172.16–31.x, 192.168.x, 169.254.169.254, ::1).
@@ -257,7 +267,7 @@ export async function paginateQuery(runQuery, baseFilter, opts) {
257
267
  * validateRelayUrl('wss://localhost') // throws — private address
258
268
  * validateRelayUrl('http://relay.damus.io') // throws — wrong scheme
259
269
  */
260
- export function validateRelayUrl(url) {
270
+ export function validateRelayUrl(url, opts = {}) {
261
271
  if (typeof url !== 'string') {
262
272
  throw new Error('Relay URL must be a string');
263
273
  }
@@ -267,13 +277,16 @@ export function validateRelayUrl(url) {
267
277
  if (!/^wss?:\/\//i.test(url)) {
268
278
  throw new Error('Relay URL must use wss:// or ws:// scheme');
269
279
  }
270
- validatePublicUrl(url);
280
+ if (!opts.allowPrivate)
281
+ validatePublicUrl(url);
271
282
  }
272
283
  /**
273
284
  * Fetch NIP-11 relay information document.
274
285
  *
275
286
  * @param url - WebSocket URL of the relay (`wss://` or `ws://`). The URL is validated before
276
287
  * the HTTP request is made.
288
+ * @param opts - `allowPrivateRelays` accepts a private-network URL, as the relay pool does when
289
+ * BRAY_ALLOW_PRIVATE_RELAYS=1. Off by default.
277
290
  * @returns Parsed JSON object from the relay's NIP-11 information document. Shape varies per relay
278
291
  * but typically includes `name`, `description`, `pubkey`, `supported_nips`, and `software`.
279
292
  * @throws {Error} If the URL is invalid, the HTTP response is not OK, the document exceeds 1 MiB,
@@ -282,8 +295,8 @@ export function validateRelayUrl(url) {
282
295
  * const info = await handleRelayInfo('wss://relay.damus.io')
283
296
  * console.log(info.name, info.supported_nips)
284
297
  */
285
- export async function handleRelayInfo(url) {
286
- validateRelayUrl(url);
298
+ export async function handleRelayInfo(url, opts = {}) {
299
+ validateRelayUrl(url, { allowPrivate: opts.allowPrivateRelays });
287
300
  const httpUrl = url.replace(/^wss:\/\//, 'https://').replace(/^ws:\/\//, 'http://');
288
301
  const response = await fetch(httpUrl, {
289
302
  headers: { Accept: 'application/nostr+json' },
@@ -323,18 +336,20 @@ export async function handleRelayInfo(url) {
323
336
  * @param filter - Nostr filter object.
324
337
  * @param onEvent - Callback invoked for each matching event.
325
338
  * @param relayOverrides - Optional explicit relay URLs.
339
+ * @param opts - `onclose` is called once every relay has ended the subscription,
340
+ * with each relay's reason. Stopping it yourself also ends it ("closed by caller").
326
341
  * @returns Async cleanup function.
327
342
  * @example
328
343
  * const stop = await handleSubscribe(pool, npub, { kinds: [1] }, ev => console.log(ev))
329
344
  * // later:
330
345
  * stop()
331
346
  */
332
- export async function handleSubscribe(pool, npub, filter, onEvent, relayOverrides) {
347
+ export async function handleSubscribe(pool, npub, filter, onEvent, relayOverrides, opts = {}) {
333
348
  const relays = relayOverrides?.length
334
349
  ? relayOverrides
335
350
  : (npub ? pool.getRelays(npub).read : []);
336
351
  if (relays.length === 0) {
337
352
  throw new Error('No relays available. Set NOSTR_RELAYS or pass --relay <url>.');
338
353
  }
339
- return pool.subscribe(relays, filter, onEvent);
354
+ return pool.subscribe(relays, filter, onEvent, opts);
340
355
  }
@@ -127,7 +127,7 @@ export function registerRelayTools(server, deps) {
127
127
  },
128
128
  annotations: { readOnlyHint: true },
129
129
  }, async ({ url }) => {
130
- const info = await handleRelayInfo(url);
130
+ const info = await handleRelayInfo(url, { allowPrivateRelays: deps.pool.allowsPrivateRelays?.() === true });
131
131
  return {
132
132
  content: [{ type: 'text', text: JSON.stringify(info, null, 2) }],
133
133
  };
@@ -26,6 +26,17 @@ export type AuthMode = 'off' | 'on-demand' | 'eager';
26
26
  export interface Subscription {
27
27
  close(): void;
28
28
  }
29
+ /** Why one relay ended a subscription: its CLOSED reason, or the connection's fate. */
30
+ export interface SubscriptionClose {
31
+ url: string;
32
+ reason: string;
33
+ }
34
+ /**
35
+ * Whether a relay ended a REQ in the ordinary way: at EOSE (nostr-tools closes
36
+ * a one-shot query itself then) or because the caller closed it. Anything else
37
+ * is the relay's CLOSED reason or a connection failure.
38
+ */
39
+ export declare function isNormalRequestEnd(reason: string): boolean;
29
40
  /** Params threaded through to nostr-tools: deadlines plus NIP-42 auth retry. */
30
41
  export interface PoolParams {
31
42
  maxWait?: number;
@@ -39,7 +50,13 @@ export interface PoolLike {
39
50
  subscribeMany?(relays: string[], filter: Filter, handlers: {
40
51
  onevent(event: NostrEvent): void;
41
52
  oneose?(): void;
53
+ onclose?(reasons: SubscriptionClose[]): void;
42
54
  } & Pick<PoolParams, 'onauth'>): Subscription;
55
+ /** A REQ that closes itself at EOSE, reporting each relay's reason. Absent on injected test doubles. */
56
+ subscribeEose?(relays: string[], filter: Filter, handlers: {
57
+ onevent(event: NostrEvent): void;
58
+ onclose(reasons: SubscriptionClose[]): void;
59
+ } & PoolParams): Subscription;
43
60
  ensureRelay?(url: string, params?: {
44
61
  connectionTimeout?: number;
45
62
  abort?: AbortSignal;
@@ -109,6 +126,11 @@ export declare class RelayPool {
109
126
  constructor(config: RelayPoolConfig, injectedPool?: PoolLike);
110
127
  /** Store relay set for an identity and flush any queued writes */
111
128
  reconfigure(npub: string, relays: RelaySet): void;
129
+ /**
130
+ * Whether private-network relay URLs are accepted (BRAY_ALLOW_PRIVATE_RELAYS=1),
131
+ * so handlers that validate a URL before reaching the pool apply the same rule.
132
+ */
133
+ allowsPrivateRelays(): boolean;
112
134
  /** Get relay set for an identity, falling back to defaults */
113
135
  getRelays(npub: string): RelaySet;
114
136
  /**
@@ -134,14 +156,30 @@ export declare class RelayPool {
134
156
  timeoutMs?: number;
135
157
  signal?: AbortSignal;
136
158
  }): Promise<PublishResult>;
137
- /** Live subscription — calls onEvent for each matching event until the returned function is called. */
138
- subscribe(relays: string[], filter: Filter, onEvent: (event: NostrEvent) => void): Promise<() => void>;
139
- /** One-shot query from read relays for the given identity */
140
- query(npub: string, filter: Filter): Promise<NostrEvent[]>;
141
- /** One-shot query against explicit relay URLs (not identity-bound) */
159
+ /**
160
+ * Live subscription — calls onEvent for each matching event until the returned function is called.
161
+ *
162
+ * `onclose` is called once every relay has ended the subscription, with each
163
+ * relay's reason (auth failures explained as for a publish). Closing it with
164
+ * the returned function also ends it, with the reason "closed by caller".
165
+ */
166
+ subscribe(relays: string[], filter: Filter, onEvent: (event: NostrEvent) => void, opts?: {
167
+ onclose?: (reasons: SubscriptionClose[]) => void;
168
+ }): Promise<() => void>;
169
+ /**
170
+ * One-shot query from read relays for the given identity.
171
+ *
172
+ * `onclose`, if given, receives each relay's reason for ending the REQ; see
173
+ * {@link isNormalRequestEnd}. Without it a relay's refusal looks like no events.
174
+ */
175
+ query(npub: string, filter: Filter, opts?: {
176
+ onclose?: (reasons: SubscriptionClose[]) => void;
177
+ }): Promise<NostrEvent[]>;
178
+ /** One-shot query against explicit relay URLs (not identity-bound). `onclose` as for {@link query}. */
142
179
  queryDirect(relays: string[], filter: Filter, opts?: {
143
180
  timeoutMs?: number;
144
181
  signal?: AbortSignal;
182
+ onclose?: (reasons: SubscriptionClose[]) => void;
145
183
  }): Promise<NostrEvent[]>;
146
184
  /** Reconcile local event IDs with one relay using NIP-77 Negentropy. */
147
185
  reconcileDirect(relayUrl: string, items: Array<{
@@ -4,12 +4,28 @@ import { brayFetch } from './http-client.js';
4
4
  // pushing 100 MB EVENTs that would exhaust memory (ws library defaults to
5
5
  // 100 MB maxPayload, which is far more than any legitimate Nostr event).
6
6
  const WS_MAX_PAYLOAD = 512 * 1024;
7
+ /**
8
+ * Whether a relay ended a REQ in the ordinary way: at EOSE (nostr-tools closes
9
+ * a one-shot query itself then) or because the caller closed it. Anything else
10
+ * is the relay's CLOSED reason or a connection failure.
11
+ */
12
+ export function isNormalRequestEnd(reason) {
13
+ return reason === 'closed automatically on eose' || reason === 'closed by caller';
14
+ }
7
15
  export class Nip77UnavailableError extends Error {
8
16
  constructor(message) {
9
17
  super(message);
10
18
  this.name = 'Nip77UnavailableError';
11
19
  }
12
20
  }
21
+ /**
22
+ * Whether a resolved per-relay publish result is nostr-tools' report that it
23
+ * could not connect ("connection failure: ..."), which it resolves with instead
24
+ * of rejecting. Any other resolved value is the relay's OK message.
25
+ */
26
+ function isConnectionFailure(value) {
27
+ return typeof value === 'string' && value.startsWith('connection failure: ');
28
+ }
13
29
  /**
14
30
  * Summarise a publish attempt into the two boolean flags on {@link PublishResult}.
15
31
  *
@@ -43,6 +59,9 @@ async function createRealPool(torProxy) {
43
59
  const WebSocketImpl = webSocketFor(torProxy, { maxPayload: WS_MAX_PAYLOAD });
44
60
  useWebSocketImplementation(WebSocketImpl);
45
61
  const pool = new SimplePool({ websocketImplementation: WebSocketImpl });
62
+ // The pool's relay map is protected in nostr-tools' types; the eager guard
63
+ // needs the relay that `automaticallyAuth` is being asked about.
64
+ const relayMap = pool.relays;
46
65
  return {
47
66
  // `onauth` is spread straight through to the subscription params by
48
67
  // querySync/subscribeEose, so it works despite not being in querySync's
@@ -50,11 +69,50 @@ async function createRealPool(torProxy) {
50
69
  publish: (relays, event, params) => pool.publish(relays, event, params),
51
70
  querySync: (relays, filter, params) => pool.querySync(relays, filter, params),
52
71
  subscribeMany: (relays, filters, handlers) => pool.subscribeMany(relays, filters, handlers),
72
+ subscribeEose: (relays, filter, handlers) => pool.subscribeEose(relays, filter, handlers),
53
73
  ensureRelay: (url, params) => pool.ensureRelay(url, params),
54
- setAutomaticAuth: signer => { pool.automaticallyAuth = signer; },
74
+ setAutomaticAuth: signerFor => {
75
+ // nostr-tools calls this from ensureRelay, before the relay connects, so
76
+ // the guard is in place before any challenge can arrive.
77
+ ;
78
+ pool.automaticallyAuth = signerFor && ((url) => {
79
+ const sign = signerFor(url);
80
+ const relay = sign ? relayMap.get(url) : undefined;
81
+ if (relay)
82
+ guardAutomaticAuth(relay);
83
+ return sign;
84
+ });
85
+ },
55
86
  destroy: () => pool.destroy(),
56
87
  };
57
88
  }
89
+ const guardedRelays = new WeakSet();
90
+ /**
91
+ * Keep a refused eager AUTH from ending the process.
92
+ *
93
+ * nostr-tools answers a relay's challenge with `this.auth(this.onauth)` and
94
+ * rethrows any refusal from that promise's `.catch`, where nothing can handle
95
+ * it, so Node exits on the unhandled rejection. In eager mode a relay that
96
+ * refuses the AUTH (a members-only relay, a key it does not know, an AUTH that
97
+ * names another URL) therefore crashed the CLI, even when the relay would have
98
+ * served the operation without it. The MCP server uses the same pool and
99
+ * installs no unhandledRejection handler, so it is exposed in the same way.
100
+ *
101
+ * Only the automatic answer is quietened: it is the one call made with the
102
+ * relay's own `onauth`. `auth()` keeps its first attempt, so an operation that
103
+ * then needs auth (the on-demand retry) still receives the relay's refusal and
104
+ * reports it.
105
+ */
106
+ function guardAutomaticAuth(relay) {
107
+ if (guardedRelays.has(relay))
108
+ return;
109
+ guardedRelays.add(relay);
110
+ const auth = relay.auth.bind(relay);
111
+ relay.auth = signer => {
112
+ const attempt = auth(signer);
113
+ return signer === relay.onauth ? attempt.catch(() => '') : attempt;
114
+ };
115
+ }
58
116
  export class RelayPool {
59
117
  pool;
60
118
  poolReady;
@@ -139,6 +197,13 @@ export class RelayPool {
139
197
  this.relaySets.set(npub, relays);
140
198
  void this.flushQueue(npub);
141
199
  }
200
+ /**
201
+ * Whether private-network relay URLs are accepted (BRAY_ALLOW_PRIVATE_RELAYS=1),
202
+ * so handlers that validate a URL before reaching the pool apply the same rule.
203
+ */
204
+ allowsPrivateRelays() {
205
+ return this.allowPrivateRelays;
206
+ }
142
207
  /** Get relay set for an identity, falling back to defaults */
143
208
  getRelays(npub) {
144
209
  return this.relaySets.get(npub) ?? this.defaults;
@@ -180,8 +245,14 @@ export class RelayPool {
180
245
  pool.setAutomaticAuth(undefined);
181
246
  return;
182
247
  }
183
- pool.setAutomaticAuth(() => this.#signAuth);
248
+ pool.setAutomaticAuth(() => this.#eagerSignAuth);
184
249
  }
250
+ /**
251
+ * The eager responder's signer. It signs exactly as {@link #signAuth} does,
252
+ * but is a separate function so the pool can tell nostr-tools' automatic
253
+ * answer to a challenge apart from an operation's own on-demand AUTH.
254
+ */
255
+ #eagerSignAuth = (evt) => this.#signAuth(evt);
185
256
  /**
186
257
  * Bound signer handed to nostr-tools. Records which relays were authenticated
187
258
  * to so callers can tell whether a query identified them.
@@ -277,7 +348,13 @@ export class RelayPool {
277
348
  for (let i = 0; i < results.length; i++) {
278
349
  const result = results[i];
279
350
  const url = relayUrls[i] ?? `relay-${i}`;
280
- if (result.status === 'fulfilled') {
351
+ if (result.status === 'fulfilled' && isConnectionFailure(result.value)) {
352
+ // nostr-tools resolves, rather than rejects, a publish whose relay it
353
+ // could not connect to: the event never left this machine.
354
+ rejected.push(url);
355
+ errors.push(`${url}: ${result.value}`);
356
+ }
357
+ else if (result.status === 'fulfilled') {
281
358
  accepted.push(url);
282
359
  }
283
360
  else {
@@ -292,29 +369,73 @@ export class RelayPool {
292
369
  errors,
293
370
  };
294
371
  }
295
- /** Live subscription — calls onEvent for each matching event until the returned function is called. */
296
- async subscribe(relays, filter, onEvent) {
372
+ /**
373
+ * Live subscription — calls onEvent for each matching event until the returned function is called.
374
+ *
375
+ * `onclose` is called once every relay has ended the subscription, with each
376
+ * relay's reason (auth failures explained as for a publish). Closing it with
377
+ * the returned function also ends it, with the reason "closed by caller".
378
+ */
379
+ async subscribe(relays, filter, onEvent, opts = {}) {
297
380
  this.#validateDirectRelays(relays);
298
381
  const pool = await this.poolReady;
299
382
  if (!pool.subscribeMany) {
300
383
  throw new Error('The underlying pool does not support subscriptions. Ensure nostr-tools/pool is available.');
301
384
  }
302
- const sub = pool.subscribeMany(relays, filter, { onevent: onEvent, ...this.#authParams() });
385
+ const { onclose } = opts;
386
+ const sub = pool.subscribeMany(relays, filter, {
387
+ onevent: onEvent,
388
+ ...(onclose ? {
389
+ onclose: (reasons) => onclose(reasons.map(({ url, reason }) => ({ url, reason: this.#annotateAuthError(reason) }))),
390
+ } : {}),
391
+ ...this.#authParams(),
392
+ });
303
393
  return () => sub.close();
304
394
  }
305
- /** One-shot query from read relays for the given identity */
306
- async query(npub, filter) {
395
+ /**
396
+ * One-shot query from read relays for the given identity.
397
+ *
398
+ * `onclose`, if given, receives each relay's reason for ending the REQ; see
399
+ * {@link isNormalRequestEnd}. Without it a relay's refusal looks like no events.
400
+ */
401
+ async query(npub, filter, opts = {}) {
307
402
  const pool = await this.poolReady;
308
403
  const relays = this.getRelays(npub);
309
- return pool.querySync(relays.read, filter, this.#authParams());
404
+ return this.#query(pool, relays.read, filter, this.#authParams(), opts.onclose);
310
405
  }
311
- /** One-shot query against explicit relay URLs (not identity-bound) */
406
+ /** One-shot query against explicit relay URLs (not identity-bound). `onclose` as for {@link query}. */
312
407
  async queryDirect(relays, filter, opts = {}) {
313
408
  this.#validateDirectRelays(relays);
314
409
  const pool = await this.poolReady;
315
- return opts.timeoutMs || opts.signal
316
- ? pool.querySync(relays, filter, { maxWait: opts.timeoutMs, abort: opts.signal, ...this.#authParams() })
317
- : pool.querySync(relays, filter, this.#authParams());
410
+ const params = opts.timeoutMs || opts.signal
411
+ ? { maxWait: opts.timeoutMs, abort: opts.signal, ...this.#authParams() }
412
+ : this.#authParams();
413
+ return this.#query(pool, relays, filter, params, opts.onclose);
414
+ }
415
+ /**
416
+ * querySync, except that it settles at once for no relays (querySync never
417
+ * does, so a query with nothing to ask hung) and, given `onclose`, reports
418
+ * each relay's reason for ending the REQ, which querySync drops.
419
+ */
420
+ #query(pool, relays, filter, params, onclose) {
421
+ if (relays.length === 0) {
422
+ onclose?.([]);
423
+ return Promise.resolve([]);
424
+ }
425
+ const subscribeEose = pool.subscribeEose;
426
+ if (!onclose || !subscribeEose)
427
+ return pool.querySync(relays, filter, params);
428
+ return new Promise(resolve => {
429
+ const events = [];
430
+ subscribeEose(relays, filter, {
431
+ ...params,
432
+ onevent: event => { events.push(event); },
433
+ onclose: reasons => {
434
+ onclose(reasons.map(({ url, reason }) => ({ url, reason: this.#annotateAuthError(reason) })));
435
+ resolve(events);
436
+ },
437
+ });
438
+ });
318
439
  }
319
440
  /** Reconcile local event IDs with one relay using NIP-77 Negentropy. */
320
441
  async reconcileDirect(relayUrl, items, filter, opts = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nostr-bray",
3
- "version": "3.11.0",
3
+ "version": "3.12.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",
@@ -180,7 +180,7 @@
180
180
  "farrier-kit": "1.1.3",
181
181
  "nostr-attestations": "^3.0.1",
182
182
  "nostr-tools": "2.24.1",
183
- "nostr-veil": "^0.32.0",
183
+ "nostr-veil": "^0.34.0",
184
184
  "nsec-tree": "^1.4.2",
185
185
  "signet-protocol": "^1.1.0",
186
186
  "socks-proxy-agent": "^10.0.0",