nostr-bray 3.14.1 → 3.14.2

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.
@@ -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
  }
@@ -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;
@@ -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) {
@@ -434,7 +435,7 @@ export async function dispatch(args) {
434
435
  bunkerKeyHex = getOrCreateBunkerKey(persona ?? profileName ?? 'default');
435
436
  }
436
437
  catch (err) {
437
- console.error(`bunker: ${err.message}`);
438
+ console.error(`bunker: ${errorMessage(err)}`);
438
439
  process.exit(1);
439
440
  }
440
441
  }
@@ -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,
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;
@@ -1,4 +1,5 @@
1
1
  import { validateRelayUrl } from './handlers.js';
2
+ import { errorMessage } from '../error-message.js';
2
3
  /**
3
4
  * Authenticate to a relay that requires NIP-42 AUTH.
4
5
  *
@@ -67,7 +68,7 @@ export async function handleRelayAuth(ctx, relay, pool) {
67
68
  settled = true;
68
69
  clearTimeout(timeout);
69
70
  ws.close();
70
- resolve({ authenticated: false, relay, error: `Failed to sign AUTH event: ${err.message}` });
71
+ resolve({ authenticated: false, relay, error: `Failed to sign AUTH event: ${errorMessage(err)}` });
71
72
  }
72
73
  }
73
74
  }
@@ -108,7 +109,7 @@ export async function handleRelayAuth(ctx, relay, pool) {
108
109
  if (!settled) {
109
110
  settled = true;
110
111
  clearTimeout(timeout);
111
- resolve({ authenticated: false, relay, error: `Failed to create WebSocket: ${err.message}` });
112
+ resolve({ authenticated: false, relay, error: `Failed to create WebSocket: ${errorMessage(err)}` });
112
113
  }
113
114
  });
114
115
  });
@@ -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
  }
@@ -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;
@@ -489,7 +489,7 @@ export class RelayPool {
489
489
  relay = await pool.ensureRelay(url, { connectionTimeout: timeoutMs });
490
490
  }
491
491
  catch (err) {
492
- return { url, error: `connection failure: ${reasonOf(err)}` };
492
+ return { url, error: `connection failure: ${errorMessage(err)}` };
493
493
  }
494
494
  const count = async () => {
495
495
  // countWithHLL resolves with the relay's whole COUNT payload, approximate included.
@@ -500,7 +500,7 @@ export class RelayPool {
500
500
  return await count();
501
501
  }
502
502
  catch (err) {
503
- const reason = reasonOf(err);
503
+ const reason = errorMessage(err);
504
504
  const { onauth } = this.#authParams();
505
505
  if (!reason.startsWith('auth-required: ') || !onauth)
506
506
  return { url, error: this.#annotateAuthError(reason) };
@@ -509,7 +509,7 @@ export class RelayPool {
509
509
  return await count();
510
510
  }
511
511
  catch (authErr) {
512
- return { url, error: this.#annotateAuthError(reasonOf(authErr)) };
512
+ return { url, error: this.#annotateAuthError(errorMessage(authErr)) };
513
513
  }
514
514
  }
515
515
  }
@@ -542,7 +542,7 @@ export class RelayPool {
542
542
  relay = await pool.ensureRelay(url, { connectionTimeout: timeoutMs });
543
543
  }
544
544
  catch (err) {
545
- return { authenticated: false, relay: url, error: `connection failure: ${reasonOf(err)}` };
545
+ return { authenticated: false, relay: url, error: `connection failure: ${errorMessage(err)}` };
546
546
  }
547
547
  // nostr-tools keeps the latest challenge on the relay; it is private in its types.
548
548
  const challenge = () => relay.challenge;
@@ -564,7 +564,7 @@ export class RelayPool {
564
564
  }
565
565
  catch (err) {
566
566
  pool.forget?.(url);
567
- return { authenticated: false, relay: url, error: `AUTH rejected: ${reasonOf(err)}` };
567
+ return { authenticated: false, relay: url, error: `AUTH rejected: ${errorMessage(err)}` };
568
568
  }
569
569
  }
570
570
  /** Reconcile local event IDs with one relay using NIP-77 Negentropy. */
@@ -600,7 +600,7 @@ export class RelayPool {
600
600
  catch (error) {
601
601
  if (opts.signal?.aborted)
602
602
  throw new DOMException('NIP-77 reconciliation was cancelled', 'AbortError');
603
- throw new Nip77UnavailableError(`Could not open NIP-77 relay connection: ${error.message}`);
603
+ throw new Nip77UnavailableError(`Could not open NIP-77 relay connection: ${errorMessage(error)}`);
604
604
  }
605
605
  return new Promise((resolve, reject) => {
606
606
  const localOnlyIds = [];
@@ -674,7 +674,7 @@ export class RelayPool {
674
674
  close();
675
675
  };
676
676
  }
677
- void sync.start().catch((error) => fail(new Nip77UnavailableError(`Could not start NIP-77 reconciliation: ${error.message}`)));
677
+ void sync.start().catch((error) => fail(new Nip77UnavailableError(`Could not start NIP-77 reconciliation: ${errorMessage(error)}`)));
678
678
  });
679
679
  }
680
680
  /** 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 = {}) {
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nostr-bray",
3
- "version": "3.14.1",
3
+ "version": "3.14.2",
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",