nostr-bray 3.14.3 → 3.14.4

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,7 +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
+ import { guardRelaySends, setAutomaticAuth } from './nostr-tools-guards.js';
21
21
  import { readStateFile, writeStateFile } from './state.js';
22
22
  import { errorMessage } from './error-message.js';
23
23
  /** Bound the NIP-46 connect handshake. nostr-tools' BunkerSigner has no
@@ -141,6 +141,7 @@ export class BunkerContext {
141
141
  // relays that only let a key read messages addressed to it still work.
142
142
  // Its own WebSocket class, so TOR_PROXY applies to signer traffic too.
143
143
  const pool = new SimplePool({ websocketImplementation: webSocketFor(options.torProxy) });
144
+ guardRelaySends(pool);
144
145
  const answerChallenge = async (template) => finalizeEvent(template, clientSk);
145
146
  setAutomaticAuth(pool, () => answerChallenge);
146
147
  const signer = BunkerSigner.fromBunker(clientSk, {
@@ -24,7 +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
+ import { guardRelaySends, setAutomaticAuth } from './nostr-tools-guards.js';
28
28
  import { errorMessage } from './error-message.js';
29
29
  /** Saved by `bunker connect` and `bunker pair`; read by loadConfig. */
30
30
  export const BUNKER_URI_FILE = 'bunker-uri';
@@ -73,6 +73,7 @@ export async function pairWithNostrConnect(options) {
73
73
  // Answer NIP-42 challenges with the client key, as BunkerContext does.
74
74
  // With TOR_PROXY set, pairing goes through the proxy like bray's other relay traffic.
75
75
  const pool = new SimplePool({ websocketImplementation: webSocketFor(options.torProxy) });
76
+ guardRelaySends(pool);
76
77
  const answerChallenge = async (template) => finalizeEvent(template, clientSk);
77
78
  setAutomaticAuth(pool, () => answerChallenge);
78
79
  const timeoutMs = options.timeoutMs ?? PAIR_TIMEOUT_MS;
package/dist/bunker.js CHANGED
@@ -15,7 +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
+ import { guardRelaySends, isConnectionFailure, setAutomaticAuth } from './nostr-tools-guards.js';
19
19
  import { readStateFile, readStateFileStrict, writeStateFile } from './state.js';
20
20
  const MAX_RESUBSCRIBE_DELAY_MS = 60_000;
21
21
  // A subscription that lasted this long was healthy: the next drop starts the
@@ -124,6 +124,7 @@ export function startBunker(opts) {
124
124
  // Sign in (NIP-42) with the bunker key when a relay asks, so a private
125
125
  // relay lets the bunker read requests addressed to it.
126
126
  const pool = new SimplePool({ websocketImplementation: webSocketFor(opts.torProxy) });
127
+ guardRelaySends(pool);
127
128
  const answerChallenge = async (template) => finalizeEvent(template, bunkerSk);
128
129
  setAutomaticAuth(pool, () => answerChallenge);
129
130
  // Subscribe to kind 24133 events addressed to us, one subscription per relay
@@ -1,6 +1,6 @@
1
1
  import type { EventTemplate, VerifiedEvent } from 'nostr-tools';
2
2
  /**
3
- * Guards for two nostr-tools (2.24) behaviours that otherwise mislead or crash
3
+ * Guards for three nostr-tools (2.24) behaviours that otherwise mislead or crash
4
4
  * bray. Every pool bray creates goes through these: the relay pool, the bunker
5
5
  * daemon, the bunker client and bunker pairing.
6
6
  */
@@ -13,6 +13,11 @@ export type ChallengeSigner = (evt: EventTemplate) => Promise<VerifiedEvent>;
13
13
  * answering. Use this rather than setting `pool.automaticallyAuth`.
14
14
  */
15
15
  export declare function setAutomaticAuth(pool: object, signerFor: ((relayUrl: string) => ChallengeSigner | null) | undefined): void;
16
+ /**
17
+ * Guard every relay a nostr-tools SimplePool connects to, as above. Call it
18
+ * once, straight after creating the pool.
19
+ */
20
+ export declare function guardRelaySends(pool: object): void;
16
21
  /**
17
22
  * Whether a resolved per-relay publish result is nostr-tools' report that it
18
23
  * could not connect ("connection failure: ..."), which it resolves with instead
@@ -44,6 +44,67 @@ export function setAutomaticAuth(pool, signerFor) {
44
44
  return sign;
45
45
  });
46
46
  }
47
+ const sendGuardedRelays = new WeakSet();
48
+ /**
49
+ * Keep a send on a closed connection from ending the process.
50
+ *
51
+ * nostr-tools sends an AUTH answer, and a subscription's REQ, without awaiting
52
+ * the send, and `send` rejects once the connection has closed. A relay that
53
+ * dropped the connection while the AUTH signature was still being made (a
54
+ * remote signer can take many seconds) therefore left a rejection nothing
55
+ * handled, and Node exited. Every send gets a handler here. A failed AUTH send
56
+ * also fails that AUTH at once with the send's error, the one nostr-tools'
57
+ * own automatic answer already ignores, instead of leaving it to report
58
+ * "auth timed out" seconds later.
59
+ */
60
+ function guardSends(relay) {
61
+ if (sendGuardedRelays.has(relay))
62
+ return;
63
+ sendGuardedRelays.add(relay);
64
+ const send = relay.send.bind(relay);
65
+ relay.send = message => {
66
+ const sent = send(message);
67
+ sent.catch(err => { if (message.startsWith('["AUTH",'))
68
+ failPendingAuth(relay, message, err); });
69
+ return sent;
70
+ };
71
+ }
72
+ function failPendingAuth(relay, message, err) {
73
+ let id;
74
+ try {
75
+ id = JSON.parse(message)[1]?.id;
76
+ }
77
+ catch {
78
+ return;
79
+ }
80
+ if (typeof id !== 'string')
81
+ return;
82
+ const pending = relay.openEventPublishes;
83
+ const entry = pending.get(id);
84
+ if (!entry)
85
+ return;
86
+ clearTimeout(entry.timeout);
87
+ pending.delete(id);
88
+ entry.reject(err);
89
+ }
90
+ /**
91
+ * Guard every relay a nostr-tools SimplePool connects to, as above. Call it
92
+ * once, straight after creating the pool.
93
+ */
94
+ export function guardRelaySends(pool) {
95
+ // The relay map is protected in nostr-tools' types. ensureRelay is the only
96
+ // place a relay is made, and it adds the relay to the map before it starts
97
+ // connecting, so the relay is guarded before any message can arrive. The map
98
+ // is read on each call because destroy() replaces it.
99
+ const p = pool;
100
+ const ensureRelay = p.ensureRelay.bind(pool);
101
+ p.ensureRelay = (...args) => {
102
+ const ready = ensureRelay(...args);
103
+ for (const relay of p.relays.values())
104
+ guardSends(relay);
105
+ return ready;
106
+ };
107
+ }
47
108
  /**
48
109
  * Whether a resolved per-relay publish result is nostr-tools' report that it
49
110
  * could not connect ("connection failure: ..."), which it resolves with instead
@@ -1,6 +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
+ import { guardRelaySends, isConnectionFailure, setAutomaticAuth } from './nostr-tools-guards.js';
4
4
  import { errorMessage } from './error-message.js';
5
5
  // 512 KiB cap on any inbound relay frame. Protects against malicious relays
6
6
  // pushing 100 MB EVENTs that would exhaust memory (ws library defaults to
@@ -61,6 +61,7 @@ async function createRealPool(torProxy) {
61
61
  const WebSocketImpl = webSocketFor(torProxy, { maxPayload: WS_MAX_PAYLOAD });
62
62
  useWebSocketImplementation(WebSocketImpl);
63
63
  const pool = new SimplePool({ websocketImplementation: WebSocketImpl });
64
+ guardRelaySends(pool);
64
65
  const { normalizeURL } = await import('nostr-tools/utils');
65
66
  // nostr-tools reaches every relay through ensureRelay, so this is where a
66
67
  // connection can be refused reuse. The relay map is protected in its types.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nostr-bray",
3
- "version": "3.14.3",
3
+ "version": "3.14.4",
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",