nostr-bray 3.10.1 → 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.
package/README.md CHANGED
@@ -243,7 +243,9 @@ Create `~/.config/bray/config.json` (or `~/.nostr/bray.json`):
243
243
  {
244
244
  "bunkerUriFile": "/Users/you/.nostr/bunker-uri",
245
245
  "relays": ["wss://relay.damus.io", "wss://nos.lol"],
246
- "trustMode": "annotate"
246
+ "trustMode": "annotate",
247
+ "veilTrustedCircles": ["<64 lowercase hex circle ID>"],
248
+ "veilTrustedPublishers": ["npub1... or 64 hex"]
247
249
  }
248
250
  ```
249
251
 
@@ -251,6 +253,8 @@ Secrets are referenced by **file path** (`bunkerUriFile`, `secretKeyFile`, `nwcU
251
253
 
252
254
  `trustMode` is `strict` (hide content from untrusted pubkeys), `annotate` (show trust scores) or `off` (no filtering). The default is `annotate`; an unrecognised value falls back to `annotate`. The `TRUST_MODE` environment variable overrides the config file.
253
255
 
256
+ `veilTrustedCircles` lists circle IDs (64 lowercase hex, from `computeCircleId`) whose ring proofs count towards Veil trust scores. `veilTrustedPublishers` lists pubkeys (hex or npub) whose assertions and ring proofs count, as if you followed them. Your own follows always count. `VEIL_TRUSTED_CIRCLES` and `VEIL_TRUSTED_PUBLISHERS` take comma-separated lists, merged with the file; an invalid entry stops startup. See [docs/trust-scoring.md](docs/trust-scoring.md).
257
+
254
258
  Search order: `BRAY_CONFIG` env var > `$XDG_CONFIG_HOME/bray/config.json` > `~/.nostr/bray.json`.
255
259
 
256
260
  ### Environment variables
@@ -277,6 +281,8 @@ Search order: `BRAY_CONFIG` env var > `$XDG_CONFIG_HOME/bray/config.json` > `~/.
277
281
  | `TOR_PROXY` | SOCKS5h proxy for Tor; covers relay traffic, NIP-46 signer traffic and the bunker daemon |
278
282
  | `NIP04_ENABLED` | Set `1` to enable legacy NIP-04 DMs |
279
283
  | `TRUST_MODE` | `strict`, `annotate` (default) or `off`. See the config file section above |
284
+ | `VEIL_TRUSTED_CIRCLES` | Comma-separated circle IDs (64 lowercase hex) whose Veil ring proofs count. Merged with `veilTrustedCircles` |
285
+ | `VEIL_TRUSTED_PUBLISHERS` | Comma-separated npubs or hex whose Veil assertions and ring proofs count. Merged with `veilTrustedPublishers` |
280
286
  | `TRANSPORT` | `stdio` (default) or `http` |
281
287
  | `PORT` | HTTP port (default 3000) |
282
288
  | `BIND_ADDRESS` | HTTP bind address (default `127.0.0.1`) |
@@ -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)
package/dist/config.d.ts CHANGED
@@ -38,6 +38,10 @@ interface ConfigFile {
38
38
  dispatchIdentities?: string;
39
39
  /** Public keys this process must never sign as. See ContextOptions. */
40
40
  forbidPubkeys?: string[];
41
+ /** Circle IDs (64 lowercase hex) whose Veil ring proofs count towards trust scores. */
42
+ veilTrustedCircles?: string[];
43
+ /** Pubkeys (hex or npub) whose Veil assertions and ring proofs count towards trust scores. */
44
+ veilTrustedPublishers?: string[];
41
45
  /** Register the tools that mint spending connections (wallet-grant, wallet-refill, wallet-serve). */
42
46
  walletService?: boolean;
43
47
  }
package/dist/config.js CHANGED
@@ -56,6 +56,49 @@ function validateTorRelays(relays, torProxy, allowClearnet) {
56
56
  throw new Error(`Clearnet relays not allowed with Tor proxy (set ALLOW_CLEARNET_WITH_TOR=1 to override): ${clearnet.join(', ')}`);
57
57
  }
58
58
  }
59
+ /**
60
+ * Merge a comma-separated environment list with a config file list. An entry
61
+ * that fails validation is a startup error: a misconfigured trust allowlist
62
+ * must not quietly fail open or closed.
63
+ */
64
+ function mergeList(envValue, fileValue) {
65
+ return [...(envValue ?? '').split(','), ...(fileValue ?? [])]
66
+ .map(s => String(s).trim())
67
+ .filter(Boolean);
68
+ }
69
+ /** Circle IDs are the 64-char lowercase hex SHA-256 from computeCircleId. */
70
+ function parseTrustedCircles(raw) {
71
+ for (const id of raw) {
72
+ if (!HEX_RE.test(id)) {
73
+ throw new Error(`veilTrustedCircles entry "${id}" is not a circle ID: expected 64 lowercase hex characters`);
74
+ }
75
+ }
76
+ return [...new Set(raw)];
77
+ }
78
+ /** Trusted publishers may be hex or npub; both resolve to lowercase hex. */
79
+ function parseTrustedPublishers(raw) {
80
+ const out = new Set();
81
+ for (const entry of raw) {
82
+ if (/^[0-9a-fA-F]{64}$/.test(entry)) {
83
+ out.add(entry.toLowerCase());
84
+ continue;
85
+ }
86
+ if (entry.toLowerCase().startsWith('nsec1')) {
87
+ throw new Error('veilTrustedPublishers wants a PUBLIC key; that is an nsec. Treat it as exposed.');
88
+ }
89
+ let hex;
90
+ try {
91
+ const decoded = decodeNip19(entry);
92
+ if (decoded.type === 'npub')
93
+ hex = decoded.data;
94
+ }
95
+ catch { /* reported below */ }
96
+ if (!hex)
97
+ throw new Error(`veilTrustedPublishers entry "${entry}" is neither an npub nor 64 hex characters`);
98
+ out.add(hex);
99
+ }
100
+ return [...out];
101
+ }
59
102
  /**
60
103
  * Load config from a JSON file. Searches in order:
61
104
  * 1. BRAY_CONFIG env var (explicit path)
@@ -362,6 +405,9 @@ export async function loadConfig(options = {}) {
362
405
  ]
363
406
  .map((s) => s.trim())
364
407
  .filter(Boolean);
408
+ // --- Veil trust anchors ---
409
+ const veilTrustedCircles = parseTrustedCircles(mergeList(process.env.VEIL_TRUSTED_CIRCLES, file.veilTrustedCircles));
410
+ const veilTrustedPublishers = parseTrustedPublishers(mergeList(process.env.VEIL_TRUSTED_PUBLISHERS, file.veilTrustedPublishers));
365
411
  // --- Wallet service ---
366
412
  // Off unless asked for: wallet-grant, wallet-refill and wallet-serve hand
367
413
  // out spending authority over the operator's wallet, which is not
@@ -398,6 +444,8 @@ export async function loadConfig(options = {}) {
398
444
  bindAddress,
399
445
  dispatchIdentities: undefined,
400
446
  forbidPubkeys,
447
+ veilTrustedCircles,
448
+ veilTrustedPublishers,
401
449
  walletService: false,
402
450
  };
403
451
  }
@@ -426,6 +474,8 @@ export async function loadConfig(options = {}) {
426
474
  bindAddress,
427
475
  dispatchIdentities,
428
476
  forbidPubkeys,
477
+ veilTrustedCircles,
478
+ veilTrustedPublishers,
429
479
  walletService,
430
480
  };
431
481
  }
@@ -15,6 +15,10 @@ export interface ToolDeps {
15
15
  nip04Enabled?: boolean;
16
16
  veilCacheTtl?: number;
17
17
  veilCacheMax?: number;
18
+ /** Hex circle IDs whose ring proofs count towards Veil scores. */
19
+ veilTrustedCircles?: string[];
20
+ /** Hex pubkeys whose assertions and ring proofs count towards Veil scores. */
21
+ veilTrustedPublishers?: string[];
18
22
  trust?: TrustContext;
19
23
  }
20
24
  export declare function registerIdentityTools(server: McpServer, deps: ToolDeps): void;
package/dist/index.d.ts CHANGED
@@ -11,4 +11,6 @@ export declare const deps: {
11
11
  nwcUri: string | undefined;
12
12
  walletsFile: string;
13
13
  nip04Enabled: boolean;
14
+ veilTrustedCircles: string[] | undefined;
15
+ veilTrustedPublishers: string[] | undefined;
14
16
  };
package/dist/index.js CHANGED
@@ -136,12 +136,16 @@ const trust = new TrustContext(ctx, pool, {
136
136
  cacheTtl: config.trustCacheTtl,
137
137
  cacheMax: config.trustCacheMax,
138
138
  trustMode: config.trustMode,
139
+ veilTrustedCircles: config.veilTrustedCircles,
140
+ veilTrustedPublishers: config.veilTrustedPublishers,
139
141
  });
140
142
  export const deps = {
141
143
  ctx, pool, nip65, trust,
142
144
  nwcUri: config.nwcUri,
143
145
  walletsFile: config.walletsFile,
144
146
  nip04Enabled: config.nip04Enabled,
147
+ veilTrustedCircles: config.veilTrustedCircles,
148
+ veilTrustedPublishers: config.veilTrustedPublishers,
145
149
  };
146
150
  config.secretKey = '';
147
151
  config.nwcUri = undefined;
@@ -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<{