nostr-bray 3.12.0 → 3.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,6 +17,7 @@ import { SimplePool } from 'nostr-tools/pool';
17
17
  import { generateSecretKey, finalizeEvent } from 'nostr-tools/pure';
18
18
  import { npubEncode } from 'nostr-tools/nip19';
19
19
  import { webSocketFor } from './ws-safe.js';
20
+ import { setAutomaticAuth } from './nostr-tools-guards.js';
20
21
  import { readStateFile, writeStateFile } from './state.js';
21
22
  /** Bound the NIP-46 connect handshake. nostr-tools' BunkerSigner has no
22
23
  * per-request timeout, so an offline signer or unreachable relays make the
@@ -139,7 +140,8 @@ export class BunkerContext {
139
140
  // relays that only let a key read messages addressed to it still work.
140
141
  // Its own WebSocket class, so TOR_PROXY applies to signer traffic too.
141
142
  const pool = new SimplePool({ websocketImplementation: webSocketFor(options.torProxy) });
142
- pool.automaticallyAuth = () => async (template) => finalizeEvent(template, clientSk);
143
+ const answerChallenge = async (template) => finalizeEvent(template, clientSk);
144
+ setAutomaticAuth(pool, () => answerChallenge);
143
145
  const signer = BunkerSigner.fromBunker(clientSk, {
144
146
  pubkey: config.pubkey,
145
147
  relays: config.relays,
@@ -24,6 +24,7 @@ import { CLIENT_NAME, CLIENT_KEYS_FILE, REQUEST_TIMEOUT_MS, TimeoutError, withTi
24
24
  import { readStateFile, writeStateFile } from './state.js';
25
25
  import { isOnionUrl, validateRelayScheme } from './validation.js';
26
26
  import { webSocketFor } from './ws-safe.js';
27
+ import { setAutomaticAuth } from './nostr-tools-guards.js';
27
28
  /** Saved by `bunker connect` and `bunker pair`; read by loadConfig. */
28
29
  export const BUNKER_URI_FILE = 'bunker-uri';
29
30
  /** NIP-46 request and response events. */
@@ -74,7 +75,8 @@ export async function pairWithNostrConnect(options) {
74
75
  // Answer NIP-42 challenges with the client key, as BunkerContext does.
75
76
  // With TOR_PROXY set, pairing goes through the proxy like bray's other relay traffic.
76
77
  const pool = new SimplePool({ websocketImplementation: webSocketFor(options.torProxy) });
77
- pool.automaticallyAuth = () => async (template) => finalizeEvent(template, clientSk);
78
+ const answerChallenge = async (template) => finalizeEvent(template, clientSk);
79
+ setAutomaticAuth(pool, () => answerChallenge);
78
80
  const timeoutMs = options.timeoutMs ?? PAIR_TIMEOUT_MS;
79
81
  let timer;
80
82
  let sub;
package/dist/bunker.js CHANGED
@@ -15,6 +15,7 @@ import { finalizeEvent, getPublicKey, generateSecretKey } from 'nostr-tools/pure
15
15
  import { npubEncode } from 'nostr-tools/nip19';
16
16
  import { SimplePool } from 'nostr-tools/pool';
17
17
  import { webSocketFor } from './ws-safe.js';
18
+ import { isConnectionFailure, setAutomaticAuth } from './nostr-tools-guards.js';
18
19
  import { readStateFile, readStateFileStrict, writeStateFile } from './state.js';
19
20
  /**
20
21
  * Remove a client pubkey from every bunker key's approvals in
@@ -112,7 +113,8 @@ export function startBunker(opts) {
112
113
  // Sign in (NIP-42) with the bunker key when a relay asks, so a private
113
114
  // relay lets the bunker read requests addressed to it.
114
115
  const pool = new SimplePool({ websocketImplementation: webSocketFor(opts.torProxy) });
115
- pool.automaticallyAuth = () => async (template) => finalizeEvent(template, bunkerSk);
116
+ const answerChallenge = async (template) => finalizeEvent(template, bunkerSk);
117
+ setAutomaticAuth(pool, () => answerChallenge);
116
118
  // Subscribe to kind 24133 events addressed to us
117
119
  const sub = pool.subscribeMany(relays, { kinds: [24133], '#p': [bunkerPk] }, {
118
120
  onevent: async (event) => {
@@ -349,7 +351,21 @@ export function startBunker(opts) {
349
351
  tags: [['p', clientPk]],
350
352
  content: encrypted,
351
353
  }, bunkerSk);
352
- await Promise.any(pool.publish(relays, responseEvent));
354
+ // nostr-tools resolves a publish to a relay it cannot reach with
355
+ // "connection failure: ...", which is not delivery.
356
+ const deliveries = pool.publish(relays, responseEvent).map(p => p.then(reason => {
357
+ if (isConnectionFailure(reason))
358
+ throw new Error(reason);
359
+ return reason;
360
+ }));
361
+ try {
362
+ await Promise.any(deliveries);
363
+ }
364
+ catch (e) {
365
+ const reasons = e instanceof AggregateError ? e.errors.map(err => err instanceof Error ? err.message : String(err)) : [String(e)];
366
+ log(`Response ${id} not delivered: ${reasons.join('; ')}`);
367
+ return;
368
+ }
353
369
  log(`Response ${id}: ${error ?? 'ok'}`);
354
370
  }
355
371
  // Build bunker:// URI
@@ -0,0 +1,22 @@
1
+ import type { EventTemplate, VerifiedEvent } from 'nostr-tools';
2
+ /**
3
+ * Guards for two nostr-tools (2.24) behaviours that otherwise mislead or crash
4
+ * bray. Every pool bray creates goes through these: the relay pool, the bunker
5
+ * daemon, the bunker client and bunker pairing.
6
+ */
7
+ /** Signs a NIP-42 kind 22242 template for one relay. */
8
+ export type ChallengeSigner = (evt: EventTemplate) => Promise<VerifiedEvent>;
9
+ /**
10
+ * Have a nostr-tools SimplePool answer every relay's NIP-42 challenge as it
11
+ * arrives, with each answer guarded as above. `signerFor` returns the signer
12
+ * for a relay URL, or null to leave that relay unanswered; `undefined` stops
13
+ * answering. Use this rather than setting `pool.automaticallyAuth`.
14
+ */
15
+ export declare function setAutomaticAuth(pool: object, signerFor: ((relayUrl: string) => ChallengeSigner | null) | undefined): void;
16
+ /**
17
+ * Whether a resolved per-relay publish result is nostr-tools' report that it
18
+ * could not connect ("connection failure: ..."), which it resolves with instead
19
+ * of rejecting: the event never left this machine. Any other resolved value is
20
+ * the relay's OK message.
21
+ */
22
+ export declare function isConnectionFailure(value: unknown): boolean;
@@ -0,0 +1,55 @@
1
+ const guardedRelays = new WeakSet();
2
+ /**
3
+ * Keep a refused automatic AUTH from ending the process.
4
+ *
5
+ * nostr-tools answers a relay's challenge with `this.auth(this.onauth)` and
6
+ * rethrows any refusal from that promise's `.catch`, where nothing can handle
7
+ * it, so Node exits on the unhandled rejection. A relay that refuses the AUTH
8
+ * (a members-only relay, a key it does not know, an AUTH that names another URL)
9
+ * therefore crashed the CLI, even when the relay would have served the operation
10
+ * without it; the bunker daemon, the bunker client and the MCP server answer
11
+ * challenges the same way and were exposed alike.
12
+ *
13
+ * Only the automatic answer is quietened: it is the one call made with the
14
+ * relay's own `onauth`. `auth()` keeps its first attempt, so an operation that
15
+ * then needs auth (the on-demand retry) still receives the relay's refusal and
16
+ * reports it.
17
+ */
18
+ function guardAutomaticAuth(relay) {
19
+ if (guardedRelays.has(relay))
20
+ return;
21
+ guardedRelays.add(relay);
22
+ const auth = relay.auth.bind(relay);
23
+ relay.auth = signer => {
24
+ const attempt = auth(signer);
25
+ return signer === relay.onauth ? attempt.catch(() => '') : attempt;
26
+ };
27
+ }
28
+ /**
29
+ * Have a nostr-tools SimplePool answer every relay's NIP-42 challenge as it
30
+ * arrives, with each answer guarded as above. `signerFor` returns the signer
31
+ * for a relay URL, or null to leave that relay unanswered; `undefined` stops
32
+ * answering. Use this rather than setting `pool.automaticallyAuth`.
33
+ */
34
+ export function setAutomaticAuth(pool, signerFor) {
35
+ // The relay map is protected in nostr-tools' types. nostr-tools calls
36
+ // automaticallyAuth from ensureRelay once the relay is in the map and before
37
+ // it connects, so the guard is in place before any challenge can arrive.
38
+ const relays = pool.relays;
39
+ pool.automaticallyAuth = signerFor && ((url) => {
40
+ const sign = signerFor(url);
41
+ const relay = sign ? relays.get(url) : undefined;
42
+ if (relay)
43
+ guardAutomaticAuth(relay);
44
+ return sign;
45
+ });
46
+ }
47
+ /**
48
+ * Whether a resolved per-relay publish result is nostr-tools' report that it
49
+ * could not connect ("connection failure: ..."), which it resolves with instead
50
+ * of rejecting: the event never left this machine. Any other resolved value is
51
+ * the relay's OK message.
52
+ */
53
+ export function isConnectionFailure(value) {
54
+ return typeof value === 'string' && value.startsWith('connection failure: ');
55
+ }
@@ -1,5 +1,6 @@
1
1
  import { validatePublicUrl, validateRelayScheme } from './validation.js';
2
2
  import { brayFetch } from './http-client.js';
3
+ import { isConnectionFailure, setAutomaticAuth } from './nostr-tools-guards.js';
3
4
  // 512 KiB cap on any inbound relay frame. Protects against malicious relays
4
5
  // pushing 100 MB EVENTs that would exhaust memory (ws library defaults to
5
6
  // 100 MB maxPayload, which is far more than any legitimate Nostr event).
@@ -18,14 +19,6 @@ export class Nip77UnavailableError extends Error {
18
19
  this.name = 'Nip77UnavailableError';
19
20
  }
20
21
  }
21
- /**
22
- * Whether a resolved per-relay publish result is nostr-tools' report that it
23
- * could not connect ("connection failure: ..."), which it resolves with instead
24
- * of rejecting. Any other resolved value is the relay's OK message.
25
- */
26
- function isConnectionFailure(value) {
27
- return typeof value === 'string' && value.startsWith('connection failure: ');
28
- }
29
22
  /**
30
23
  * Summarise a publish attempt into the two boolean flags on {@link PublishResult}.
31
24
  *
@@ -59,9 +52,6 @@ async function createRealPool(torProxy) {
59
52
  const WebSocketImpl = webSocketFor(torProxy, { maxPayload: WS_MAX_PAYLOAD });
60
53
  useWebSocketImplementation(WebSocketImpl);
61
54
  const pool = new SimplePool({ websocketImplementation: WebSocketImpl });
62
- // The pool's relay map is protected in nostr-tools' types; the eager guard
63
- // needs the relay that `automaticallyAuth` is being asked about.
64
- const relayMap = pool.relays;
65
55
  return {
66
56
  // `onauth` is spread straight through to the subscription params by
67
57
  // querySync/subscribeEose, so it works despite not being in querySync's
@@ -71,48 +61,10 @@ async function createRealPool(torProxy) {
71
61
  subscribeMany: (relays, filters, handlers) => pool.subscribeMany(relays, filters, handlers),
72
62
  subscribeEose: (relays, filter, handlers) => pool.subscribeEose(relays, filter, handlers),
73
63
  ensureRelay: (url, params) => pool.ensureRelay(url, params),
74
- setAutomaticAuth: signerFor => {
75
- // nostr-tools calls this from ensureRelay, before the relay connects, so
76
- // the guard is in place before any challenge can arrive.
77
- ;
78
- pool.automaticallyAuth = signerFor && ((url) => {
79
- const sign = signerFor(url);
80
- const relay = sign ? relayMap.get(url) : undefined;
81
- if (relay)
82
- guardAutomaticAuth(relay);
83
- return sign;
84
- });
85
- },
64
+ setAutomaticAuth: signerFor => setAutomaticAuth(pool, signerFor),
86
65
  destroy: () => pool.destroy(),
87
66
  };
88
67
  }
89
- const guardedRelays = new WeakSet();
90
- /**
91
- * Keep a refused eager AUTH from ending the process.
92
- *
93
- * nostr-tools answers a relay's challenge with `this.auth(this.onauth)` and
94
- * rethrows any refusal from that promise's `.catch`, where nothing can handle
95
- * it, so Node exits on the unhandled rejection. In eager mode a relay that
96
- * refuses the AUTH (a members-only relay, a key it does not know, an AUTH that
97
- * names another URL) therefore crashed the CLI, even when the relay would have
98
- * served the operation without it. The MCP server uses the same pool and
99
- * installs no unhandledRejection handler, so it is exposed in the same way.
100
- *
101
- * Only the automatic answer is quietened: it is the one call made with the
102
- * relay's own `onauth`. `auth()` keeps its first attempt, so an operation that
103
- * then needs auth (the on-demand retry) still receives the relay's refusal and
104
- * reports it.
105
- */
106
- function guardAutomaticAuth(relay) {
107
- if (guardedRelays.has(relay))
108
- return;
109
- guardedRelays.add(relay);
110
- const auth = relay.auth.bind(relay);
111
- relay.auth = signer => {
112
- const attempt = auth(signer);
113
- return signer === relay.onauth ? attempt.catch(() => '') : attempt;
114
- };
115
- }
116
68
  export class RelayPool {
117
69
  pool;
118
70
  poolReady;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nostr-bray",
3
- "version": "3.12.0",
3
+ "version": "3.12.1",
4
4
  "mcpName": "dev.forgesworn/bray",
5
5
  "description": "Trust-aware Nostr MCP server, CLI and TypeScript SDK for AI agents and humans. Three dimensions of trust -- verification, proximity, and access -- woven into every interaction.",
6
6
  "type": "module",