nostr-bray 3.12.2 → 3.14.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 +2 -2
- package/dist/help.js +1 -1
- package/dist/index.js +1 -1
- package/dist/relay/auth.d.ts +11 -1
- package/dist/relay/auth.js +14 -1
- package/dist/relay/count.d.ts +15 -3
- package/dist/relay/count.js +42 -3
- package/dist/relay/tools.js +5 -6
- package/dist/relay-pool.d.ts +52 -1
- package/dist/relay-pool.js +180 -2
- 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):
|
|
@@ -391,7 +391,7 @@ else {
|
|
|
391
391
|
ctx = new IdentityContext(config.secretKey, config.secretFormat, { forbidPubkeys: config.forbidPubkeys });
|
|
392
392
|
}
|
|
393
393
|
// NIP-42: the pool answers AUTH challenges with the active identity's key.
|
|
394
|
-
pool.setAuthSigner(async (evt) => ctx.getSigningFunction()(evt));
|
|
394
|
+
pool.setAuthSigner(async (evt) => ctx.getSigningFunction()(evt), () => ctx.activePublicKeyHex);
|
|
395
395
|
const globalNwcUri = config.nwcUri;
|
|
396
396
|
const walletsFile = config.walletsFile;
|
|
397
397
|
config.secretKey = '';
|
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/index.js
CHANGED
|
@@ -130,7 +130,7 @@ else {
|
|
|
130
130
|
// effect when authMode is not 'off' -- the pool checks the mode per operation.
|
|
131
131
|
// Read-only mode has no signer, and loadConfig has already set authMode off.
|
|
132
132
|
if (!config.readOnly) {
|
|
133
|
-
pool.setAuthSigner(async (evt) => ctx.getSigningFunction()(evt));
|
|
133
|
+
pool.setAuthSigner(async (evt) => ctx.getSigningFunction()(evt), () => ctx.activePublicKeyHex);
|
|
134
134
|
}
|
|
135
135
|
const trust = new TrustContext(ctx, pool, {
|
|
136
136
|
cacheTtl: config.trustCacheTtl,
|
package/dist/relay/auth.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { SigningContext } from '../signing-context.js';
|
|
2
|
+
import type { RelayPool } from '../relay-pool.js';
|
|
2
3
|
export interface RelayAuthResult {
|
|
3
4
|
authenticated: boolean;
|
|
4
5
|
relay: string;
|
|
@@ -8,6 +9,15 @@ export interface RelayAuthResult {
|
|
|
8
9
|
/**
|
|
9
10
|
* Authenticate to a relay that requires NIP-42 AUTH.
|
|
10
11
|
*
|
|
12
|
+
* Pass the `RelayPool` as the third argument: the pool's own connection to the
|
|
13
|
+
* relay is then authenticated as the active identity, through TOR_PROXY and the
|
|
14
|
+
* relay URL rules, so later queries and publishes to that relay on it are
|
|
15
|
+
* served (see RelayPool.authenticate).
|
|
16
|
+
*
|
|
17
|
+
* The older two-argument form still works but opens a separate WebSocket,
|
|
18
|
+
* ignores TOR_PROXY, and closes that connection once authenticated, so the
|
|
19
|
+
* AUTH applies to nothing else. It only shows that the relay accepts the key.
|
|
20
|
+
*
|
|
11
21
|
* Flow:
|
|
12
22
|
* 1. Connect via WebSocket
|
|
13
23
|
* 2. Wait for ["AUTH", challenge] message
|
|
@@ -15,4 +25,4 @@ export interface RelayAuthResult {
|
|
|
15
25
|
* 4. Send ["AUTH", signedEvent]
|
|
16
26
|
* 5. Wait for ["OK", eventId, true, ...] confirmation
|
|
17
27
|
*/
|
|
18
|
-
export declare function handleRelayAuth(ctx: SigningContext, relay: string): Promise<RelayAuthResult>;
|
|
28
|
+
export declare function handleRelayAuth(ctx: SigningContext, relay: string, pool?: RelayPool): Promise<RelayAuthResult>;
|
package/dist/relay/auth.js
CHANGED
|
@@ -2,6 +2,15 @@ import { validateRelayUrl } from './handlers.js';
|
|
|
2
2
|
/**
|
|
3
3
|
* Authenticate to a relay that requires NIP-42 AUTH.
|
|
4
4
|
*
|
|
5
|
+
* Pass the `RelayPool` as the third argument: the pool's own connection to the
|
|
6
|
+
* relay is then authenticated as the active identity, through TOR_PROXY and the
|
|
7
|
+
* relay URL rules, so later queries and publishes to that relay on it are
|
|
8
|
+
* served (see RelayPool.authenticate).
|
|
9
|
+
*
|
|
10
|
+
* The older two-argument form still works but opens a separate WebSocket,
|
|
11
|
+
* ignores TOR_PROXY, and closes that connection once authenticated, so the
|
|
12
|
+
* AUTH applies to nothing else. It only shows that the relay accepts the key.
|
|
13
|
+
*
|
|
5
14
|
* Flow:
|
|
6
15
|
* 1. Connect via WebSocket
|
|
7
16
|
* 2. Wait for ["AUTH", challenge] message
|
|
@@ -9,7 +18,11 @@ import { validateRelayUrl } from './handlers.js';
|
|
|
9
18
|
* 4. Send ["AUTH", signedEvent]
|
|
10
19
|
* 5. Wait for ["OK", eventId, true, ...] confirmation
|
|
11
20
|
*/
|
|
12
|
-
export async function handleRelayAuth(ctx, relay) {
|
|
21
|
+
export async function handleRelayAuth(ctx, relay, pool) {
|
|
22
|
+
if (pool) {
|
|
23
|
+
validateRelayUrl(relay, { allowPrivate: pool.allowsPrivateRelays?.() === true });
|
|
24
|
+
return pool.authenticate(relay);
|
|
25
|
+
}
|
|
13
26
|
validateRelayUrl(relay); // throws on private IPs -- intentionally not caught
|
|
14
27
|
return new Promise((resolve) => {
|
|
15
28
|
let settled = false;
|
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
|
@@ -186,10 +186,8 @@ export function registerRelayTools(server, deps) {
|
|
|
186
186
|
filter[tagKey] = values;
|
|
187
187
|
}
|
|
188
188
|
}
|
|
189
|
-
|
|
190
|
-
|
|
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
|
};
|
|
@@ -209,13 +207,14 @@ export function registerRelayTools(server, deps) {
|
|
|
209
207
|
};
|
|
210
208
|
});
|
|
211
209
|
server.registerTool('relay-auth', {
|
|
212
|
-
description: 'Authenticate to a relay
|
|
210
|
+
description: 'Authenticate (NIP-42) bray\'s own connection to a relay as the active identity, so later queries and publishes to that relay on it are served. Waits for the relay\'s AUTH challenge, signs a kind 22242 event and sends it back. Returns { authenticated: true/false }. Use this when a relay-query fails due to AUTH requirements, then retry the query. Switching identity drops a connection that authenticated as another identity, so authenticate again after a switch.',
|
|
213
211
|
inputSchema: {
|
|
214
212
|
relay: relayUrl.describe('Relay WebSocket URL to authenticate with'),
|
|
215
213
|
},
|
|
216
214
|
annotations: { readOnlyHint: false },
|
|
217
215
|
}, async ({ relay }) => {
|
|
218
|
-
|
|
216
|
+
// On the pool's own connection, so the retried query is authenticated.
|
|
217
|
+
const result = await handleRelayAuth(deps.ctx, relay, deps.pool);
|
|
219
218
|
return {
|
|
220
219
|
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
221
220
|
};
|
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;
|
|
@@ -63,6 +72,14 @@ export interface PoolLike {
|
|
|
63
72
|
}): Promise<AbstractRelay>;
|
|
64
73
|
/** Install the eager AUTH-challenge responder. Absent on injected test doubles. */
|
|
65
74
|
setAutomaticAuth?(signer: ((relayUrl: string) => AuthSigner | null) | undefined): void;
|
|
75
|
+
/**
|
|
76
|
+
* Consulted before each use of a relay connection, with nostr-tools'
|
|
77
|
+
* normalised URL and whether a connection is open: true closes the open one
|
|
78
|
+
* so the use starts on a fresh connection. Absent on injected test doubles.
|
|
79
|
+
*/
|
|
80
|
+
setReuseCheck?(check: ((url: string, open: boolean) => boolean) | undefined): void;
|
|
81
|
+
/** Close and forget one relay's connection. Absent on injected test doubles. */
|
|
82
|
+
forget?(url: string): void;
|
|
66
83
|
destroy(): void;
|
|
67
84
|
}
|
|
68
85
|
export interface ReconcileDirectResult {
|
|
@@ -139,8 +156,13 @@ export declare class RelayPool {
|
|
|
139
156
|
* Called once the identity context exists, which is after the pool is
|
|
140
157
|
* constructed. Passing `undefined` disables authentication again (used when
|
|
141
158
|
* switching identity, so a challenge is never answered with a stale key).
|
|
159
|
+
*
|
|
160
|
+
* `currentPubkey` returns the active identity's pubkey (hex). With it, a
|
|
161
|
+
* relay connection is not reused across an identity switch when that could
|
|
162
|
+
* tie the two identities together (see #reuse); without it, connections are
|
|
163
|
+
* reused as before.
|
|
142
164
|
*/
|
|
143
|
-
setAuthSigner(signer: AuthSigner | undefined): void;
|
|
165
|
+
setAuthSigner(signer: AuthSigner | undefined, currentPubkey?: () => string): void;
|
|
144
166
|
/** Current NIP-42 policy. */
|
|
145
167
|
getAuthMode(): AuthMode;
|
|
146
168
|
/** Change the NIP-42 policy at runtime. */
|
|
@@ -181,6 +203,35 @@ export declare class RelayPool {
|
|
|
181
203
|
signal?: AbortSignal;
|
|
182
204
|
onclose?: (reasons: SubscriptionClose[]) => void;
|
|
183
205
|
}): Promise<NostrEvent[]>;
|
|
206
|
+
/**
|
|
207
|
+
* NIP-45 COUNT against explicit relays, on the pool's own connections, so
|
|
208
|
+
* the Tor proxy, the relay URL rules and NIP-42 AUTH apply as for a query.
|
|
209
|
+
* A relay that answers auth-required: is authenticated and asked again when
|
|
210
|
+
* auth is on. nostr-tools sets no deadline on a COUNT, so `timeoutMs`
|
|
211
|
+
* (default 5 s) bounds each relay's connection and each COUNT.
|
|
212
|
+
*/
|
|
213
|
+
countDirect(relays: string[], filter: Filter, opts?: {
|
|
214
|
+
timeoutMs?: number;
|
|
215
|
+
}): Promise<RelayCount[]>;
|
|
216
|
+
/**
|
|
217
|
+
* NIP-42: authenticate the pool's own connection to `url` as the active
|
|
218
|
+
* identity, so later queries and publishes to that relay on it are served.
|
|
219
|
+
*
|
|
220
|
+
* An explicit request, so it works in every auth mode. It waits for the
|
|
221
|
+
* relay's challenge, prompting one with an empty REQ if the relay sends it
|
|
222
|
+
* only after refusing a request (bray's serve --auth does). A connection
|
|
223
|
+
* that carried another identity's traffic is replaced first; after a refusal
|
|
224
|
+
* the connection is dropped, since nostr-tools keeps its first attempt and a
|
|
225
|
+
* second try on it would only repeat the refusal.
|
|
226
|
+
*/
|
|
227
|
+
authenticate(url: string, opts?: {
|
|
228
|
+
timeoutMs?: number;
|
|
229
|
+
}): Promise<{
|
|
230
|
+
authenticated: boolean;
|
|
231
|
+
relay: string;
|
|
232
|
+
pubkey?: string;
|
|
233
|
+
error?: string;
|
|
234
|
+
}>;
|
|
184
235
|
/** Reconcile local event IDs with one relay using NIP-77 Negentropy. */
|
|
185
236
|
reconcileDirect(relayUrl: string, items: Array<{
|
|
186
237
|
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);
|
|
@@ -52,6 +61,18 @@ async function createRealPool(torProxy) {
|
|
|
52
61
|
const WebSocketImpl = webSocketFor(torProxy, { maxPayload: WS_MAX_PAYLOAD });
|
|
53
62
|
useWebSocketImplementation(WebSocketImpl);
|
|
54
63
|
const pool = new SimplePool({ websocketImplementation: WebSocketImpl });
|
|
64
|
+
const { normalizeURL } = await import('nostr-tools/utils');
|
|
65
|
+
// nostr-tools reaches every relay through ensureRelay, so this is where a
|
|
66
|
+
// connection can be refused reuse. The relay map is protected in its types.
|
|
67
|
+
const relayMap = pool.relays;
|
|
68
|
+
const ensureRelay = pool.ensureRelay.bind(pool);
|
|
69
|
+
let reuseCheck;
|
|
70
|
+
pool.ensureRelay = ((url, params) => {
|
|
71
|
+
const key = normalizeURL(url);
|
|
72
|
+
if (reuseCheck?.(key, relayMap.has(key)))
|
|
73
|
+
pool.close([key]);
|
|
74
|
+
return ensureRelay(url, params);
|
|
75
|
+
});
|
|
55
76
|
return {
|
|
56
77
|
// `onauth` is spread straight through to the subscription params by
|
|
57
78
|
// querySync/subscribeEose, so it works despite not being in querySync's
|
|
@@ -62,6 +83,8 @@ async function createRealPool(torProxy) {
|
|
|
62
83
|
subscribeEose: (relays, filter, handlers) => pool.subscribeEose(relays, filter, handlers),
|
|
63
84
|
ensureRelay: (url, params) => pool.ensureRelay(url, params),
|
|
64
85
|
setAutomaticAuth: signerFor => setAutomaticAuth(pool, signerFor),
|
|
86
|
+
setReuseCheck: check => { reuseCheck = check; },
|
|
87
|
+
forget: url => pool.close([normalizeURL(url)]),
|
|
65
88
|
destroy: () => pool.destroy(),
|
|
66
89
|
};
|
|
67
90
|
}
|
|
@@ -80,6 +103,14 @@ export class RelayPool {
|
|
|
80
103
|
authSigner;
|
|
81
104
|
/** Relays we have signed an AUTH event for, for diagnostics. */
|
|
82
105
|
authedRelays = new Set();
|
|
106
|
+
/** The active identity's pubkey (hex), from the signing context. */
|
|
107
|
+
#currentPubkey;
|
|
108
|
+
/**
|
|
109
|
+
* For each relay connection (nostr-tools' normalised URL): the identity that
|
|
110
|
+
* last used it, and the one whose AUTH event it has seen (accepted or not, the
|
|
111
|
+
* relay has seen the key). See #reuse.
|
|
112
|
+
*/
|
|
113
|
+
#connectionOwners = new Map();
|
|
83
114
|
constructor(config, injectedPool) {
|
|
84
115
|
this.torProxy = config.torProxy;
|
|
85
116
|
this.allowClearnet = config.allowClearnet;
|
|
@@ -117,6 +148,45 @@ export class RelayPool {
|
|
|
117
148
|
else {
|
|
118
149
|
this.poolReady = createRealPool(config.torProxy).then(p => { this.pool = p; return p; });
|
|
119
150
|
}
|
|
151
|
+
// Registered before any caller can await poolReady, so no use goes unchecked.
|
|
152
|
+
void this.poolReady.then(p => p.setReuseCheck?.((url, open) => this.#reuse(url, open)));
|
|
153
|
+
}
|
|
154
|
+
/** The active identity's pubkey, or undefined when it is not known (yet). */
|
|
155
|
+
#activePubkey() {
|
|
156
|
+
try {
|
|
157
|
+
return this.#currentPubkey?.();
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
// A bunker context throws until its key is resolved.
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Whether the open connection to `url` must be replaced before the active
|
|
166
|
+
* identity uses it, so one connection never carries two identities.
|
|
167
|
+
*
|
|
168
|
+
* A NIP-42 AUTH ties a connection to a key, so a relay that has seen one
|
|
169
|
+
* identity's AUTH on a connection could link it to the next identity's
|
|
170
|
+
* traffic there. That connection is replaced in every auth mode. With AUTH on
|
|
171
|
+
* (on-demand or eager), any connection another identity used is replaced
|
|
172
|
+
* too, since the next AUTH on it would link the two. With AUTH off and no AUTH
|
|
173
|
+
* sent, a connection is kept across a switch. The same IP and timing remain
|
|
174
|
+
* either way: this removes the AUTH link only.
|
|
175
|
+
*/
|
|
176
|
+
#reuse(url, open) {
|
|
177
|
+
const current = this.#activePubkey();
|
|
178
|
+
if (current === undefined)
|
|
179
|
+
return false;
|
|
180
|
+
const owner = open ? this.#connectionOwners.get(url) : undefined;
|
|
181
|
+
const sawOtherAuth = owner?.authedBy !== undefined && owner.authedBy !== current;
|
|
182
|
+
const usedByOther = this.authMode !== 'off' && owner?.usedBy !== undefined && owner.usedBy !== current;
|
|
183
|
+
if (sawOtherAuth || usedByOther) {
|
|
184
|
+
console.error(`[bray] new connection to ${url} for the active identity: the open one ${sawOtherAuth ? 'authenticated as' : 'was used by'} another identity`);
|
|
185
|
+
this.#connectionOwners.set(url, { usedBy: current });
|
|
186
|
+
return true;
|
|
187
|
+
}
|
|
188
|
+
this.#connectionOwners.set(url, { ...owner, usedBy: current });
|
|
189
|
+
return false;
|
|
120
190
|
}
|
|
121
191
|
/** Store relay set for an identity and flush any queued writes */
|
|
122
192
|
reconfigure(npub, relays) {
|
|
@@ -166,9 +236,15 @@ export class RelayPool {
|
|
|
166
236
|
* Called once the identity context exists, which is after the pool is
|
|
167
237
|
* constructed. Passing `undefined` disables authentication again (used when
|
|
168
238
|
* switching identity, so a challenge is never answered with a stale key).
|
|
239
|
+
*
|
|
240
|
+
* `currentPubkey` returns the active identity's pubkey (hex). With it, a
|
|
241
|
+
* relay connection is not reused across an identity switch when that could
|
|
242
|
+
* tie the two identities together (see #reuse); without it, connections are
|
|
243
|
+
* reused as before.
|
|
169
244
|
*/
|
|
170
|
-
setAuthSigner(signer) {
|
|
245
|
+
setAuthSigner(signer, currentPubkey) {
|
|
171
246
|
this.authSigner = signer;
|
|
247
|
+
this.#currentPubkey = currentPubkey;
|
|
172
248
|
this.authedRelays.clear();
|
|
173
249
|
void this.#applyEagerAuth();
|
|
174
250
|
}
|
|
@@ -214,8 +290,11 @@ export class RelayPool {
|
|
|
214
290
|
throw new Error('NIP-42 AUTH requested but no signer is configured');
|
|
215
291
|
const relayTag = evt.tags.find(t => t[0] === 'relay')?.[1];
|
|
216
292
|
const signed = await this.authSigner(evt);
|
|
217
|
-
if (relayTag)
|
|
293
|
+
if (relayTag) {
|
|
218
294
|
this.authedRelays.add(relayTag);
|
|
295
|
+
// nostr-tools names the relay by the same normalised URL as its map.
|
|
296
|
+
this.#connectionOwners.set(relayTag, { ...this.#connectionOwners.get(relayTag), authedBy: signed.pubkey });
|
|
297
|
+
}
|
|
219
298
|
return signed;
|
|
220
299
|
};
|
|
221
300
|
/**
|
|
@@ -389,6 +468,105 @@ export class RelayPool {
|
|
|
389
468
|
});
|
|
390
469
|
});
|
|
391
470
|
}
|
|
471
|
+
/**
|
|
472
|
+
* NIP-45 COUNT against explicit relays, on the pool's own connections, so
|
|
473
|
+
* the Tor proxy, the relay URL rules and NIP-42 AUTH apply as for a query.
|
|
474
|
+
* A relay that answers auth-required: is authenticated and asked again when
|
|
475
|
+
* auth is on. nostr-tools sets no deadline on a COUNT, so `timeoutMs`
|
|
476
|
+
* (default 5 s) bounds each relay's connection and each COUNT.
|
|
477
|
+
*/
|
|
478
|
+
async countDirect(relays, filter, opts = {}) {
|
|
479
|
+
this.#validateDirectRelays(relays);
|
|
480
|
+
const pool = await this.poolReady;
|
|
481
|
+
const timeoutMs = opts.timeoutMs ?? 5_000;
|
|
482
|
+
return Promise.all(relays.map(url => this.#countOne(pool, url, filter, timeoutMs)));
|
|
483
|
+
}
|
|
484
|
+
async #countOne(pool, url, filter, timeoutMs) {
|
|
485
|
+
if (!pool.ensureRelay)
|
|
486
|
+
return { url, error: 'the underlying relay pool cannot send COUNT' };
|
|
487
|
+
let relay;
|
|
488
|
+
try {
|
|
489
|
+
relay = await pool.ensureRelay(url, { connectionTimeout: timeoutMs });
|
|
490
|
+
}
|
|
491
|
+
catch (err) {
|
|
492
|
+
return { url, error: `connection failure: ${reasonOf(err)}` };
|
|
493
|
+
}
|
|
494
|
+
const count = async () => {
|
|
495
|
+
// countWithHLL resolves with the relay's whole COUNT payload, approximate included.
|
|
496
|
+
const reply = await within(timeoutMs, relay.countWithHLL([filter], {}), 'COUNT timed out');
|
|
497
|
+
return { url, count: reply.count, ...(reply.approximate ? { approximate: true } : {}) };
|
|
498
|
+
};
|
|
499
|
+
try {
|
|
500
|
+
return await count();
|
|
501
|
+
}
|
|
502
|
+
catch (err) {
|
|
503
|
+
const reason = reasonOf(err);
|
|
504
|
+
const { onauth } = this.#authParams();
|
|
505
|
+
if (!reason.startsWith('auth-required: ') || !onauth)
|
|
506
|
+
return { url, error: this.#annotateAuthError(reason) };
|
|
507
|
+
try {
|
|
508
|
+
await relay.auth(onauth);
|
|
509
|
+
return await count();
|
|
510
|
+
}
|
|
511
|
+
catch (authErr) {
|
|
512
|
+
return { url, error: this.#annotateAuthError(reasonOf(authErr)) };
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* NIP-42: authenticate the pool's own connection to `url` as the active
|
|
518
|
+
* identity, so later queries and publishes to that relay on it are served.
|
|
519
|
+
*
|
|
520
|
+
* An explicit request, so it works in every auth mode. It waits for the
|
|
521
|
+
* relay's challenge, prompting one with an empty REQ if the relay sends it
|
|
522
|
+
* only after refusing a request (bray's serve --auth does). A connection
|
|
523
|
+
* that carried another identity's traffic is replaced first; after a refusal
|
|
524
|
+
* the connection is dropped, since nostr-tools keeps its first attempt and a
|
|
525
|
+
* second try on it would only repeat the refusal.
|
|
526
|
+
*/
|
|
527
|
+
async authenticate(url, opts = {}) {
|
|
528
|
+
this.#validateDirectRelays([url]);
|
|
529
|
+
if (!this.authSigner)
|
|
530
|
+
return { authenticated: false, relay: url, error: 'NIP-42 AUTH requested but no signer is configured' };
|
|
531
|
+
const pool = await this.poolReady;
|
|
532
|
+
if (!pool.ensureRelay)
|
|
533
|
+
return { authenticated: false, relay: url, error: 'the underlying relay pool cannot authenticate' };
|
|
534
|
+
const timeoutMs = opts.timeoutMs ?? 5_000;
|
|
535
|
+
const { normalizeURL } = await import('nostr-tools/utils');
|
|
536
|
+
const current = this.#activePubkey();
|
|
537
|
+
const owner = this.#connectionOwners.get(normalizeURL(url));
|
|
538
|
+
if (current !== undefined && owner?.usedBy !== undefined && owner.usedBy !== current)
|
|
539
|
+
pool.forget?.(url);
|
|
540
|
+
let relay;
|
|
541
|
+
try {
|
|
542
|
+
relay = await pool.ensureRelay(url, { connectionTimeout: timeoutMs });
|
|
543
|
+
}
|
|
544
|
+
catch (err) {
|
|
545
|
+
return { authenticated: false, relay: url, error: `connection failure: ${reasonOf(err)}` };
|
|
546
|
+
}
|
|
547
|
+
// nostr-tools keeps the latest challenge on the relay; it is private in its types.
|
|
548
|
+
const challenge = () => relay.challenge;
|
|
549
|
+
const deadline = Date.now() + timeoutMs;
|
|
550
|
+
const probeAt = Date.now() + Math.min(500, timeoutMs / 2);
|
|
551
|
+
let probed = false;
|
|
552
|
+
while (!challenge()) {
|
|
553
|
+
if (Date.now() >= deadline)
|
|
554
|
+
return { authenticated: false, relay: url, error: 'AUTH handshake timed out (no challenge received)' };
|
|
555
|
+
if (!probed && Date.now() >= probeAt) {
|
|
556
|
+
probed = true;
|
|
557
|
+
const probe = relay.subscribe([{ limit: 0 }], { onevent: () => { }, oneose: () => probe.close(), onclose: () => { } });
|
|
558
|
+
}
|
|
559
|
+
await new Promise(resolve => setTimeout(resolve, 25));
|
|
560
|
+
}
|
|
561
|
+
try {
|
|
562
|
+
await within(timeoutMs, relay.auth(this.#signAuth), 'AUTH timed out');
|
|
563
|
+
return { authenticated: true, relay: url, pubkey: this.#connectionOwners.get(relay.url)?.authedBy ?? current };
|
|
564
|
+
}
|
|
565
|
+
catch (err) {
|
|
566
|
+
pool.forget?.(url);
|
|
567
|
+
return { authenticated: false, relay: url, error: `AUTH rejected: ${reasonOf(err)}` };
|
|
568
|
+
}
|
|
569
|
+
}
|
|
392
570
|
/** Reconcile local event IDs with one relay using NIP-77 Negentropy. */
|
|
393
571
|
async reconcileDirect(relayUrl, items, filter, opts = {}) {
|
|
394
572
|
this.#validateDirectRelays([relayUrl]);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nostr-bray",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.14.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",
|