nostr-bray 3.14.1 → 3.14.3

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 */
@@ -19,6 +19,7 @@ import { npubEncode } from 'nostr-tools/nip19';
19
19
  import { webSocketFor } from './ws-safe.js';
20
20
  import { setAutomaticAuth } from './nostr-tools-guards.js';
21
21
  import { readStateFile, writeStateFile } from './state.js';
22
+ import { errorMessage } from './error-message.js';
22
23
  /** Bound the NIP-46 connect handshake. nostr-tools' BunkerSigner has no
23
24
  * per-request timeout, so an offline signer or unreachable relays make the
24
25
  * connect hang forever. A hardware signer (e.g. Heartwood) may also wait on
@@ -176,7 +177,7 @@ export class BunkerContext {
176
177
  }
177
178
  catch (e) {
178
179
  // Most likely the app has been revoked or reinstalled: say how to fix it.
179
- throw new Error(`${e.message}. If the signer app no longer lists bray, ${PAIRED_REPAIR_HINT}`);
180
+ throw new Error(`${errorMessage(e)}. If the signer app no longer lists bray, ${PAIRED_REPAIR_HINT}`);
180
181
  }
181
182
  return;
182
183
  }
@@ -229,6 +230,8 @@ export class BunkerContext {
229
230
  return withTimeout(this.signer.signEvent(template), REQUEST_TIMEOUT_MS, 'bunker sign_event');
230
231
  };
231
232
  }
233
+ /** Signatures come from the remote signer over a relay. A getter, so a Heartwood context re-classed from this one has it too. */
234
+ get remoteSigner() { return true; }
232
235
  /** List identities — bunker mode only has one (the remote key) */
233
236
  async listIdentities() {
234
237
  return [{ npub: this.activeNpub, purpose: 'bunker', index: 0 }];
@@ -25,15 +25,13 @@ import { readStateFile, writeStateFile } from './state.js';
25
25
  import { isOnionUrl, validateRelayScheme } from './validation.js';
26
26
  import { webSocketFor } from './ws-safe.js';
27
27
  import { setAutomaticAuth } from './nostr-tools-guards.js';
28
+ import { errorMessage } from './error-message.js';
28
29
  /** Saved by `bunker connect` and `bunker pair`; read by loadConfig. */
29
30
  export const BUNKER_URI_FILE = 'bunker-uri';
30
31
  /** NIP-46 request and response events. */
31
32
  const NOSTR_CONNECT_KIND = 24133;
32
33
  /** How long to try to reach each relay before leaving it out. */
33
34
  const CONNECT_WAIT_MS = 10_000;
34
- function reasonText(reason) {
35
- return reason instanceof Error ? reason.message : String(reason);
36
- }
37
35
  /** Show the URI after this long even if a relay has not confirmed the subscription. */
38
36
  const LISTEN_WAIT_MS = 5_000;
39
37
  function sameSecret(a, b) {
@@ -88,7 +86,7 @@ export async function pairWithNostrConnect(options) {
88
86
  const reachable = relays.filter((_relay, i) => attempts[i].status === 'fulfilled');
89
87
  attempts.forEach((attempt, i) => {
90
88
  if (attempt.status === 'rejected')
91
- options.onRelayUnreachable?.(relays[i], reasonText(attempt.reason));
89
+ options.onRelayUnreachable?.(relays[i], errorMessage(attempt.reason));
92
90
  });
93
91
  if (reachable.length === 0) {
94
92
  throw new Error(`could not reach any relay: ${relays.join(', ').slice(0, 256)}`);
@@ -138,7 +136,7 @@ export async function pairWithNostrConnect(options) {
138
136
  if (e instanceof TimeoutError) {
139
137
  throw new Error(`no signer answered within ${Math.round(timeoutMs / 1000)}s`);
140
138
  }
141
- throw new Error(`could not listen on the relays: ${e.message}`);
139
+ throw new Error(`could not listen on the relays: ${errorMessage(e)}`);
142
140
  }
143
141
  sub?.close();
144
142
  sub = undefined;
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
@@ -17,6 +17,17 @@ import { SimplePool } from 'nostr-tools/pool';
17
17
  import { webSocketFor } from './ws-safe.js';
18
18
  import { 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
@@ -115,17 +126,73 @@ export function startBunker(opts) {
115
126
  const pool = new SimplePool({ websocketImplementation: webSocketFor(opts.torProxy) });
116
127
  const answerChallenge = async (template) => finalizeEvent(template, bunkerSk);
117
128
  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) => {
129
+ // Subscribe to kind 24133 events addressed to us, one subscription per relay
130
+ // so that each can be restored on its own. nostr-tools reports the end of a
131
+ // multi-relay subscription only once every relay has ended it, and it does
132
+ // not reconnect by default, so a relay that drops would otherwise stay
133
+ // unlistened to for as long as another one stayed up.
134
+ const baseResubscribeDelay = opts.resubscribeDelayMs ?? 5_000;
135
+ const seenEvents = new Set();
136
+ const subscriptions = new Map();
137
+ const retries = new Map();
138
+ let closed = false;
139
+ const onEvent = async (event) => {
140
+ if (seenEvents.has(event.id))
141
+ return;
142
+ seenEvents.add(event.id);
143
+ if (seenEvents.size > SEEN_EVENTS_MAX)
144
+ seenEvents.delete(seenEvents.values().next().value);
145
+ try {
146
+ await handleRequest(event);
147
+ }
148
+ catch (e) {
149
+ log(`Error handling request: ${e.message}`);
150
+ }
151
+ };
152
+ // `delayMs` is the wait to use if this subscription ends before it proved
153
+ // healthy; the wait doubles while a relay keeps dropping it.
154
+ function listen(url, delayMs, since) {
155
+ const startedAt = Date.now();
156
+ let ended = false;
157
+ const filter = { kinds: [24133], '#p': [bunkerPk], ...(since === undefined ? {} : { since }) };
158
+ const sub = pool.subscribeMany([url], filter, {
159
+ onevent: onEvent,
160
+ // A members-only relay refuses a REQ that beats the AUTH with
161
+ // `auth-required:`; nostr-tools then authenticates and subscribes again
162
+ // at once, instead of the drop path below waiting out its delay.
163
+ onauth: answerChallenge,
164
+ onclose: reasons => {
165
+ // close() ends every subscription itself; that is not a drop.
166
+ if (closed || ended)
167
+ return;
168
+ ended = true;
169
+ subscriptions.delete(url);
170
+ const why = reasons.map(r => r.reason).join('; ') || 'no reason given';
171
+ const wait = Date.now() - startedAt >= HEALTHY_SUBSCRIPTION_MS ? baseResubscribeDelay : delayMs;
172
+ log(`Subscription on ${url} ended (${why}); subscribing again in ${wait} ms`);
173
+ retry(url, wait);
174
+ },
175
+ });
176
+ subscriptions.set(url, sub);
177
+ }
178
+ function retry(url, waitMs) {
179
+ const nextMs = Math.min(waitMs * 2, MAX_RESUBSCRIBE_DELAY_MS);
180
+ retries.set(url, setTimeout(() => {
181
+ retries.delete(url);
182
+ if (closed)
183
+ return;
121
184
  try {
122
- await handleRequest(event);
185
+ listen(url, nextMs, Math.floor(Date.now() / 1000) - RESUBSCRIBE_WINDOW_SECS);
186
+ log(`Subscribed again on ${url}`);
123
187
  }
124
188
  catch (e) {
125
- log(`Error handling request: ${e.message}`);
189
+ log(`Could not subscribe again on ${url}: ${e.message}; trying again in ${nextMs} ms`);
190
+ retry(url, nextMs);
126
191
  }
127
- },
128
- });
192
+ }, waitMs));
193
+ }
194
+ for (const url of new Set(relays))
195
+ listen(url, baseResubscribeDelay);
129
196
  // `bunker revoke` edits the approvals file while the daemon runs, so a
130
197
  // client approved in memory is checked against the file before each request.
131
198
  function stillApproved(clientPk) {
@@ -393,7 +460,13 @@ export function startBunker(opts) {
393
460
  pubkey: bunkerPk,
394
461
  npub: bunkerNpub,
395
462
  close: () => {
396
- sub.close();
463
+ closed = true;
464
+ for (const timer of retries.values())
465
+ clearTimeout(timer);
466
+ retries.clear();
467
+ for (const sub of subscriptions.values())
468
+ sub.close();
469
+ subscriptions.clear();
397
470
  pool.destroy();
398
471
  bunkerSk.fill(0);
399
472
  },
@@ -1,9 +1,3 @@
1
- /**
2
- * Bunker command module.
3
- * bunker sign, bunker connect, bunker pair, bunker authorize, bunker revoke, bunker status, and bunker daemon
4
- * are all dispatched BEFORE ctx/pool setup in index.ts, so this module does its
5
- * own config/context construction.
6
- */
7
1
  /**
8
2
  * Apply `--persona <name>` to a bunker context: switch signing to that named
9
3
  * sub-identity (the same key `nsec-tree-cli export nsec <name>` yields). With no
@@ -1,3 +1,4 @@
1
+ import { errorMessage } from '../../error-message.js';
1
2
  /**
2
3
  * Bunker command module.
3
4
  * bunker sign, bunker connect, bunker pair, bunker authorize, bunker revoke, bunker status, and bunker daemon
@@ -62,7 +63,7 @@ export async function dispatch(args) {
62
63
  await client.resolvePublicKey();
63
64
  }
64
65
  catch (err) {
65
- console.error(`bunker connect: failed to connect — ${err.message}`);
66
+ console.error(`bunker connect: failed to connect — ${errorMessage(err)}`);
66
67
  process.exit(1);
67
68
  }
68
69
  const hw = await HeartwoodContext.probe(client);
@@ -210,7 +211,7 @@ export async function dispatch(args) {
210
211
  console.error('bunker pair: not saved.');
211
212
  }
212
213
  else {
213
- console.error(`bunker pair: ${err.message}`);
214
+ console.error(`bunker pair: ${errorMessage(err)}`);
214
215
  }
215
216
  process.exit(1);
216
217
  }
@@ -329,7 +330,7 @@ export async function dispatch(args) {
329
330
  removed = revokeClient(clientPk);
330
331
  }
331
332
  catch (err) {
332
- console.error(`bunker revoke: ${err.message}`);
333
+ console.error(`bunker revoke: ${errorMessage(err)}`);
333
334
  process.exit(1);
334
335
  }
335
336
  if (removed === 0) {
@@ -402,6 +403,7 @@ export async function dispatch(args) {
402
403
  }
403
404
  // Bunker daemon
404
405
  const { startBunker } = await import('../../bunker.js');
406
+ const { holdProcessOpen } = await import('../../hold-open.js');
405
407
  const { readNsecTreeProfileMnemonic, getOrCreateBunkerKey } = await import('../../bunker-helpers.js');
406
408
  // --profile <name>: load the master straight from an nsec-tree-cli profile
407
409
  // (~/.nsec-tree/profiles/<name>.json). loadConfig scrubs NOSTR_SECRET_KEY after.
@@ -434,7 +436,7 @@ export async function dispatch(args) {
434
436
  bunkerKeyHex = getOrCreateBunkerKey(persona ?? profileName ?? 'default');
435
437
  }
436
438
  catch (err) {
437
- console.error(`bunker: ${err.message}`);
439
+ console.error(`bunker: ${errorMessage(err)}`);
438
440
  process.exit(1);
439
441
  }
440
442
  }
@@ -476,7 +478,12 @@ export async function dispatch(args) {
476
478
  }
477
479
  console.error(`Signing as: ${bCtx.activeNpub}`);
478
480
  console.error('Press Ctrl+C to stop');
479
- process.on('SIGINT', () => { bunker.close(); bCtx.destroy(); process.exit(0); });
480
- process.on('SIGTERM', () => { bunker.close(); bCtx.destroy(); process.exit(0); });
481
- 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;
482
489
  }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The text of a thrown or rejected value.
3
+ *
4
+ * Not everything that rejects is an Error. nostr-tools rejects with a bare
5
+ * string when a relay connection times out or fails, and passes a remote
6
+ * signer's NIP-46 `error` field through as a string, so `(e as Error).message`
7
+ * reads `undefined` for exactly the failures a user most needs to see.
8
+ *
9
+ * Only a string ever comes back: a rejected object is never serialised, since
10
+ * its fields could carry request data into a log.
11
+ */
12
+ export declare function errorMessage(e: unknown): string;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The text of a thrown or rejected value.
3
+ *
4
+ * Not everything that rejects is an Error. nostr-tools rejects with a bare
5
+ * string when a relay connection times out or fails, and passes a remote
6
+ * signer's NIP-46 `error` field through as a string, so `(e as Error).message`
7
+ * reads `undefined` for exactly the failures a user most needs to see.
8
+ *
9
+ * Only a string ever comes back: a rejected object is never serialised, since
10
+ * its fields could carry request data into a log.
11
+ */
12
+ export function errorMessage(e) {
13
+ if (e instanceof Error)
14
+ return e.message;
15
+ try {
16
+ return String(e);
17
+ }
18
+ catch {
19
+ // An object with no prototype has no toString.
20
+ return 'unknown error';
21
+ }
22
+ }
@@ -17,6 +17,7 @@
17
17
  * this works unchanged under NIP-46 where the key lives in a remote bunker.
18
18
  */
19
19
  import { finalizeEvent, generateSecretKey, getEventHash } from 'nostr-tools/pure';
20
+ import { errorMessage } from '../error-message.js';
20
21
  /** Timestamps are randomised up to two days back, per NIP-59, to frustrate correlation. */
21
22
  const TWO_DAYS = 2 * 24 * 60 * 60;
22
23
  const randomNow = () => Math.round(Date.now() / 1000 - Math.random() * TWO_DAYS);
@@ -83,7 +84,7 @@ export async function handleGiftUnwrap(ctx, args) {
83
84
  seal = JSON.parse(await ctx.nip44Decrypt(wrap.pubkey, wrap.content));
84
85
  }
85
86
  catch (e) {
86
- throw new Error(`Could not decrypt the gift wrap — it may not be addressed to this identity: ${e.message}`);
87
+ throw new Error(`Could not decrypt the gift wrap — it may not be addressed to this identity: ${errorMessage(e)}`);
87
88
  }
88
89
  if (seal?.kind !== 13) {
89
90
  throw new Error(`Expected a kind 13 seal inside the wrap, got kind ${seal?.kind}`);
@@ -94,7 +95,7 @@ export async function handleGiftUnwrap(ctx, args) {
94
95
  rumor = JSON.parse(await ctx.nip44Decrypt(seal.pubkey, seal.content));
95
96
  }
96
97
  catch (e) {
97
- throw new Error(`Could not decrypt the seal: ${e.message}`);
98
+ throw new Error(`Could not decrypt the seal: ${errorMessage(e)}`);
98
99
  }
99
100
  return {
100
101
  rumor,
@@ -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
+ }
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ import { registerAllTools } from './tool-groups.js';
10
10
  import { configureHttpClient } from './http-client.js';
11
11
  import { BRAY_VERSION } from './version.js';
12
12
  import { ReadOnlyContext, createReadOnlyFilter, READ_ONLY_MESSAGE } from './read-only.js';
13
+ import { errorMessage } from './error-message.js';
13
14
  const config = await loadConfig({ allowReadOnly: true });
14
15
  // Route every fetch() in this process through the SOCKS proxy when Tor is
15
16
  // configured, before any HTTP-using code runs. Structural protection
@@ -42,7 +43,7 @@ const nip65 = new Nip65Manager(pool, config.relays);
42
43
  function loadIdentityRelays(npub) {
43
44
  nip65.loadForIdentity(npub)
44
45
  .then(masterRelays => pool.reconfigure(npub, masterRelays))
45
- .catch(e => console.error('NIP-65 relay load failed:', e.message));
46
+ .catch(e => console.error('NIP-65 relay load failed:', errorMessage(e)));
46
47
  }
47
48
  // Establish the bunker connection in the background, with a bounded connect and
48
49
  // exponential backoff. Crucially this does NOT block startup: a slow or offline
@@ -71,13 +72,13 @@ async function establishBunkerInBackground(base) {
71
72
  }
72
73
  }
73
74
  catch (e) {
74
- console.error('Heartwood probe failed (non-fatal):', e.message);
75
+ console.error('Heartwood probe failed (non-fatal):', errorMessage(e));
75
76
  }
76
77
  return;
77
78
  }
78
79
  catch (e) {
79
80
  const delay = Math.min(30_000, 1_000 * 2 ** Math.min(attempt, 5));
80
- console.error(`Bunker connect failed (attempt ${attempt + 1}), retrying in ${delay}ms:`, e.message);
81
+ console.error(`Bunker connect failed (attempt ${attempt + 1}), retrying in ${delay}ms:`, errorMessage(e));
81
82
  await new Promise(resolve => setTimeout(resolve, delay));
82
83
  }
83
84
  }
@@ -108,7 +109,7 @@ else if (config.bunkerUri) {
108
109
  }
109
110
  catch (e) {
110
111
  // No network has happened yet, so exiting cannot flood the signer.
111
- console.error(e.message);
112
+ console.error(errorMessage(e));
112
113
  process.exit(1);
113
114
  }
114
115
  ctx = base;
@@ -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,4 +1,6 @@
1
1
  import { validateRelayUrl } from './handlers.js';
2
+ import { errorMessage } from '../error-message.js';
3
+ import { REQUEST_TIMEOUT_MS } from '../bunker-context.js';
2
4
  /**
3
5
  * Authenticate to a relay that requires NIP-42 AUTH.
4
6
  *
@@ -11,6 +13,12 @@ import { validateRelayUrl } from './handlers.js';
11
13
  * ignores TOR_PROXY, and closes that connection once authenticated, so the
12
14
  * AUTH applies to nothing else. It only shows that the relay accepts the key.
13
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
+ *
14
22
  * Flow:
15
23
  * 1. Connect via WebSocket
16
24
  * 2. Wait for ["AUTH", challenge] message
@@ -18,10 +26,11 @@ import { validateRelayUrl } from './handlers.js';
18
26
  * 4. Send ["AUTH", signedEvent]
19
27
  * 5. Wait for ["OK", eventId, true, ...] confirmation
20
28
  */
21
- export async function handleRelayAuth(ctx, relay, pool) {
29
+ export async function handleRelayAuth(ctx, relay, pool, opts = {}) {
22
30
  if (pool) {
23
31
  validateRelayUrl(relay, { allowPrivate: pool.allowsPrivateRelays?.() === true });
24
- 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 });
25
34
  }
26
35
  validateRelayUrl(relay); // throws on private IPs -- intentionally not caught
27
36
  return new Promise((resolve) => {
@@ -67,7 +76,7 @@ export async function handleRelayAuth(ctx, relay, pool) {
67
76
  settled = true;
68
77
  clearTimeout(timeout);
69
78
  ws.close();
70
- resolve({ authenticated: false, relay, error: `Failed to sign AUTH event: ${err.message}` });
79
+ resolve({ authenticated: false, relay, error: `Failed to sign AUTH event: ${errorMessage(err)}` });
71
80
  }
72
81
  }
73
82
  }
@@ -108,7 +117,7 @@ export async function handleRelayAuth(ctx, relay, pool) {
108
117
  if (!settled) {
109
118
  settled = true;
110
119
  clearTimeout(timeout);
111
- resolve({ authenticated: false, relay, error: `Failed to create WebSocket: ${err.message}` });
120
+ resolve({ authenticated: false, relay, error: `Failed to create WebSocket: ${errorMessage(err)}` });
112
121
  }
113
122
  });
114
123
  });
@@ -1,4 +1,5 @@
1
1
  import { validateRelayUrl } from './handlers.js';
2
+ import { errorMessage } from '../error-message.js';
2
3
  /**
3
4
  * Send a NIP-45 COUNT to each relay, falling back to fetch-and-count (capped at
4
5
  * 1000) when a relay does not support NIP-45.
@@ -43,7 +44,7 @@ async function countThroughPool(pool, relays, filter) {
43
44
  return { relay: answer.url, count: events.length, fallback: true, estimated: events.length >= 1000 };
44
45
  }
45
46
  catch (err) {
46
- return { relay: answer.url, count: 0, error: `COUNT failed (${answer.error}) and the fallback failed: ${err.message}` };
47
+ return { relay: answer.url, count: 0, error: `COUNT failed (${answer.error}) and the fallback failed: ${errorMessage(err)}` };
47
48
  }
48
49
  }));
49
50
  return {
@@ -72,14 +73,14 @@ async function countFromRelay(url, filter, poolQuery) {
72
73
  return {
73
74
  relay: url,
74
75
  count: 0,
75
- error: `COUNT not supported and fallback failed: ${fallbackErr.message}`,
76
+ error: `COUNT not supported and fallback failed: ${errorMessage(fallbackErr)}`,
76
77
  };
77
78
  }
78
79
  }
79
80
  return {
80
81
  relay: url,
81
82
  count: 0,
82
- error: `COUNT not supported: ${err.message}`,
83
+ error: `COUNT not supported: ${errorMessage(err)}`,
83
84
  };
84
85
  }
85
86
  }
@@ -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,7 @@
1
1
  import { validatePublicUrl, validateRelayScheme } from './validation.js';
2
2
  import { brayFetch } from './http-client.js';
3
3
  import { isConnectionFailure, setAutomaticAuth } from './nostr-tools-guards.js';
4
+ import { errorMessage } from './error-message.js';
4
5
  // 512 KiB cap on any inbound relay frame. Protects against malicious relays
5
6
  // pushing 100 MB EVENTs that would exhaust memory (ws library defaults to
6
7
  // 100 MB maxPayload, which is far more than any legitimate Nostr event).
@@ -13,7 +14,6 @@ const WS_MAX_PAYLOAD = 512 * 1024;
13
14
  export function isNormalRequestEnd(reason) {
14
15
  return reason === 'closed automatically on eose' || reason === 'closed by caller';
15
16
  }
16
- const reasonOf = (err) => (err instanceof Error ? err.message : String(err));
17
17
  /** Settle with `p`, or reject with `message` after `ms`. */
18
18
  function within(ms, p, message) {
19
19
  let timer;
@@ -88,6 +88,22 @@ async function createRealPool(torProxy) {
88
88
  destroy: () => pool.destroy(),
89
89
  };
90
90
  }
91
+ /** An AUTH step that did not finish in time. */
92
+ class AuthTimeout extends Error {
93
+ constructor(step, ms) {
94
+ super(step === 'signature'
95
+ ? `AUTH timed out: no signature within ${ms} ms (the signer did not answer; if it is a remote signer, approve the request there)`
96
+ : `AUTH timed out: the relay did not answer the signed AUTH within ${ms} ms`);
97
+ }
98
+ }
99
+ /** The signer refused or failed. nostr-tools drops that error, so it is carried out separately. */
100
+ class AuthNotSigned extends Error {
101
+ constructor(reason) {
102
+ super(`AUTH not signed: ${errorMessage(reason)}`);
103
+ }
104
+ }
105
+ /** nostr-tools' own wait for the relay's OK to a signed AUTH (its `publishTimeout`). */
106
+ const NOSTR_TOOLS_OK_WAIT_MS = 4_400;
91
107
  export class RelayPool {
92
108
  pool;
93
109
  poolReady;
@@ -489,7 +505,7 @@ export class RelayPool {
489
505
  relay = await pool.ensureRelay(url, { connectionTimeout: timeoutMs });
490
506
  }
491
507
  catch (err) {
492
- return { url, error: `connection failure: ${reasonOf(err)}` };
508
+ return { url, error: `connection failure: ${errorMessage(err)}` };
493
509
  }
494
510
  const count = async () => {
495
511
  // countWithHLL resolves with the relay's whole COUNT payload, approximate included.
@@ -500,7 +516,7 @@ export class RelayPool {
500
516
  return await count();
501
517
  }
502
518
  catch (err) {
503
- const reason = reasonOf(err);
519
+ const reason = errorMessage(err);
504
520
  const { onauth } = this.#authParams();
505
521
  if (!reason.startsWith('auth-required: ') || !onauth)
506
522
  return { url, error: this.#annotateAuthError(reason) };
@@ -509,7 +525,7 @@ export class RelayPool {
509
525
  return await count();
510
526
  }
511
527
  catch (authErr) {
512
- return { url, error: this.#annotateAuthError(reasonOf(authErr)) };
528
+ return { url, error: this.#annotateAuthError(errorMessage(authErr)) };
513
529
  }
514
530
  }
515
531
  }
@@ -523,6 +539,13 @@ export class RelayPool {
523
539
  * that carried another identity's traffic is replaced first; after a refusal
524
540
  * the connection is dropped, since nostr-tools keeps its first attempt and a
525
541
  * second try on it would only repeat the refusal.
542
+ *
543
+ * Each step has its own wait, and a timeout names the step. `timeoutMs`
544
+ * (default 5 s) bounds the connection and the challenge. `signTimeoutMs`
545
+ * bounds the signature and defaults to `timeoutMs`: a signer that answers
546
+ * over a relay (NIP-46) needs far longer than a local key, so the caller
547
+ * gives it the remote signer's own limit. The relay's OK is bounded by
548
+ * nostr-tools itself (the connection's publish timeout, 4.4 s by default).
526
549
  */
527
550
  async authenticate(url, opts = {}) {
528
551
  this.#validateDirectRelays([url]);
@@ -532,6 +555,7 @@ export class RelayPool {
532
555
  if (!pool.ensureRelay)
533
556
  return { authenticated: false, relay: url, error: 'the underlying relay pool cannot authenticate' };
534
557
  const timeoutMs = opts.timeoutMs ?? 5_000;
558
+ const signTimeoutMs = opts.signTimeoutMs ?? timeoutMs;
535
559
  const { normalizeURL } = await import('nostr-tools/utils');
536
560
  const current = this.#activePubkey();
537
561
  const owner = this.#connectionOwners.get(normalizeURL(url));
@@ -542,7 +566,7 @@ export class RelayPool {
542
566
  relay = await pool.ensureRelay(url, { connectionTimeout: timeoutMs });
543
567
  }
544
568
  catch (err) {
545
- return { authenticated: false, relay: url, error: `connection failure: ${reasonOf(err)}` };
569
+ return { authenticated: false, relay: url, error: `connection failure: ${errorMessage(err)}` };
546
570
  }
547
571
  // nostr-tools keeps the latest challenge on the relay; it is private in its types.
548
572
  const challenge = () => relay.challenge;
@@ -551,20 +575,58 @@ export class RelayPool {
551
575
  let probed = false;
552
576
  while (!challenge()) {
553
577
  if (Date.now() >= deadline)
554
- return { authenticated: false, relay: url, error: 'AUTH handshake timed out (no challenge received)' };
578
+ return { authenticated: false, relay: url, error: `AUTH handshake timed out (no challenge received within ${timeoutMs} ms)` };
555
579
  if (!probed && Date.now() >= probeAt) {
556
580
  probed = true;
557
581
  const probe = relay.subscribe([{ limit: 0 }], { onevent: () => { }, oneose: () => probe.close(), onclose: () => { } });
558
582
  }
559
583
  await new Promise(resolve => setTimeout(resolve, 25));
560
584
  }
585
+ // relay.auth signs, sends and waits for the relay's OK. nostr-tools 2.24
586
+ // bounds the OK itself, from the moment the signature is in, but it catches
587
+ // an error from the signer, logs it and never settles. So bray bounds the
588
+ // signature, carries a refusal out of the signing wrapper, and labels the
589
+ // outcome by what that wrapper saw.
590
+ let timer;
591
+ let signed = false;
592
+ let settled = false;
593
+ let refuse = () => { };
594
+ const stopped = new Promise((_, reject) => {
595
+ refuse = reject;
596
+ timer = setTimeout(() => reject(new AuthTimeout('signature', signTimeoutMs)), signTimeoutMs);
597
+ });
598
+ const signForRelay = async (evt) => {
599
+ try {
600
+ const event = await this.#signAuth(evt);
601
+ if (!settled) {
602
+ signed = true;
603
+ clearTimeout(timer);
604
+ }
605
+ return event;
606
+ }
607
+ catch (err) {
608
+ if (!settled)
609
+ refuse(new AuthNotSigned(err));
610
+ throw err;
611
+ }
612
+ };
561
613
  try {
562
- await within(timeoutMs, relay.auth(this.#signAuth), 'AUTH timed out');
614
+ await Promise.race([relay.auth(signForRelay), stopped]);
563
615
  return { authenticated: true, relay: url, pubkey: this.#connectionOwners.get(relay.url)?.authedBy ?? current };
564
616
  }
565
617
  catch (err) {
566
618
  pool.forget?.(url);
567
- return { authenticated: false, relay: url, error: `AUTH rejected: ${reasonOf(err)}` };
619
+ if (err instanceof AuthTimeout || err instanceof AuthNotSigned)
620
+ return { authenticated: false, relay: url, error: err.message };
621
+ if (signed && errorMessage(err) === 'auth timed out') {
622
+ const okWait = relay.publishTimeout ?? NOSTR_TOOLS_OK_WAIT_MS;
623
+ return { authenticated: false, relay: url, error: new AuthTimeout('relay OK', okWait).message };
624
+ }
625
+ return { authenticated: false, relay: url, error: `AUTH rejected: ${errorMessage(err)}` };
626
+ }
627
+ finally {
628
+ settled = true;
629
+ clearTimeout(timer);
568
630
  }
569
631
  }
570
632
  /** Reconcile local event IDs with one relay using NIP-77 Negentropy. */
@@ -600,7 +662,7 @@ export class RelayPool {
600
662
  catch (error) {
601
663
  if (opts.signal?.aborted)
602
664
  throw new DOMException('NIP-77 reconciliation was cancelled', 'AbortError');
603
- throw new Nip77UnavailableError(`Could not open NIP-77 relay connection: ${error.message}`);
665
+ throw new Nip77UnavailableError(`Could not open NIP-77 relay connection: ${errorMessage(error)}`);
604
666
  }
605
667
  return new Promise((resolve, reject) => {
606
668
  const localOnlyIds = [];
@@ -674,7 +736,7 @@ export class RelayPool {
674
736
  close();
675
737
  };
676
738
  }
677
- void sync.start().catch((error) => fail(new Nip77UnavailableError(`Could not start NIP-77 reconciliation: ${error.message}`)));
739
+ void sync.start().catch((error) => fail(new Nip77UnavailableError(`Could not start NIP-77 reconciliation: ${errorMessage(error)}`)));
678
740
  });
679
741
  }
680
742
  /** Fetch the relay's NIP-11 `self` identity for verifying relay-generated events. */
package/dist/serve.js CHANGED
@@ -9,6 +9,7 @@ import { createServer } from 'node:http';
9
9
  import { readFileSync } from 'node:fs';
10
10
  import { randomBytes, createHash } from 'node:crypto';
11
11
  import { verifyEvent } from 'nostr-tools/pure';
12
+ import { errorMessage } from './error-message.js';
12
13
  let subCounter = 0;
13
14
  /** Check if an event matches a single filter */
14
15
  function matchFilter(filter, event) {
@@ -183,7 +184,7 @@ async function serveBlossom(req, res, blobs, hostname, log) {
183
184
  json(405, { message: `method ${req.method} not allowed on ${path}` });
184
185
  }
185
186
  catch (e) {
186
- json(400, { message: e.message });
187
+ json(400, { message: errorMessage(e) });
187
188
  }
188
189
  }
189
190
  export function startRelay(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>;
@@ -7,9 +7,9 @@
7
7
  */
8
8
  import { readFileSync, statSync } from 'node:fs';
9
9
  import { matchFilter, verifyEvent } from 'nostr-tools';
10
- import { Nip77UnavailableError } from '../relay-pool.js';
11
10
  import { assertEventSemanticallyValid } from '../event-validation/validator.js';
12
11
  import { nostrEventSchema, validateInputPath } from '../validation.js';
12
+ import { errorMessage } from '../error-message.js';
13
13
  const DEFAULT_MAX_IDS = 1_000;
14
14
  const DEFAULT_MAX_REMOTE_EVENTS = 10_000;
15
15
  const DEFAULT_TIMEOUT_MS = 10_000;
@@ -142,7 +142,7 @@ export async function handleSyncPlan(pool, opts) {
142
142
  throw error;
143
143
  if (preference === 'nip77')
144
144
  throw error;
145
- const reason = error instanceof Nip77UnavailableError ? error.message : error.message;
145
+ const reason = errorMessage(error);
146
146
  warnings.push(`NIP-77 unavailable; used bounded REQ fallback: ${reason}`);
147
147
  }
148
148
  }
@@ -241,7 +241,7 @@ export async function handleSyncPush(pool, opts) {
241
241
  if (error.name === 'AbortError')
242
242
  throw error;
243
243
  failed++;
244
- results.push({ id, success: false, error: error.message });
244
+ results.push({ id, success: false, error: errorMessage(error) });
245
245
  }
246
246
  }
247
247
  return {
@@ -2,6 +2,7 @@ import { finalizeEvent, getPublicKey, verifyEvent, nip44 } from 'nostr-tools';
2
2
  import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js';
3
3
  import { tryDecodeBolt11 } from 'farrier-kit';
4
4
  import { feeReserveMsat } from '../zap/payment-guard.js';
5
+ import { errorMessage } from '../error-message.js';
5
6
  // A NIP-47 wallet service: the server side of Nostr Wallet Connect.
6
7
  //
7
8
  // bray already speaks NWC as a client - `zap-send` spends through a wallet
@@ -263,7 +264,7 @@ export class WalletService {
263
264
  }
264
265
  catch (err) {
265
266
  const next = Math.min(delayMs * 2, MAX_RESUBSCRIBE_DELAY_MS);
266
- this.#opts.log?.(`could not subscribe again for ${grant.name}: ${err.message}; trying again in ${next} ms`);
267
+ this.#opts.log?.(`could not subscribe again for ${grant.name}: ${errorMessage(err)}; trying again in ${next} ms`);
267
268
  this.#retry(grant, session, next);
268
269
  }
269
270
  }
@@ -321,7 +322,7 @@ export class WalletService {
321
322
  const previous = this.#queues.get(grantId) ?? Promise.resolve();
322
323
  this.#queues.set(grantId, previous
323
324
  .then(() => this.#handle(grantId, event))
324
- .catch((err) => this.#opts.log?.(`request failed: ${err.message}`)));
325
+ .catch((err) => this.#opts.log?.(`request failed: ${errorMessage(err)}`)));
325
326
  }
326
327
  async #handle(grantId, event) {
327
328
  const grant = this.#grants.get(grantId);
@@ -389,7 +390,7 @@ export class WalletService {
389
390
  }
390
391
  catch (err) {
391
392
  const code = err instanceof ServiceError ? err.code : 'INTERNAL';
392
- const message = err.message || 'The wallet could not answer that.';
393
+ const message = errorMessage(err) || 'The wallet could not answer that.';
393
394
  answer = { result_type: method, error: { code, message } };
394
395
  this.#opts.log?.(`refused ${method || 'an unnamed method'} on ${grant.name}: ${message}`);
395
396
  }
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.1",
3
+ "version": "3.14.3",
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",