nostr-bray 3.14.2 → 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.
@@ -151,6 +151,8 @@ export declare class BunkerContext implements SigningContext {
151
151
  get activePublicKeyHex(): string;
152
152
  /** Sign an event via the remote bunker */
153
153
  getSigningFunction(): SignFn;
154
+ /** Signatures come from the remote signer over a relay. A getter, so a Heartwood context re-classed from this one has it too. */
155
+ get remoteSigner(): boolean;
154
156
  /** List identities — bunker mode only has one (the remote key) */
155
157
  listIdentities(): Promise<PublicIdentity[]>;
156
158
  /** NIP-44 encrypt via the remote bunker */
@@ -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, {
@@ -230,6 +231,8 @@ export class BunkerContext {
230
231
  return withTimeout(this.signer.signEvent(template), REQUEST_TIMEOUT_MS, 'bunker sign_event');
231
232
  };
232
233
  }
234
+ /** Signatures come from the remote signer over a relay. A getter, so a Heartwood context re-classed from this one has it too. */
235
+ get remoteSigner() { return true; }
233
236
  /** List identities — bunker mode only has one (the remote key) */
234
237
  async listIdentities() {
235
238
  return [{ npub: this.activeNpub, purpose: 'bunker', index: 0 }];
@@ -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.d.ts CHANGED
@@ -26,6 +26,12 @@ export interface BunkerOptions {
26
26
  open?: boolean;
27
27
  /** Called with the new link each time a client uses up the connect secret. */
28
28
  onUrlChange?: (url: string) => void;
29
+ /**
30
+ * Milliseconds before subscribing again to a relay that ended the
31
+ * subscription (default 5000), doubling up to a minute while the relay
32
+ * keeps refusing or dropping it.
33
+ */
34
+ resubscribeDelayMs?: number;
29
35
  }
30
36
  /**
31
37
  * Remove a client pubkey from every bunker key's approvals in
package/dist/bunker.js CHANGED
@@ -15,8 +15,19 @@ 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
+ const MAX_RESUBSCRIBE_DELAY_MS = 60_000;
21
+ // A subscription that lasted this long was healthy: the next drop starts the
22
+ // backoff again instead of continuing it.
23
+ const HEALTHY_SUBSCRIPTION_MS = 30_000;
24
+ // A resubscription asks for requests from this far back, the longest a client
25
+ // waits on a signature (the bunker client's own timeout), so a request sent
26
+ // during a short outage is still answered.
27
+ const RESUBSCRIBE_WINDOW_SECS = 60;
28
+ // Request ids kept to answer each event once: the same request can arrive from
29
+ // several relays, and again when a resubscription replays it.
30
+ const SEEN_EVENTS_MAX = 2048;
20
31
  /**
21
32
  * Remove a client pubkey from every bunker key's approvals in
22
33
  * approved-clients.json. A running daemon notices on the client's next
@@ -113,19 +124,76 @@ export function startBunker(opts) {
113
124
  // Sign in (NIP-42) with the bunker key when a relay asks, so a private
114
125
  // relay lets the bunker read requests addressed to it.
115
126
  const pool = new SimplePool({ websocketImplementation: webSocketFor(opts.torProxy) });
127
+ guardRelaySends(pool);
116
128
  const answerChallenge = async (template) => finalizeEvent(template, bunkerSk);
117
129
  setAutomaticAuth(pool, () => answerChallenge);
118
- // Subscribe to kind 24133 events addressed to us
119
- const sub = pool.subscribeMany(relays, { kinds: [24133], '#p': [bunkerPk] }, {
120
- onevent: async (event) => {
130
+ // Subscribe to kind 24133 events addressed to us, one subscription per relay
131
+ // so that each can be restored on its own. nostr-tools reports the end of a
132
+ // multi-relay subscription only once every relay has ended it, and it does
133
+ // not reconnect by default, so a relay that drops would otherwise stay
134
+ // unlistened to for as long as another one stayed up.
135
+ const baseResubscribeDelay = opts.resubscribeDelayMs ?? 5_000;
136
+ const seenEvents = new Set();
137
+ const subscriptions = new Map();
138
+ const retries = new Map();
139
+ let closed = false;
140
+ const onEvent = async (event) => {
141
+ if (seenEvents.has(event.id))
142
+ return;
143
+ seenEvents.add(event.id);
144
+ if (seenEvents.size > SEEN_EVENTS_MAX)
145
+ seenEvents.delete(seenEvents.values().next().value);
146
+ try {
147
+ await handleRequest(event);
148
+ }
149
+ catch (e) {
150
+ log(`Error handling request: ${e.message}`);
151
+ }
152
+ };
153
+ // `delayMs` is the wait to use if this subscription ends before it proved
154
+ // healthy; the wait doubles while a relay keeps dropping it.
155
+ function listen(url, delayMs, since) {
156
+ const startedAt = Date.now();
157
+ let ended = false;
158
+ const filter = { kinds: [24133], '#p': [bunkerPk], ...(since === undefined ? {} : { since }) };
159
+ const sub = pool.subscribeMany([url], filter, {
160
+ onevent: onEvent,
161
+ // A members-only relay refuses a REQ that beats the AUTH with
162
+ // `auth-required:`; nostr-tools then authenticates and subscribes again
163
+ // at once, instead of the drop path below waiting out its delay.
164
+ onauth: answerChallenge,
165
+ onclose: reasons => {
166
+ // close() ends every subscription itself; that is not a drop.
167
+ if (closed || ended)
168
+ return;
169
+ ended = true;
170
+ subscriptions.delete(url);
171
+ const why = reasons.map(r => r.reason).join('; ') || 'no reason given';
172
+ const wait = Date.now() - startedAt >= HEALTHY_SUBSCRIPTION_MS ? baseResubscribeDelay : delayMs;
173
+ log(`Subscription on ${url} ended (${why}); subscribing again in ${wait} ms`);
174
+ retry(url, wait);
175
+ },
176
+ });
177
+ subscriptions.set(url, sub);
178
+ }
179
+ function retry(url, waitMs) {
180
+ const nextMs = Math.min(waitMs * 2, MAX_RESUBSCRIBE_DELAY_MS);
181
+ retries.set(url, setTimeout(() => {
182
+ retries.delete(url);
183
+ if (closed)
184
+ return;
121
185
  try {
122
- await handleRequest(event);
186
+ listen(url, nextMs, Math.floor(Date.now() / 1000) - RESUBSCRIBE_WINDOW_SECS);
187
+ log(`Subscribed again on ${url}`);
123
188
  }
124
189
  catch (e) {
125
- log(`Error handling request: ${e.message}`);
190
+ log(`Could not subscribe again on ${url}: ${e.message}; trying again in ${nextMs} ms`);
191
+ retry(url, nextMs);
126
192
  }
127
- },
128
- });
193
+ }, waitMs));
194
+ }
195
+ for (const url of new Set(relays))
196
+ listen(url, baseResubscribeDelay);
129
197
  // `bunker revoke` edits the approvals file while the daemon runs, so a
130
198
  // client approved in memory is checked against the file before each request.
131
199
  function stillApproved(clientPk) {
@@ -393,7 +461,13 @@ export function startBunker(opts) {
393
461
  pubkey: bunkerPk,
394
462
  npub: bunkerNpub,
395
463
  close: () => {
396
- sub.close();
464
+ closed = true;
465
+ for (const timer of retries.values())
466
+ clearTimeout(timer);
467
+ retries.clear();
468
+ for (const sub of subscriptions.values())
469
+ sub.close();
470
+ subscriptions.clear();
397
471
  pool.destroy();
398
472
  bunkerSk.fill(0);
399
473
  },
@@ -403,6 +403,7 @@ export async function dispatch(args) {
403
403
  }
404
404
  // Bunker daemon
405
405
  const { startBunker } = await import('../../bunker.js');
406
+ const { holdProcessOpen } = await import('../../hold-open.js');
406
407
  const { readNsecTreeProfileMnemonic, getOrCreateBunkerKey } = await import('../../bunker-helpers.js');
407
408
  // --profile <name>: load the master straight from an nsec-tree-cli profile
408
409
  // (~/.nsec-tree/profiles/<name>.json). loadConfig scrubs NOSTR_SECRET_KEY after.
@@ -477,7 +478,12 @@ export async function dispatch(args) {
477
478
  }
478
479
  console.error(`Signing as: ${bCtx.activeNpub}`);
479
480
  console.error('Press Ctrl+C to stop');
480
- process.on('SIGINT', () => { bunker.close(); bCtx.destroy(); process.exit(0); });
481
- process.on('SIGTERM', () => { bunker.close(); bCtx.destroy(); process.exit(0); });
482
- await new Promise(() => { });
481
+ // The daemon is held up by a timer, not by its relay sockets: a relay that
482
+ // restarts or an idle close must not leave the process with nothing to wait
483
+ // for (Node then exits with code 13). The bunker resubscribes on its own.
484
+ const hold = holdProcessOpen();
485
+ const stop = () => { hold.release(); bunker.close(); bCtx.destroy(); process.exit(0); };
486
+ process.on('SIGINT', stop);
487
+ process.on('SIGTERM', stop);
488
+ await hold.done;
483
489
  }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Keep the process alive until released.
3
+ *
4
+ * A long-running daemon must not end with `await new Promise(() => {})`: that
5
+ * promise holds no event-loop handle, so the moment the last socket closes
6
+ * Node finds nothing left to wait for and exits with code 13 ("unsettled
7
+ * top-level await"). A timer is a handle, so this holds the loop open however
8
+ * the sockets behave. Release it from the shutdown path.
9
+ */
10
+ export declare function holdProcessOpen(): {
11
+ done: Promise<void>;
12
+ release: () => void;
13
+ };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Keep the process alive until released.
3
+ *
4
+ * A long-running daemon must not end with `await new Promise(() => {})`: that
5
+ * promise holds no event-loop handle, so the moment the last socket closes
6
+ * Node finds nothing left to wait for and exits with code 13 ("unsettled
7
+ * top-level await"). A timer is a handle, so this holds the loop open however
8
+ * the sockets behave. Release it from the shutdown path.
9
+ */
10
+ export function holdProcessOpen() {
11
+ let release;
12
+ const done = new Promise(resolve => {
13
+ const timer = setInterval(() => { }, 60_000);
14
+ release = () => {
15
+ clearInterval(timer);
16
+ resolve();
17
+ };
18
+ });
19
+ return { done, release };
20
+ }
@@ -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
@@ -18,6 +18,12 @@ export interface RelayAuthResult {
18
18
  * ignores TOR_PROXY, and closes that connection once authenticated, so the
19
19
  * AUTH applies to nothing else. It only shows that the relay accepts the key.
20
20
  *
21
+ * Waits: connecting and the challenge each get `timeoutMs` (default 5 s).
22
+ * The signature gets the same, except that a remote signer (NIP-46) gets the
23
+ * bunker client's own request limit, since it signs over a relay and may wait
24
+ * on a person to approve. An explicit `timeoutMs` applies to all three. The
25
+ * relay's OK keeps nostr-tools' own 4.4 s. The error says which step timed out.
26
+ *
21
27
  * Flow:
22
28
  * 1. Connect via WebSocket
23
29
  * 2. Wait for ["AUTH", challenge] message
@@ -25,4 +31,6 @@ export interface RelayAuthResult {
25
31
  * 4. Send ["AUTH", signedEvent]
26
32
  * 5. Wait for ["OK", eventId, true, ...] confirmation
27
33
  */
28
- export declare function handleRelayAuth(ctx: SigningContext, relay: string, pool?: RelayPool): Promise<RelayAuthResult>;
34
+ export declare function handleRelayAuth(ctx: SigningContext, relay: string, pool?: RelayPool, opts?: {
35
+ timeoutMs?: number;
36
+ }): Promise<RelayAuthResult>;
@@ -1,5 +1,6 @@
1
1
  import { validateRelayUrl } from './handlers.js';
2
2
  import { errorMessage } from '../error-message.js';
3
+ import { REQUEST_TIMEOUT_MS } from '../bunker-context.js';
3
4
  /**
4
5
  * Authenticate to a relay that requires NIP-42 AUTH.
5
6
  *
@@ -12,6 +13,12 @@ import { errorMessage } from '../error-message.js';
12
13
  * ignores TOR_PROXY, and closes that connection once authenticated, so the
13
14
  * AUTH applies to nothing else. It only shows that the relay accepts the key.
14
15
  *
16
+ * Waits: connecting and the challenge each get `timeoutMs` (default 5 s).
17
+ * The signature gets the same, except that a remote signer (NIP-46) gets the
18
+ * bunker client's own request limit, since it signs over a relay and may wait
19
+ * on a person to approve. An explicit `timeoutMs` applies to all three. The
20
+ * relay's OK keeps nostr-tools' own 4.4 s. The error says which step timed out.
21
+ *
15
22
  * Flow:
16
23
  * 1. Connect via WebSocket
17
24
  * 2. Wait for ["AUTH", challenge] message
@@ -19,10 +26,11 @@ import { errorMessage } from '../error-message.js';
19
26
  * 4. Send ["AUTH", signedEvent]
20
27
  * 5. Wait for ["OK", eventId, true, ...] confirmation
21
28
  */
22
- export async function handleRelayAuth(ctx, relay, pool) {
29
+ export async function handleRelayAuth(ctx, relay, pool, opts = {}) {
23
30
  if (pool) {
24
31
  validateRelayUrl(relay, { allowPrivate: pool.allowsPrivateRelays?.() === true });
25
- return pool.authenticate(relay);
32
+ const signTimeoutMs = opts.timeoutMs === undefined && ctx.remoteSigner === true ? REQUEST_TIMEOUT_MS : undefined;
33
+ return pool.authenticate(relay, { timeoutMs: opts.timeoutMs, signTimeoutMs });
26
34
  }
27
35
  validateRelayUrl(relay); // throws on private IPs -- intentionally not caught
28
36
  return new Promise((resolve) => {
@@ -207,14 +207,15 @@ export function registerRelayTools(server, deps) {
207
207
  };
208
208
  });
209
209
  server.registerTool('relay-auth', {
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.',
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. Connecting, the challenge and the signature each wait 5 seconds, except that a remote signer (NIP-46 bunker or hardware signer) gets up to 60 seconds to sign; the relay then has 4.4 seconds to accept the signed AUTH. A timeout names the step. timeout_ms sets the wait for connecting, the challenge and the signature.',
211
211
  inputSchema: {
212
212
  relay: relayUrl.describe('Relay WebSocket URL to authenticate with'),
213
+ timeout_ms: z.number().int().min(1_000).max(120_000).optional().describe('Wait in milliseconds for connecting, the challenge and the signature (1000 to 120000). Default 5000, and 60000 for the signature when the identity signs through a remote signer.'),
213
214
  },
214
215
  annotations: { readOnlyHint: false },
215
- }, async ({ relay }) => {
216
+ }, async ({ relay, timeout_ms }) => {
216
217
  // On the pool's own connection, so the retried query is authenticated.
217
- const result = await handleRelayAuth(deps.ctx, relay, deps.pool);
218
+ const result = await handleRelayAuth(deps.ctx, relay, deps.pool, { timeoutMs: timeout_ms });
218
219
  return {
219
220
  content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
220
221
  };
@@ -223,9 +223,17 @@ export declare class RelayPool {
223
223
  * that carried another identity's traffic is replaced first; after a refusal
224
224
  * the connection is dropped, since nostr-tools keeps its first attempt and a
225
225
  * second try on it would only repeat the refusal.
226
+ *
227
+ * Each step has its own wait, and a timeout names the step. `timeoutMs`
228
+ * (default 5 s) bounds the connection and the challenge. `signTimeoutMs`
229
+ * bounds the signature and defaults to `timeoutMs`: a signer that answers
230
+ * over a relay (NIP-46) needs far longer than a local key, so the caller
231
+ * gives it the remote signer's own limit. The relay's OK is bounded by
232
+ * nostr-tools itself (the connection's publish timeout, 4.4 s by default).
226
233
  */
227
234
  authenticate(url: string, opts?: {
228
235
  timeoutMs?: number;
236
+ signTimeoutMs?: number;
229
237
  }): Promise<{
230
238
  authenticated: boolean;
231
239
  relay: string;
@@ -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.
@@ -88,6 +89,22 @@ async function createRealPool(torProxy) {
88
89
  destroy: () => pool.destroy(),
89
90
  };
90
91
  }
92
+ /** An AUTH step that did not finish in time. */
93
+ class AuthTimeout extends Error {
94
+ constructor(step, ms) {
95
+ super(step === 'signature'
96
+ ? `AUTH timed out: no signature within ${ms} ms (the signer did not answer; if it is a remote signer, approve the request there)`
97
+ : `AUTH timed out: the relay did not answer the signed AUTH within ${ms} ms`);
98
+ }
99
+ }
100
+ /** The signer refused or failed. nostr-tools drops that error, so it is carried out separately. */
101
+ class AuthNotSigned extends Error {
102
+ constructor(reason) {
103
+ super(`AUTH not signed: ${errorMessage(reason)}`);
104
+ }
105
+ }
106
+ /** nostr-tools' own wait for the relay's OK to a signed AUTH (its `publishTimeout`). */
107
+ const NOSTR_TOOLS_OK_WAIT_MS = 4_400;
91
108
  export class RelayPool {
92
109
  pool;
93
110
  poolReady;
@@ -523,6 +540,13 @@ export class RelayPool {
523
540
  * that carried another identity's traffic is replaced first; after a refusal
524
541
  * the connection is dropped, since nostr-tools keeps its first attempt and a
525
542
  * second try on it would only repeat the refusal.
543
+ *
544
+ * Each step has its own wait, and a timeout names the step. `timeoutMs`
545
+ * (default 5 s) bounds the connection and the challenge. `signTimeoutMs`
546
+ * bounds the signature and defaults to `timeoutMs`: a signer that answers
547
+ * over a relay (NIP-46) needs far longer than a local key, so the caller
548
+ * gives it the remote signer's own limit. The relay's OK is bounded by
549
+ * nostr-tools itself (the connection's publish timeout, 4.4 s by default).
526
550
  */
527
551
  async authenticate(url, opts = {}) {
528
552
  this.#validateDirectRelays([url]);
@@ -532,6 +556,7 @@ export class RelayPool {
532
556
  if (!pool.ensureRelay)
533
557
  return { authenticated: false, relay: url, error: 'the underlying relay pool cannot authenticate' };
534
558
  const timeoutMs = opts.timeoutMs ?? 5_000;
559
+ const signTimeoutMs = opts.signTimeoutMs ?? timeoutMs;
535
560
  const { normalizeURL } = await import('nostr-tools/utils');
536
561
  const current = this.#activePubkey();
537
562
  const owner = this.#connectionOwners.get(normalizeURL(url));
@@ -551,21 +576,59 @@ export class RelayPool {
551
576
  let probed = false;
552
577
  while (!challenge()) {
553
578
  if (Date.now() >= deadline)
554
- return { authenticated: false, relay: url, error: 'AUTH handshake timed out (no challenge received)' };
579
+ return { authenticated: false, relay: url, error: `AUTH handshake timed out (no challenge received within ${timeoutMs} ms)` };
555
580
  if (!probed && Date.now() >= probeAt) {
556
581
  probed = true;
557
582
  const probe = relay.subscribe([{ limit: 0 }], { onevent: () => { }, oneose: () => probe.close(), onclose: () => { } });
558
583
  }
559
584
  await new Promise(resolve => setTimeout(resolve, 25));
560
585
  }
586
+ // relay.auth signs, sends and waits for the relay's OK. nostr-tools 2.24
587
+ // bounds the OK itself, from the moment the signature is in, but it catches
588
+ // an error from the signer, logs it and never settles. So bray bounds the
589
+ // signature, carries a refusal out of the signing wrapper, and labels the
590
+ // outcome by what that wrapper saw.
591
+ let timer;
592
+ let signed = false;
593
+ let settled = false;
594
+ let refuse = () => { };
595
+ const stopped = new Promise((_, reject) => {
596
+ refuse = reject;
597
+ timer = setTimeout(() => reject(new AuthTimeout('signature', signTimeoutMs)), signTimeoutMs);
598
+ });
599
+ const signForRelay = async (evt) => {
600
+ try {
601
+ const event = await this.#signAuth(evt);
602
+ if (!settled) {
603
+ signed = true;
604
+ clearTimeout(timer);
605
+ }
606
+ return event;
607
+ }
608
+ catch (err) {
609
+ if (!settled)
610
+ refuse(new AuthNotSigned(err));
611
+ throw err;
612
+ }
613
+ };
561
614
  try {
562
- await within(timeoutMs, relay.auth(this.#signAuth), 'AUTH timed out');
615
+ await Promise.race([relay.auth(signForRelay), stopped]);
563
616
  return { authenticated: true, relay: url, pubkey: this.#connectionOwners.get(relay.url)?.authedBy ?? current };
564
617
  }
565
618
  catch (err) {
566
619
  pool.forget?.(url);
620
+ if (err instanceof AuthTimeout || err instanceof AuthNotSigned)
621
+ return { authenticated: false, relay: url, error: err.message };
622
+ if (signed && errorMessage(err) === 'auth timed out') {
623
+ const okWait = relay.publishTimeout ?? NOSTR_TOOLS_OK_WAIT_MS;
624
+ return { authenticated: false, relay: url, error: new AuthTimeout('relay OK', okWait).message };
625
+ }
567
626
  return { authenticated: false, relay: url, error: `AUTH rejected: ${errorMessage(err)}` };
568
627
  }
628
+ finally {
629
+ settled = true;
630
+ clearTimeout(timer);
631
+ }
569
632
  }
570
633
  /** Reconcile local event IDs with one relay using NIP-77 Negentropy. */
571
634
  async reconcileDirect(relayUrl, items, filter, opts = {}) {
@@ -4,6 +4,12 @@ import type { PublicIdentity, SignFn } from './types.js';
4
4
  export interface SigningContext {
5
5
  readonly activeNpub: string;
6
6
  readonly activePublicKeyHex: string;
7
+ /**
8
+ * True when signatures come from another device or process over a relay
9
+ * (NIP-46), so a signature takes seconds, not microseconds, and may wait on
10
+ * a person. Unset for a local key.
11
+ */
12
+ readonly remoteSigner?: boolean;
7
13
  getSigningFunction(): SignFn;
8
14
  listIdentities(): Promise<PublicIdentity[]>;
9
15
  nip44Encrypt(recipientPubkey: string, plaintext: string): Promise<string>;
package/llms-full.txt CHANGED
@@ -594,8 +594,8 @@ Count events matching a filter without fetching (NIP-45). Falls back to fetch-an
594
594
  - Input: relays, kinds (optional), authors (optional), tags (optional), since (optional), until (optional)
595
595
 
596
596
  #### relay-auth
597
- Authenticate to a relay requiring NIP-42 AUTH. Signs a kind 22242 event.
598
- - Input: relay (URL)
597
+ Authenticate to a relay requiring NIP-42 AUTH. Signs a kind 22242 event. Connecting, the challenge and the signature wait 5 s each; a remote signer gets 60 s to sign, and a timeout names the step.
598
+ - Input: relay (URL), timeout_ms (optional, 1000-120000, wait for connecting, the challenge and the signature)
599
599
 
600
600
  #### relay-discover
601
601
  Discover relays used by your contacts. Fetches NIP-65 relay lists from your follow list, ranks by popularity.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nostr-bray",
3
- "version": "3.14.2",
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",