nostr-bray 3.14.0 → 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.
- package/dist/bunker-context.js +2 -1
- package/dist/bunker-pair.js +3 -5
- package/dist/cli/commands/bunker.d.ts +0 -6
- package/dist/cli/commands/bunker.js +5 -4
- package/dist/error-message.d.ts +12 -0
- package/dist/error-message.js +22 -0
- package/dist/event/gift-wrap.js +3 -2
- package/dist/index.js +5 -4
- package/dist/relay/auth.js +3 -2
- package/dist/relay/count.js +4 -3
- package/dist/relay-pool.js +8 -8
- package/dist/serve.js +2 -1
- package/dist/sync/handlers.js +3 -3
- package/dist/wallet-service/service.d.ts +19 -1
- package/dist/wallet-service/service.js +69 -5
- package/dist/wallet-service/tools.js +4 -1
- package/package.json +1 -1
package/dist/bunker-context.js
CHANGED
|
@@ -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
|
|
180
|
+
throw new Error(`${errorMessage(e)}. If the signer app no longer lists bray, ${PAIRED_REPAIR_HINT}`);
|
|
180
181
|
}
|
|
181
182
|
return;
|
|
182
183
|
}
|
package/dist/bunker-pair.js
CHANGED
|
@@ -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],
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
+
}
|
package/dist/event/gift-wrap.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
112
|
+
console.error(errorMessage(e));
|
|
112
113
|
process.exit(1);
|
|
113
114
|
}
|
|
114
115
|
ctx = base;
|
package/dist/relay/auth.js
CHANGED
|
@@ -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
|
|
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
|
|
112
|
+
resolve({ authenticated: false, relay, error: `Failed to create WebSocket: ${errorMessage(err)}` });
|
|
112
113
|
}
|
|
113
114
|
});
|
|
114
115
|
});
|
package/dist/relay/count.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
83
|
+
error: `COUNT not supported: ${errorMessage(err)}`,
|
|
83
84
|
};
|
|
84
85
|
}
|
|
85
86
|
}
|
package/dist/relay-pool.js
CHANGED
|
@@ -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: ${
|
|
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 =
|
|
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(
|
|
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: ${
|
|
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: ${
|
|
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
|
|
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
|
|
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
|
|
187
|
+
json(400, { message: errorMessage(e) });
|
|
187
188
|
}
|
|
188
189
|
}
|
|
189
190
|
export function startRelay(opts = {}) {
|
package/dist/sync/handlers.js
CHANGED
|
@@ -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
|
|
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
|
|
244
|
+
results.push({ id, success: false, error: errorMessage(error) });
|
|
245
245
|
}
|
|
246
246
|
}
|
|
247
247
|
return {
|
|
@@ -44,7 +44,15 @@ export interface ServiceWallet {
|
|
|
44
44
|
}): Promise<ServiceInvoice | null>;
|
|
45
45
|
}
|
|
46
46
|
export interface ServiceTransport {
|
|
47
|
-
|
|
47
|
+
/**
|
|
48
|
+
* `onclose`, if the transport supports it, is called when the relays end the
|
|
49
|
+
* subscription themselves, with each relay's reason; the service then
|
|
50
|
+
* subscribes again. A transport without it cannot report that.
|
|
51
|
+
*/
|
|
52
|
+
subscribe(relays: string[], filter: Filter, onEvent: (event: NostrEvent) => void, onclose?: (reasons: Array<{
|
|
53
|
+
url: string;
|
|
54
|
+
reason: string;
|
|
55
|
+
}>) => void): Promise<() => void>;
|
|
48
56
|
publish(relays: string[], event: NostrEvent): Promise<void>;
|
|
49
57
|
}
|
|
50
58
|
export interface Grant {
|
|
@@ -93,6 +101,16 @@ export interface ServiceOptions {
|
|
|
93
101
|
persist?: () => Promise<void>;
|
|
94
102
|
log?: (message: string) => void;
|
|
95
103
|
now?: () => number;
|
|
104
|
+
/**
|
|
105
|
+
* Milliseconds before subscribing again once the relays end a subscription
|
|
106
|
+
* (default 5000), doubling up to a minute while they refuse a new one.
|
|
107
|
+
*/
|
|
108
|
+
resubscribeDelayMs?: number;
|
|
109
|
+
/**
|
|
110
|
+
* Asked before subscribing again: false stops the grant instead, for when
|
|
111
|
+
* the service should no longer answer (the active identity changed).
|
|
112
|
+
*/
|
|
113
|
+
shouldServe?: () => boolean;
|
|
96
114
|
}
|
|
97
115
|
export declare class WalletService {
|
|
98
116
|
#private;
|
|
@@ -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
|
|
@@ -168,6 +169,7 @@ function invoiceResult(view) {
|
|
|
168
169
|
...(view.feesPaidMsat === undefined ? {} : { fees_paid: view.feesPaidMsat }),
|
|
169
170
|
};
|
|
170
171
|
}
|
|
172
|
+
const MAX_RESUBSCRIBE_DELAY_MS = 60_000;
|
|
171
173
|
// The fields another process may change while this one serves.
|
|
172
174
|
function adopt(target, source) {
|
|
173
175
|
target.methods = source.methods;
|
|
@@ -193,6 +195,10 @@ export class WalletService {
|
|
|
193
195
|
#stops = new Map();
|
|
194
196
|
#queues = new Map();
|
|
195
197
|
#grants = new Map();
|
|
198
|
+
// One per grant while it is served: a subscription ending belongs to the
|
|
199
|
+
// session it was opened in, so a late close from an old one is ignored.
|
|
200
|
+
#sessions = new Map();
|
|
201
|
+
#retries = new Map();
|
|
196
202
|
constructor(opts) {
|
|
197
203
|
this.#opts = opts;
|
|
198
204
|
this.#now = opts.now ?? (() => Date.now());
|
|
@@ -205,19 +211,77 @@ export class WalletService {
|
|
|
205
211
|
return;
|
|
206
212
|
this.stop(grant.id);
|
|
207
213
|
this.#grants.set(grant.id, grant);
|
|
214
|
+
const session = {};
|
|
215
|
+
this.#sessions.set(grant.id, session);
|
|
208
216
|
await this.#opts.transport.publish(grant.relays, infoEvent(grant));
|
|
217
|
+
await this.#listen(grant, session);
|
|
218
|
+
this.#opts.log?.(`serving ${grant.name} on ${grant.relays.join(', ')}`);
|
|
219
|
+
}
|
|
220
|
+
// Subscribe for the grant's requests. It starts MAX_REQUEST_AGE_SECS back,
|
|
221
|
+
// here as on a resubscription; a request seen before is in grant.seen, and
|
|
222
|
+
// a spending one is written there before it runs, so it is not paid twice.
|
|
223
|
+
async #listen(grant, session) {
|
|
209
224
|
const since = Math.floor(this.#now() / 1000) - MAX_REQUEST_AGE_SECS;
|
|
210
|
-
|
|
225
|
+
let ended = false;
|
|
226
|
+
const stop = await this.#opts.transport.subscribe(grant.relays, { kinds: [NWC_REQUEST_KIND], '#p': [grant.servicePubkey], since }, (event) => this.#enqueue(grant.id, event), (reasons) => {
|
|
227
|
+
if (ended)
|
|
228
|
+
return;
|
|
229
|
+
ended = true;
|
|
230
|
+
this.#ended(grant, session, reasons);
|
|
231
|
+
});
|
|
232
|
+
if (this.#sessions.get(grant.id) !== session) {
|
|
233
|
+
stop();
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
211
236
|
this.#stops.set(grant.id, stop);
|
|
212
|
-
|
|
237
|
+
}
|
|
238
|
+
// The relays ended the subscription (not this service: stop() ends the
|
|
239
|
+
// session first). Subscribe again rather than go quiet while serving.
|
|
240
|
+
#ended(grant, session, reasons) {
|
|
241
|
+
if (this.#sessions.get(grant.id) !== session)
|
|
242
|
+
return;
|
|
243
|
+
this.#stops.delete(grant.id);
|
|
244
|
+
const why = reasons.map(({ url, reason }) => `${url}: ${reason}`).join('; ') || 'no reason given';
|
|
245
|
+
this.#opts.log?.(`subscription for ${grant.name} ended (${why})`);
|
|
246
|
+
this.#retry(grant, session, this.#opts.resubscribeDelayMs ?? 5_000);
|
|
247
|
+
}
|
|
248
|
+
#retry(grant, session, delayMs) {
|
|
249
|
+
const timer = setTimeout(() => { void this.#resubscribe(grant, session, delayMs); }, delayMs);
|
|
250
|
+
this.#retries.set(grant.id, timer);
|
|
251
|
+
}
|
|
252
|
+
async #resubscribe(grant, session, delayMs) {
|
|
253
|
+
this.#retries.delete(grant.id);
|
|
254
|
+
if (this.#sessions.get(grant.id) !== session)
|
|
255
|
+
return;
|
|
256
|
+
if (this.#opts.shouldServe && !this.#opts.shouldServe()) {
|
|
257
|
+
this.stop(grant.id);
|
|
258
|
+
this.#opts.log?.(`stopped serving ${grant.name}: it should no longer be served here (the identity changed)`);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
await this.#listen(grant, session);
|
|
263
|
+
this.#opts.log?.(`serving ${grant.name} again`);
|
|
264
|
+
}
|
|
265
|
+
catch (err) {
|
|
266
|
+
const next = Math.min(delayMs * 2, MAX_RESUBSCRIBE_DELAY_MS);
|
|
267
|
+
this.#opts.log?.(`could not subscribe again for ${grant.name}: ${errorMessage(err)}; trying again in ${next} ms`);
|
|
268
|
+
this.#retry(grant, session, next);
|
|
269
|
+
}
|
|
213
270
|
}
|
|
214
271
|
stop(grantId) {
|
|
272
|
+
// End the session first, so the subscription closing below is not taken
|
|
273
|
+
// for the relays ending it.
|
|
274
|
+
this.#sessions.delete(grantId);
|
|
275
|
+
const retry = this.#retries.get(grantId);
|
|
276
|
+
if (retry)
|
|
277
|
+
clearTimeout(retry);
|
|
278
|
+
this.#retries.delete(grantId);
|
|
215
279
|
this.#stops.get(grantId)?.();
|
|
216
280
|
this.#stops.delete(grantId);
|
|
217
281
|
this.#grants.delete(grantId);
|
|
218
282
|
}
|
|
219
283
|
close() {
|
|
220
|
-
for (const id of [...this.#stops.keys()])
|
|
284
|
+
for (const id of new Set([...this.#stops.keys(), ...this.#sessions.keys()]))
|
|
221
285
|
this.stop(id);
|
|
222
286
|
}
|
|
223
287
|
// The grant as the store has it now. False when it is gone or revoked.
|
|
@@ -258,7 +322,7 @@ export class WalletService {
|
|
|
258
322
|
const previous = this.#queues.get(grantId) ?? Promise.resolve();
|
|
259
323
|
this.#queues.set(grantId, previous
|
|
260
324
|
.then(() => this.#handle(grantId, event))
|
|
261
|
-
.catch((err) => this.#opts.log?.(`request failed: ${err
|
|
325
|
+
.catch((err) => this.#opts.log?.(`request failed: ${errorMessage(err)}`)));
|
|
262
326
|
}
|
|
263
327
|
async #handle(grantId, event) {
|
|
264
328
|
const grant = this.#grants.get(grantId);
|
|
@@ -326,7 +390,7 @@ export class WalletService {
|
|
|
326
390
|
}
|
|
327
391
|
catch (err) {
|
|
328
392
|
const code = err instanceof ServiceError ? err.code : 'INTERNAL';
|
|
329
|
-
const message = err
|
|
393
|
+
const message = errorMessage(err) || 'The wallet could not answer that.';
|
|
330
394
|
answer = { result_type: method, error: { code, message } };
|
|
331
395
|
this.#opts.log?.(`refused ${method || 'an unnamed method'} on ${grant.name}: ${message}`);
|
|
332
396
|
}
|
|
@@ -75,12 +75,15 @@ export function registerWalletServiceTools(server, deps, options = {}) {
|
|
|
75
75
|
service = new WalletService({
|
|
76
76
|
wallet: upstreamWallet({ uri, alias: deps.ctx.activeNpub, guard: defaultPaymentGuard() }),
|
|
77
77
|
transport: {
|
|
78
|
-
|
|
78
|
+
// With onclose the service subscribes again when a relay ends it.
|
|
79
|
+
subscribe: (relays, filter, onEvent, onclose) => deps.pool.subscribe(relays, filter, onEvent, { onclose }),
|
|
79
80
|
publish: async (relays, event) => {
|
|
80
81
|
await deps.pool.publishDirect(relays, event);
|
|
81
82
|
},
|
|
82
83
|
},
|
|
83
84
|
store: fileGrantStore(grantsFile, pubkey),
|
|
85
|
+
// An identity switch is a different wallet: do not subscribe again for it.
|
|
86
|
+
shouldServe: () => identity() === servingFor,
|
|
84
87
|
});
|
|
85
88
|
return service;
|
|
86
89
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nostr-bray",
|
|
3
|
-
"version": "3.14.
|
|
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",
|