nostr-bray 3.11.0 → 3.12.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.
@@ -17,6 +17,7 @@ import { SimplePool } from 'nostr-tools/pool';
17
17
  import { generateSecretKey, finalizeEvent } from 'nostr-tools/pure';
18
18
  import { npubEncode } from 'nostr-tools/nip19';
19
19
  import { webSocketFor } from './ws-safe.js';
20
+ import { setAutomaticAuth } from './nostr-tools-guards.js';
20
21
  import { readStateFile, writeStateFile } from './state.js';
21
22
  /** Bound the NIP-46 connect handshake. nostr-tools' BunkerSigner has no
22
23
  * per-request timeout, so an offline signer or unreachable relays make the
@@ -139,7 +140,8 @@ export class BunkerContext {
139
140
  // relays that only let a key read messages addressed to it still work.
140
141
  // Its own WebSocket class, so TOR_PROXY applies to signer traffic too.
141
142
  const pool = new SimplePool({ websocketImplementation: webSocketFor(options.torProxy) });
142
- pool.automaticallyAuth = () => async (template) => finalizeEvent(template, clientSk);
143
+ const answerChallenge = async (template) => finalizeEvent(template, clientSk);
144
+ setAutomaticAuth(pool, () => answerChallenge);
143
145
  const signer = BunkerSigner.fromBunker(clientSk, {
144
146
  pubkey: config.pubkey,
145
147
  relays: config.relays,
@@ -24,6 +24,7 @@ import { CLIENT_NAME, CLIENT_KEYS_FILE, REQUEST_TIMEOUT_MS, TimeoutError, withTi
24
24
  import { readStateFile, writeStateFile } from './state.js';
25
25
  import { isOnionUrl, validateRelayScheme } from './validation.js';
26
26
  import { webSocketFor } from './ws-safe.js';
27
+ import { setAutomaticAuth } from './nostr-tools-guards.js';
27
28
  /** Saved by `bunker connect` and `bunker pair`; read by loadConfig. */
28
29
  export const BUNKER_URI_FILE = 'bunker-uri';
29
30
  /** NIP-46 request and response events. */
@@ -74,7 +75,8 @@ export async function pairWithNostrConnect(options) {
74
75
  // Answer NIP-42 challenges with the client key, as BunkerContext does.
75
76
  // With TOR_PROXY set, pairing goes through the proxy like bray's other relay traffic.
76
77
  const pool = new SimplePool({ websocketImplementation: webSocketFor(options.torProxy) });
77
- pool.automaticallyAuth = () => async (template) => finalizeEvent(template, clientSk);
78
+ const answerChallenge = async (template) => finalizeEvent(template, clientSk);
79
+ setAutomaticAuth(pool, () => answerChallenge);
78
80
  const timeoutMs = options.timeoutMs ?? PAIR_TIMEOUT_MS;
79
81
  let timer;
80
82
  let sub;
package/dist/bunker.js CHANGED
@@ -15,6 +15,7 @@ import { finalizeEvent, getPublicKey, generateSecretKey } from 'nostr-tools/pure
15
15
  import { npubEncode } from 'nostr-tools/nip19';
16
16
  import { SimplePool } from 'nostr-tools/pool';
17
17
  import { webSocketFor } from './ws-safe.js';
18
+ import { isConnectionFailure, setAutomaticAuth } from './nostr-tools-guards.js';
18
19
  import { readStateFile, readStateFileStrict, writeStateFile } from './state.js';
19
20
  /**
20
21
  * Remove a client pubkey from every bunker key's approvals in
@@ -112,7 +113,8 @@ export function startBunker(opts) {
112
113
  // Sign in (NIP-42) with the bunker key when a relay asks, so a private
113
114
  // relay lets the bunker read requests addressed to it.
114
115
  const pool = new SimplePool({ websocketImplementation: webSocketFor(opts.torProxy) });
115
- pool.automaticallyAuth = () => async (template) => finalizeEvent(template, bunkerSk);
116
+ const answerChallenge = async (template) => finalizeEvent(template, bunkerSk);
117
+ setAutomaticAuth(pool, () => answerChallenge);
116
118
  // Subscribe to kind 24133 events addressed to us
117
119
  const sub = pool.subscribeMany(relays, { kinds: [24133], '#p': [bunkerPk] }, {
118
120
  onevent: async (event) => {
@@ -349,7 +351,21 @@ export function startBunker(opts) {
349
351
  tags: [['p', clientPk]],
350
352
  content: encrypted,
351
353
  }, bunkerSk);
352
- await Promise.any(pool.publish(relays, responseEvent));
354
+ // nostr-tools resolves a publish to a relay it cannot reach with
355
+ // "connection failure: ...", which is not delivery.
356
+ const deliveries = pool.publish(relays, responseEvent).map(p => p.then(reason => {
357
+ if (isConnectionFailure(reason))
358
+ throw new Error(reason);
359
+ return reason;
360
+ }));
361
+ try {
362
+ await Promise.any(deliveries);
363
+ }
364
+ catch (e) {
365
+ const reasons = e instanceof AggregateError ? e.errors.map(err => err instanceof Error ? err.message : String(err)) : [String(e)];
366
+ log(`Response ${id} not delivered: ${reasons.join('; ')}`);
367
+ return;
368
+ }
353
369
  log(`Response ${id}: ${error ?? 'ok'}`);
354
370
  }
355
371
  // Build bunker:// URI
@@ -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)
@@ -0,0 +1,22 @@
1
+ import type { EventTemplate, VerifiedEvent } from 'nostr-tools';
2
+ /**
3
+ * Guards for two nostr-tools (2.24) behaviours that otherwise mislead or crash
4
+ * bray. Every pool bray creates goes through these: the relay pool, the bunker
5
+ * daemon, the bunker client and bunker pairing.
6
+ */
7
+ /** Signs a NIP-42 kind 22242 template for one relay. */
8
+ export type ChallengeSigner = (evt: EventTemplate) => Promise<VerifiedEvent>;
9
+ /**
10
+ * Have a nostr-tools SimplePool answer every relay's NIP-42 challenge as it
11
+ * arrives, with each answer guarded as above. `signerFor` returns the signer
12
+ * for a relay URL, or null to leave that relay unanswered; `undefined` stops
13
+ * answering. Use this rather than setting `pool.automaticallyAuth`.
14
+ */
15
+ export declare function setAutomaticAuth(pool: object, signerFor: ((relayUrl: string) => ChallengeSigner | null) | undefined): void;
16
+ /**
17
+ * Whether a resolved per-relay publish result is nostr-tools' report that it
18
+ * could not connect ("connection failure: ..."), which it resolves with instead
19
+ * of rejecting: the event never left this machine. Any other resolved value is
20
+ * the relay's OK message.
21
+ */
22
+ export declare function isConnectionFailure(value: unknown): boolean;
@@ -0,0 +1,55 @@
1
+ const guardedRelays = new WeakSet();
2
+ /**
3
+ * Keep a refused automatic AUTH from ending the process.
4
+ *
5
+ * nostr-tools answers a relay's challenge with `this.auth(this.onauth)` and
6
+ * rethrows any refusal from that promise's `.catch`, where nothing can handle
7
+ * it, so Node exits on the unhandled rejection. A relay that refuses the AUTH
8
+ * (a members-only relay, a key it does not know, an AUTH that names another URL)
9
+ * therefore crashed the CLI, even when the relay would have served the operation
10
+ * without it; the bunker daemon, the bunker client and the MCP server answer
11
+ * challenges the same way and were exposed alike.
12
+ *
13
+ * Only the automatic answer is quietened: it is the one call made with the
14
+ * relay's own `onauth`. `auth()` keeps its first attempt, so an operation that
15
+ * then needs auth (the on-demand retry) still receives the relay's refusal and
16
+ * reports it.
17
+ */
18
+ function guardAutomaticAuth(relay) {
19
+ if (guardedRelays.has(relay))
20
+ return;
21
+ guardedRelays.add(relay);
22
+ const auth = relay.auth.bind(relay);
23
+ relay.auth = signer => {
24
+ const attempt = auth(signer);
25
+ return signer === relay.onauth ? attempt.catch(() => '') : attempt;
26
+ };
27
+ }
28
+ /**
29
+ * Have a nostr-tools SimplePool answer every relay's NIP-42 challenge as it
30
+ * arrives, with each answer guarded as above. `signerFor` returns the signer
31
+ * for a relay URL, or null to leave that relay unanswered; `undefined` stops
32
+ * answering. Use this rather than setting `pool.automaticallyAuth`.
33
+ */
34
+ export function setAutomaticAuth(pool, signerFor) {
35
+ // The relay map is protected in nostr-tools' types. nostr-tools calls
36
+ // automaticallyAuth from ensureRelay once the relay is in the map and before
37
+ // it connects, so the guard is in place before any challenge can arrive.
38
+ const relays = pool.relays;
39
+ pool.automaticallyAuth = signerFor && ((url) => {
40
+ const sign = signerFor(url);
41
+ const relay = sign ? relays.get(url) : undefined;
42
+ if (relay)
43
+ guardAutomaticAuth(relay);
44
+ return sign;
45
+ });
46
+ }
47
+ /**
48
+ * Whether a resolved per-relay publish result is nostr-tools' report that it
49
+ * could not connect ("connection failure: ..."), which it resolves with instead
50
+ * of rejecting: the event never left this machine. Any other resolved value is
51
+ * the relay's OK message.
52
+ */
53
+ export function isConnectionFailure(value) {
54
+ return typeof value === 'string' && value.startsWith('connection failure: ');
55
+ }
@@ -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<{
@@ -1,9 +1,18 @@
1
1
  import { validatePublicUrl, validateRelayScheme } from './validation.js';
2
2
  import { brayFetch } from './http-client.js';
3
+ import { isConnectionFailure, setAutomaticAuth } from './nostr-tools-guards.js';
3
4
  // 512 KiB cap on any inbound relay frame. Protects against malicious relays
4
5
  // pushing 100 MB EVENTs that would exhaust memory (ws library defaults to
5
6
  // 100 MB maxPayload, which is far more than any legitimate Nostr event).
6
7
  const WS_MAX_PAYLOAD = 512 * 1024;
8
+ /**
9
+ * Whether a relay ended a REQ in the ordinary way: at EOSE (nostr-tools closes
10
+ * a one-shot query itself then) or because the caller closed it. Anything else
11
+ * is the relay's CLOSED reason or a connection failure.
12
+ */
13
+ export function isNormalRequestEnd(reason) {
14
+ return reason === 'closed automatically on eose' || reason === 'closed by caller';
15
+ }
7
16
  export class Nip77UnavailableError extends Error {
8
17
  constructor(message) {
9
18
  super(message);
@@ -50,8 +59,9 @@ async function createRealPool(torProxy) {
50
59
  publish: (relays, event, params) => pool.publish(relays, event, params),
51
60
  querySync: (relays, filter, params) => pool.querySync(relays, filter, params),
52
61
  subscribeMany: (relays, filters, handlers) => pool.subscribeMany(relays, filters, handlers),
62
+ subscribeEose: (relays, filter, handlers) => pool.subscribeEose(relays, filter, handlers),
53
63
  ensureRelay: (url, params) => pool.ensureRelay(url, params),
54
- setAutomaticAuth: signer => { pool.automaticallyAuth = signer; },
64
+ setAutomaticAuth: signerFor => setAutomaticAuth(pool, signerFor),
55
65
  destroy: () => pool.destroy(),
56
66
  };
57
67
  }
@@ -139,6 +149,13 @@ export class RelayPool {
139
149
  this.relaySets.set(npub, relays);
140
150
  void this.flushQueue(npub);
141
151
  }
152
+ /**
153
+ * Whether private-network relay URLs are accepted (BRAY_ALLOW_PRIVATE_RELAYS=1),
154
+ * so handlers that validate a URL before reaching the pool apply the same rule.
155
+ */
156
+ allowsPrivateRelays() {
157
+ return this.allowPrivateRelays;
158
+ }
142
159
  /** Get relay set for an identity, falling back to defaults */
143
160
  getRelays(npub) {
144
161
  return this.relaySets.get(npub) ?? this.defaults;
@@ -180,8 +197,14 @@ export class RelayPool {
180
197
  pool.setAutomaticAuth(undefined);
181
198
  return;
182
199
  }
183
- pool.setAutomaticAuth(() => this.#signAuth);
200
+ pool.setAutomaticAuth(() => this.#eagerSignAuth);
184
201
  }
202
+ /**
203
+ * The eager responder's signer. It signs exactly as {@link #signAuth} does,
204
+ * but is a separate function so the pool can tell nostr-tools' automatic
205
+ * answer to a challenge apart from an operation's own on-demand AUTH.
206
+ */
207
+ #eagerSignAuth = (evt) => this.#signAuth(evt);
185
208
  /**
186
209
  * Bound signer handed to nostr-tools. Records which relays were authenticated
187
210
  * to so callers can tell whether a query identified them.
@@ -277,7 +300,13 @@ export class RelayPool {
277
300
  for (let i = 0; i < results.length; i++) {
278
301
  const result = results[i];
279
302
  const url = relayUrls[i] ?? `relay-${i}`;
280
- if (result.status === 'fulfilled') {
303
+ if (result.status === 'fulfilled' && isConnectionFailure(result.value)) {
304
+ // nostr-tools resolves, rather than rejects, a publish whose relay it
305
+ // could not connect to: the event never left this machine.
306
+ rejected.push(url);
307
+ errors.push(`${url}: ${result.value}`);
308
+ }
309
+ else if (result.status === 'fulfilled') {
281
310
  accepted.push(url);
282
311
  }
283
312
  else {
@@ -292,29 +321,73 @@ export class RelayPool {
292
321
  errors,
293
322
  };
294
323
  }
295
- /** Live subscription — calls onEvent for each matching event until the returned function is called. */
296
- async subscribe(relays, filter, onEvent) {
324
+ /**
325
+ * Live subscription — calls onEvent for each matching event until the returned function is called.
326
+ *
327
+ * `onclose` is called once every relay has ended the subscription, with each
328
+ * relay's reason (auth failures explained as for a publish). Closing it with
329
+ * the returned function also ends it, with the reason "closed by caller".
330
+ */
331
+ async subscribe(relays, filter, onEvent, opts = {}) {
297
332
  this.#validateDirectRelays(relays);
298
333
  const pool = await this.poolReady;
299
334
  if (!pool.subscribeMany) {
300
335
  throw new Error('The underlying pool does not support subscriptions. Ensure nostr-tools/pool is available.');
301
336
  }
302
- const sub = pool.subscribeMany(relays, filter, { onevent: onEvent, ...this.#authParams() });
337
+ const { onclose } = opts;
338
+ const sub = pool.subscribeMany(relays, filter, {
339
+ onevent: onEvent,
340
+ ...(onclose ? {
341
+ onclose: (reasons) => onclose(reasons.map(({ url, reason }) => ({ url, reason: this.#annotateAuthError(reason) }))),
342
+ } : {}),
343
+ ...this.#authParams(),
344
+ });
303
345
  return () => sub.close();
304
346
  }
305
- /** One-shot query from read relays for the given identity */
306
- async query(npub, filter) {
347
+ /**
348
+ * One-shot query from read relays for the given identity.
349
+ *
350
+ * `onclose`, if given, receives each relay's reason for ending the REQ; see
351
+ * {@link isNormalRequestEnd}. Without it a relay's refusal looks like no events.
352
+ */
353
+ async query(npub, filter, opts = {}) {
307
354
  const pool = await this.poolReady;
308
355
  const relays = this.getRelays(npub);
309
- return pool.querySync(relays.read, filter, this.#authParams());
356
+ return this.#query(pool, relays.read, filter, this.#authParams(), opts.onclose);
310
357
  }
311
- /** One-shot query against explicit relay URLs (not identity-bound) */
358
+ /** One-shot query against explicit relay URLs (not identity-bound). `onclose` as for {@link query}. */
312
359
  async queryDirect(relays, filter, opts = {}) {
313
360
  this.#validateDirectRelays(relays);
314
361
  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());
362
+ const params = opts.timeoutMs || opts.signal
363
+ ? { maxWait: opts.timeoutMs, abort: opts.signal, ...this.#authParams() }
364
+ : this.#authParams();
365
+ return this.#query(pool, relays, filter, params, opts.onclose);
366
+ }
367
+ /**
368
+ * querySync, except that it settles at once for no relays (querySync never
369
+ * does, so a query with nothing to ask hung) and, given `onclose`, reports
370
+ * each relay's reason for ending the REQ, which querySync drops.
371
+ */
372
+ #query(pool, relays, filter, params, onclose) {
373
+ if (relays.length === 0) {
374
+ onclose?.([]);
375
+ return Promise.resolve([]);
376
+ }
377
+ const subscribeEose = pool.subscribeEose;
378
+ if (!onclose || !subscribeEose)
379
+ return pool.querySync(relays, filter, params);
380
+ return new Promise(resolve => {
381
+ const events = [];
382
+ subscribeEose(relays, filter, {
383
+ ...params,
384
+ onevent: event => { events.push(event); },
385
+ onclose: reasons => {
386
+ onclose(reasons.map(({ url, reason }) => ({ url, reason: this.#annotateAuthError(reason) })));
387
+ resolve(events);
388
+ },
389
+ });
390
+ });
318
391
  }
319
392
  /** Reconcile local event IDs with one relay using NIP-77 Negentropy. */
320
393
  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.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",
@@ -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",