nostr-bray 3.12.1 → 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.
- package/dist/cli/commands/util.js +21 -2
- package/dist/cli/index.js +1 -1
- package/dist/help.js +1 -1
- package/dist/relay/count.d.ts +15 -3
- package/dist/relay/count.js +42 -3
- package/dist/relay/tools.js +14 -5
- package/dist/relay-pool.d.ts +19 -0
- package/dist/relay-pool.js +54 -0
- package/package.json +1 -1
|
@@ -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
|
-
|
|
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>]
|
|
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.' },
|
package/dist/relay/count.d.ts
CHANGED
|
@@ -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
|
|
14
|
-
*
|
|
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>,
|
|
27
|
+
export declare function handleRelayCount(relays: string[], filter: Record<string, unknown>, through?: RelayPool | PoolQuery): Promise<RelayCountResult>;
|
|
28
|
+
export {};
|
package/dist/relay/count.js
CHANGED
|
@@ -1,9 +1,21 @@
|
|
|
1
1
|
import { validateRelayUrl } from './handlers.js';
|
|
2
2
|
/**
|
|
3
|
-
* Send a COUNT
|
|
4
|
-
*
|
|
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,
|
|
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);
|
package/dist/relay/tools.js
CHANGED
|
@@ -7,6 +7,7 @@ import { handleRelayCount } from './count.js';
|
|
|
7
7
|
import { handleRelayAuth } from './auth.js';
|
|
8
8
|
import { handleCastSpell } from './spell.js';
|
|
9
9
|
import { flatOrWrapped, mergeFlatAndWrapped } from '../util/schema.js';
|
|
10
|
+
import { isNormalRequestEnd } from '../relay-pool.js';
|
|
10
11
|
export function registerRelayTools(server, deps) {
|
|
11
12
|
server.registerTool('relay-list', {
|
|
12
13
|
description: 'List the relay set (read/write) for the active identity. Optionally check for shared relays with another identity.',
|
|
@@ -51,7 +52,7 @@ export function registerRelayTools(server, deps) {
|
|
|
51
52
|
};
|
|
52
53
|
});
|
|
53
54
|
server.registerTool('relay-query', {
|
|
54
|
-
description: 'Query events from Nostr relays by kind, author, ids, tags, or time range. Useful for discovering events, scanning for specific kinds, or investigating unknown event schemas. Uses explicit relays if provided, otherwise the active identity\'s read relays. Filter fields may be supplied either as top-level arguments or wrapped in a single "filter" object (both shapes are accepted).',
|
|
55
|
+
description: 'Query events from Nostr relays by kind, author, ids, tags, or time range. Useful for discovering events, scanning for specific kinds, or investigating unknown event schemas. Uses explicit relays if provided, otherwise the active identity\'s read relays. Filter fields may be supplied either as top-level arguments or wrapped in a single "filter" object (both shapes are accepted). Relays that refuse the REQ (for example "auth-required:" or "restricted:") or cannot be reached are listed under "refused", with their reasons.',
|
|
55
56
|
inputSchema: {
|
|
56
57
|
ids: z.array(z.string()).optional().describe('Event IDs (hex) to fetch directly'),
|
|
57
58
|
kinds: z.array(z.number().int()).optional().describe('Event kinds to filter by (e.g. [30301, 31000])'),
|
|
@@ -86,6 +87,9 @@ export function registerRelayTools(server, deps) {
|
|
|
86
87
|
// "filter" key and the handler receives an empty object, yielding a firehose response.
|
|
87
88
|
const f = args.filter ?? {};
|
|
88
89
|
const mergedLimit = args.limit ?? f.limit ?? 50;
|
|
90
|
+
// Relays that refused the REQ or could not be reached, once each. Without
|
|
91
|
+
// them a refusal reads as "no matching events".
|
|
92
|
+
const refused = new Map();
|
|
89
93
|
const events = await handleRelayQuery(deps.pool, deps.ctx.activeNpub, {
|
|
90
94
|
ids: args.ids ?? f.ids,
|
|
91
95
|
kinds: args.kinds ?? f.kinds,
|
|
@@ -98,6 +102,12 @@ export function registerRelayTools(server, deps) {
|
|
|
98
102
|
search: args.search ?? f.search,
|
|
99
103
|
paginate: args.paginate,
|
|
100
104
|
maxPages: args.max_pages,
|
|
105
|
+
onRelayClose: reasons => {
|
|
106
|
+
for (const { url, reason } of reasons) {
|
|
107
|
+
if (!isNormalRequestEnd(reason))
|
|
108
|
+
refused.set(`${url}\n${reason}`, { relay: url, reason });
|
|
109
|
+
}
|
|
110
|
+
},
|
|
101
111
|
});
|
|
102
112
|
const summary = events.map(e => ({
|
|
103
113
|
id: e.id,
|
|
@@ -116,6 +126,7 @@ export function registerRelayTools(server, deps) {
|
|
|
116
126
|
...(maybeMore ? {
|
|
117
127
|
note: `Returned exactly the limit (${mergedLimit}), so there may be more. Re-run with paginate: true to collect the full set, or raise the limit.`,
|
|
118
128
|
} : {}),
|
|
129
|
+
...(refused.size ? { refused: [...refused.values()] } : {}),
|
|
119
130
|
events: summary,
|
|
120
131
|
}, null, 2) }],
|
|
121
132
|
};
|
|
@@ -175,10 +186,8 @@ export function registerRelayTools(server, deps) {
|
|
|
175
186
|
filter[tagKey] = values;
|
|
176
187
|
}
|
|
177
188
|
}
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
};
|
|
181
|
-
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);
|
|
182
191
|
return {
|
|
183
192
|
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
184
193
|
};
|
package/dist/relay-pool.d.ts
CHANGED
|
@@ -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;
|
package/dist/relay-pool.js
CHANGED
|
@@ -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.
|
|
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",
|