nostr-bray 3.12.2 → 3.13.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.
@@ -1,8 +1,9 @@
1
1
  import { handleDecode, handleEncodeNpub, handleEncodeNote, handleEncodeNprofile, handleEncodeNevent, handleVerify, handleEncrypt, handleDecrypt, handleCount, handleFetch, handleKeyPublic, handleEncodeNsec, handleFilter, handleNipList, handleNipShow, handleKeyEncrypt, handleKeyDecrypt, handleValidateEvent, lookupKind, searchKinds, handleGiftWrap, handleGiftUnwrap, } from '../../exports.js';
2
2
  import { validateInputPath } from '../../validation.js';
3
3
  import * as fmt from '../../format.js';
4
+ import { handleRelayCount } from '../../relay/count.js';
4
5
  export async function dispatch(cmd, cmdArgs, h, ctx, pool) {
5
- const { req, flag, hasFlag, out } = h;
6
+ const { req, flag, flags, hasFlag, out } = h;
6
7
  switch (cmd) {
7
8
  case 'decode':
8
9
  out(handleDecode(req(1, 'decode <nip19>')), fmt.formatDecode);
@@ -110,7 +111,25 @@ export async function dispatch(cmd, cmdArgs, h, ctx, pool) {
110
111
  const since = flag('since');
111
112
  if (since)
112
113
  filter.since = parseInt(since, 10);
113
- out(await handleCount(pool, ctx.activeNpub, filter));
114
+ const relayOverrides = flags('relay');
115
+ const relays = relayOverrides.length ? relayOverrides : pool.getRelays(ctx.activeNpub).read;
116
+ if (relays.length === 0)
117
+ throw new Error('No relays available. Set NOSTR_RELAYS or pass --relay <url>.');
118
+ if (relays.length === 1) {
119
+ // One relay: a NIP-45 COUNT through the pool (Tor, AUTH and URL rules
120
+ // apply), falling back to counting a capped REQ if it lacks NIP-45.
121
+ const result = await handleRelayCount(relays, filter, pool);
122
+ out({ count: result.total, relays: result.counts });
123
+ if (result.counts.every(c => c.error))
124
+ process.exitCode = 1;
125
+ }
126
+ else {
127
+ // Several relays: COUNT cannot tell which events they share, so fetch
128
+ // and count each event once.
129
+ out(relayOverrides.length
130
+ ? { count: (await pool.queryDirect(relays, filter)).length }
131
+ : await handleCount(pool, ctx.activeNpub, filter));
132
+ }
114
133
  break;
115
134
  }
116
135
  case 'fetch':
package/dist/cli/index.js CHANGED
@@ -234,7 +234,7 @@ Utility:
234
234
  verify <event-json> Verify event hash and signature
235
235
  encrypt <pubkey-hex> "plaintext" NIP-44 encrypt for a recipient
236
236
  decrypt <pubkey-hex> <ciphertext> NIP-44 decrypt from a sender
237
- count --kinds 1 [--authors <hex>] Count events matching filter
237
+ count --kinds 1 [--authors <hex>] [--relay url] Count events (NIP-45 COUNT when there is one relay)
238
238
  fetch <nip19> Fetch events by nip19 code
239
239
 
240
240
  MuSig2 (BIP-327 multi-signature):
package/dist/help.js CHANGED
@@ -88,7 +88,7 @@ export const COMMAND_HELP = {
88
88
  verify: { usage: 'verify <event-json>', description: 'Verify a Nostr event\'s id hash and cryptographic signature.', examples: ['nostr-bray verify \'{"id":"...","pubkey":"...","sig":"...",...}\''] },
89
89
  encrypt: { usage: 'encrypt <pubkey-hex> "plaintext"', description: 'Encrypt a string using NIP-44 for a recipient pubkey. Uses the active identity\'s private key.', examples: ['nostr-bray encrypt abc123... "secret message"'] },
90
90
  decrypt: { usage: 'decrypt <pubkey-hex> <ciphertext>', description: 'Decrypt a NIP-44 ciphertext using the active identity\'s private key.', examples: ['nostr-bray decrypt abc123... AQBh7...'] },
91
- count: { usage: 'count [--kinds N,N] [--authors X,X] [--since N]', description: 'Count events matching a filter on relays.', examples: ['nostr-bray count --kinds 1', 'nostr-bray count --kinds 1,7 --authors abc123...'] },
91
+ count: { usage: 'count [--kinds N,N] [--authors X,X] [--since N] [--relay url]', description: 'Count events matching a filter on relays. With one relay it sends a NIP-45 COUNT, falling back to counting a REQ when the relay lacks NIP-45; with several it fetches and counts each event once.', examples: ['nostr-bray count --kinds 1', 'nostr-bray count --kinds 1,7 --authors abc123...'] },
92
92
  fetch: { usage: 'fetch <nip19>', description: 'Fetch events by nip19 code (note, nevent, nprofile, npub, naddr). Resolves the entity and queries relays.', examples: ['nostr-bray fetch note1...', 'nostr-bray fetch nevent1...', 'nostr-bray fetch npub1...'] },
93
93
  shell: { usage: 'shell', description: 'Start an interactive REPL with a persistent relay connection. Supports tab autocomplete. Type "help" for commands, "exit" to quit.', examples: ['nostr-bray shell'] },
94
94
  'key-encrypt': { usage: 'key-encrypt <nsec-or-hex> <password>', description: 'Encrypt a secret key with a password using NIP-49. Returns an ncryptsec string safe for storage. Also returns the derived pubkey for verification.', examples: ['nostr-bray key-encrypt nsec1... mypassword'], notes: 'WARNING: secret key is passed as a CLI argument. Use only on trusted systems.' },
@@ -1,3 +1,4 @@
1
+ import type { RelayPool } from '../relay-pool.js';
1
2
  export interface CountResult {
2
3
  relay: string;
3
4
  count: number;
@@ -9,8 +10,19 @@ export interface RelayCountResult {
9
10
  counts: CountResult[];
10
11
  total: number;
11
12
  }
13
+ type PoolQuery = (relays: string[], filter: Record<string, unknown>) => Promise<unknown[]>;
12
14
  /**
13
- * Send a COUNT request to relays using the lower-level WebSocket protocol.
14
- * Falls back to fetch-and-count if the relay does not support NIP-45.
15
+ * Send a NIP-45 COUNT to each relay, falling back to fetch-and-count (capped at
16
+ * 1000) when a relay does not support NIP-45.
17
+ *
18
+ * Pass the `RelayPool` as the third argument: the COUNT then goes over the
19
+ * pool's own connections, so TOR_PROXY, BRAY_ALLOW_PRIVATE_RELAYS and NIP-42
20
+ * AUTH apply as for any query, and a relay that refuses (auth-required:,
21
+ * restricted:) or cannot be reached is reported, not counted by fallback.
22
+ *
23
+ * The older form, with a query function or nothing as the third argument,
24
+ * still works but opens its own WebSocket to each relay: it ignores TOR_PROXY
25
+ * and does not authenticate.
15
26
  */
16
- export declare function handleRelayCount(relays: string[], filter: Record<string, unknown>, poolQuery?: (relays: string[], filter: Record<string, unknown>) => Promise<unknown[]>): Promise<RelayCountResult>;
27
+ export declare function handleRelayCount(relays: string[], filter: Record<string, unknown>, through?: RelayPool | PoolQuery): Promise<RelayCountResult>;
28
+ export {};
@@ -1,9 +1,21 @@
1
1
  import { validateRelayUrl } from './handlers.js';
2
2
  /**
3
- * Send a COUNT request to relays using the lower-level WebSocket protocol.
4
- * Falls back to fetch-and-count if the relay does not support NIP-45.
3
+ * Send a NIP-45 COUNT to each relay, falling back to fetch-and-count (capped at
4
+ * 1000) when a relay does not support NIP-45.
5
+ *
6
+ * Pass the `RelayPool` as the third argument: the COUNT then goes over the
7
+ * pool's own connections, so TOR_PROXY, BRAY_ALLOW_PRIVATE_RELAYS and NIP-42
8
+ * AUTH apply as for any query, and a relay that refuses (auth-required:,
9
+ * restricted:) or cannot be reached is reported, not counted by fallback.
10
+ *
11
+ * The older form, with a query function or nothing as the third argument,
12
+ * still works but opens its own WebSocket to each relay: it ignores TOR_PROXY
13
+ * and does not authenticate.
5
14
  */
6
- export async function handleRelayCount(relays, filter, poolQuery) {
15
+ export async function handleRelayCount(relays, filter, through) {
16
+ if (through && typeof through !== 'function')
17
+ return countThroughPool(through, relays, filter);
18
+ const poolQuery = through;
7
19
  for (const url of relays)
8
20
  validateRelayUrl(url);
9
21
  const results = await Promise.all(relays.map(url => countFromRelay(url, filter, poolQuery)));
@@ -12,6 +24,33 @@ export async function handleRelayCount(relays, filter, poolQuery) {
12
24
  total: results.reduce((sum, r) => sum + (r.error ? 0 : r.count), 0),
13
25
  };
14
26
  }
27
+ /** A refusal or an unreachable relay: a REQ would fare no better, so no fallback. */
28
+ const noFallback = (error) => /^(auth-required|restricted):|^connection failure/.test(error);
29
+ async function countThroughPool(pool, relays, filter) {
30
+ const allowPrivate = pool.allowsPrivateRelays?.() === true;
31
+ for (const url of relays)
32
+ validateRelayUrl(url, { allowPrivate });
33
+ const answers = await pool.countDirect(relays, filter);
34
+ const counts = await Promise.all(answers.map(async (answer) => {
35
+ if (answer.error === undefined) {
36
+ return { relay: answer.url, count: answer.count ?? 0, ...(answer.approximate ? { estimated: true } : {}) };
37
+ }
38
+ if (noFallback(answer.error))
39
+ return { relay: answer.url, count: 0, error: answer.error };
40
+ // No NIP-45 (or no answer in time): count a capped REQ instead.
41
+ try {
42
+ const events = await pool.queryDirect([answer.url], { ...filter, limit: 1000 });
43
+ return { relay: answer.url, count: events.length, fallback: true, estimated: events.length >= 1000 };
44
+ }
45
+ catch (err) {
46
+ return { relay: answer.url, count: 0, error: `COUNT failed (${answer.error}) and the fallback failed: ${err.message}` };
47
+ }
48
+ }));
49
+ return {
50
+ counts,
51
+ total: counts.reduce((sum, r) => sum + (r.error ? 0 : r.count), 0),
52
+ };
53
+ }
15
54
  async function countFromRelay(url, filter, poolQuery) {
16
55
  try {
17
56
  return await countViaWebSocket(url, filter);
@@ -186,10 +186,8 @@ export function registerRelayTools(server, deps) {
186
186
  filter[tagKey] = values;
187
187
  }
188
188
  }
189
- const poolQuery = async (urls, f) => {
190
- return deps.pool.queryDirect(urls, f);
191
- };
192
- const result = await handleRelayCount(relays, filter, poolQuery);
189
+ // Through the pool: TOR_PROXY, the relay URL rules and NIP-42 AUTH apply.
190
+ const result = await handleRelayCount(relays, filter, deps.pool);
193
191
  return {
194
192
  content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
195
193
  };
@@ -37,6 +37,15 @@ export interface SubscriptionClose {
37
37
  * is the relay's CLOSED reason or a connection failure.
38
38
  */
39
39
  export declare function isNormalRequestEnd(reason: string): boolean;
40
+ /** One relay's answer to a NIP-45 COUNT: its count, or why there is none. */
41
+ export interface RelayCount {
42
+ url: string;
43
+ count?: number;
44
+ /** The relay marked its count approximate. */
45
+ approximate?: boolean;
46
+ /** The relay's CLOSED reason (auth failures explained), a timeout, or a connection failure. */
47
+ error?: string;
48
+ }
40
49
  /** Params threaded through to nostr-tools: deadlines plus NIP-42 auth retry. */
41
50
  export interface PoolParams {
42
51
  maxWait?: number;
@@ -181,6 +190,16 @@ export declare class RelayPool {
181
190
  signal?: AbortSignal;
182
191
  onclose?: (reasons: SubscriptionClose[]) => void;
183
192
  }): Promise<NostrEvent[]>;
193
+ /**
194
+ * NIP-45 COUNT against explicit relays, on the pool's own connections, so
195
+ * the Tor proxy, the relay URL rules and NIP-42 AUTH apply as for a query.
196
+ * A relay that answers auth-required: is authenticated and asked again when
197
+ * auth is on. nostr-tools sets no deadline on a COUNT, so `timeoutMs`
198
+ * (default 5 s) bounds each relay's connection and each COUNT.
199
+ */
200
+ countDirect(relays: string[], filter: Filter, opts?: {
201
+ timeoutMs?: number;
202
+ }): Promise<RelayCount[]>;
184
203
  /** Reconcile local event IDs with one relay using NIP-77 Negentropy. */
185
204
  reconcileDirect(relayUrl: string, items: Array<{
186
205
  id: string;
@@ -13,6 +13,15 @@ const WS_MAX_PAYLOAD = 512 * 1024;
13
13
  export function isNormalRequestEnd(reason) {
14
14
  return reason === 'closed automatically on eose' || reason === 'closed by caller';
15
15
  }
16
+ const reasonOf = (err) => (err instanceof Error ? err.message : String(err));
17
+ /** Settle with `p`, or reject with `message` after `ms`. */
18
+ function within(ms, p, message) {
19
+ let timer;
20
+ return Promise.race([
21
+ p.finally(() => clearTimeout(timer)),
22
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(message)), ms); }),
23
+ ]);
24
+ }
16
25
  export class Nip77UnavailableError extends Error {
17
26
  constructor(message) {
18
27
  super(message);
@@ -389,6 +398,51 @@ export class RelayPool {
389
398
  });
390
399
  });
391
400
  }
401
+ /**
402
+ * NIP-45 COUNT against explicit relays, on the pool's own connections, so
403
+ * the Tor proxy, the relay URL rules and NIP-42 AUTH apply as for a query.
404
+ * A relay that answers auth-required: is authenticated and asked again when
405
+ * auth is on. nostr-tools sets no deadline on a COUNT, so `timeoutMs`
406
+ * (default 5 s) bounds each relay's connection and each COUNT.
407
+ */
408
+ async countDirect(relays, filter, opts = {}) {
409
+ this.#validateDirectRelays(relays);
410
+ const pool = await this.poolReady;
411
+ const timeoutMs = opts.timeoutMs ?? 5_000;
412
+ return Promise.all(relays.map(url => this.#countOne(pool, url, filter, timeoutMs)));
413
+ }
414
+ async #countOne(pool, url, filter, timeoutMs) {
415
+ if (!pool.ensureRelay)
416
+ return { url, error: 'the underlying relay pool cannot send COUNT' };
417
+ let relay;
418
+ try {
419
+ relay = await pool.ensureRelay(url, { connectionTimeout: timeoutMs });
420
+ }
421
+ catch (err) {
422
+ return { url, error: `connection failure: ${reasonOf(err)}` };
423
+ }
424
+ const count = async () => {
425
+ // countWithHLL resolves with the relay's whole COUNT payload, approximate included.
426
+ const reply = await within(timeoutMs, relay.countWithHLL([filter], {}), 'COUNT timed out');
427
+ return { url, count: reply.count, ...(reply.approximate ? { approximate: true } : {}) };
428
+ };
429
+ try {
430
+ return await count();
431
+ }
432
+ catch (err) {
433
+ const reason = reasonOf(err);
434
+ const { onauth } = this.#authParams();
435
+ if (!reason.startsWith('auth-required: ') || !onauth)
436
+ return { url, error: this.#annotateAuthError(reason) };
437
+ try {
438
+ await relay.auth(onauth);
439
+ return await count();
440
+ }
441
+ catch (authErr) {
442
+ return { url, error: this.#annotateAuthError(reasonOf(authErr)) };
443
+ }
444
+ }
445
+ }
392
446
  /** Reconcile local event IDs with one relay using NIP-77 Negentropy. */
393
447
  async reconcileDirect(relayUrl, items, filter, opts = {}) {
394
448
  this.#validateDirectRelays([relayUrl]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nostr-bray",
3
- "version": "3.12.2",
3
+ "version": "3.13.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",