nostr-bray 3.14.3 → 3.15.0

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/README.md CHANGED
@@ -428,6 +428,11 @@ npx nostr-bray prove blind # create a linkage proof
428
428
  npx nostr-bray --help # see all commands
429
429
  ```
430
430
 
431
+ An unreleased preview adds owner-only `key-wrap`, `key-check` and `key-load`
432
+ for encrypted backups of existing unrelated accounts. Recovery needs the
433
+ same master **and** the saved file. See the [preview guide](docs/wrapped-account-preview.md)
434
+ for dependency gates, explicit activation and the SDK operations.
435
+
431
436
  ## Use as a library
432
437
 
433
438
  The package is also a TypeScript SDK (ESM only). `nostr-bray/sdk` is the factory API:
@@ -17,7 +17,7 @@ import { SimplePool } from 'nostr-tools/pool';
17
17
  import { generateSecretKey, finalizeEvent } from 'nostr-tools/pure';
18
18
  import { npubEncode } from 'nostr-tools/nip19';
19
19
  import { webSocketFor } from './ws-safe.js';
20
- import { setAutomaticAuth } from './nostr-tools-guards.js';
20
+ import { guardRelaySends, setAutomaticAuth } from './nostr-tools-guards.js';
21
21
  import { readStateFile, writeStateFile } from './state.js';
22
22
  import { errorMessage } from './error-message.js';
23
23
  /** Bound the NIP-46 connect handshake. nostr-tools' BunkerSigner has no
@@ -141,6 +141,7 @@ export class BunkerContext {
141
141
  // relays that only let a key read messages addressed to it still work.
142
142
  // Its own WebSocket class, so TOR_PROXY applies to signer traffic too.
143
143
  const pool = new SimplePool({ websocketImplementation: webSocketFor(options.torProxy) });
144
+ guardRelaySends(pool);
144
145
  const answerChallenge = async (template) => finalizeEvent(template, clientSk);
145
146
  setAutomaticAuth(pool, () => answerChallenge);
146
147
  const signer = BunkerSigner.fromBunker(clientSk, {
@@ -24,7 +24,7 @@ import { CLIENT_NAME, CLIENT_KEYS_FILE, REQUEST_TIMEOUT_MS, TimeoutError, withTi
24
24
  import { readStateFile, writeStateFile } from './state.js';
25
25
  import { isOnionUrl, validateRelayScheme } from './validation.js';
26
26
  import { webSocketFor } from './ws-safe.js';
27
- import { setAutomaticAuth } from './nostr-tools-guards.js';
27
+ import { guardRelaySends, setAutomaticAuth } from './nostr-tools-guards.js';
28
28
  import { errorMessage } from './error-message.js';
29
29
  /** Saved by `bunker connect` and `bunker pair`; read by loadConfig. */
30
30
  export const BUNKER_URI_FILE = 'bunker-uri';
@@ -73,6 +73,7 @@ export async function pairWithNostrConnect(options) {
73
73
  // Answer NIP-42 challenges with the client key, as BunkerContext does.
74
74
  // With TOR_PROXY set, pairing goes through the proxy like bray's other relay traffic.
75
75
  const pool = new SimplePool({ websocketImplementation: webSocketFor(options.torProxy) });
76
+ guardRelaySends(pool);
76
77
  const answerChallenge = async (template) => finalizeEvent(template, clientSk);
77
78
  setAutomaticAuth(pool, () => answerChallenge);
78
79
  const timeoutMs = options.timeoutMs ?? PAIR_TIMEOUT_MS;
package/dist/bunker.js CHANGED
@@ -15,7 +15,7 @@ import { finalizeEvent, getPublicKey, generateSecretKey } from 'nostr-tools/pure
15
15
  import { npubEncode } from 'nostr-tools/nip19';
16
16
  import { SimplePool } from 'nostr-tools/pool';
17
17
  import { webSocketFor } from './ws-safe.js';
18
- import { isConnectionFailure, setAutomaticAuth } from './nostr-tools-guards.js';
18
+ import { guardRelaySends, isConnectionFailure, setAutomaticAuth } from './nostr-tools-guards.js';
19
19
  import { readStateFile, readStateFileStrict, writeStateFile } from './state.js';
20
20
  const MAX_RESUBSCRIBE_DELAY_MS = 60_000;
21
21
  // A subscription that lasted this long was healthy: the next drop starts the
@@ -124,6 +124,7 @@ export function startBunker(opts) {
124
124
  // Sign in (NIP-42) with the bunker key when a relay asks, so a private
125
125
  // relay lets the bunker read requests addressed to it.
126
126
  const pool = new SimplePool({ websocketImplementation: webSocketFor(opts.torProxy) });
127
+ guardRelaySends(pool);
127
128
  const answerChallenge = async (template) => finalizeEvent(template, bunkerSk);
128
129
  setAutomaticAuth(pool, () => answerChallenge);
129
130
  // Subscribe to kind 24133 events addressed to us, one subscription per relay
@@ -1,8 +1,27 @@
1
1
  import { handleIdentityList, handleIdentityProve, handleIdentityCreate, handleBackupShamir, handleRestoreShamir, handleIdentityBackup, handleIdentityRestore, handleIdentityMigrate, handleTrustProofPublish, } from '../../exports.js';
2
2
  import * as fmt from '../../format.js';
3
+ import { IdentityContext } from '../../context.js';
4
+ import { wrapKeyFile, checkWrappedKeyFile, loadWrappedKeyFile } from '../../identity/wrapped-files.js';
3
5
  export async function dispatch(cmd, cmdArgs, h, ctx, pool) {
4
6
  const { req, flag, hasFlag, out } = h;
5
7
  switch (cmd) {
8
+ case 'key-wrap':
9
+ case 'key-check':
10
+ case 'key-load': {
11
+ if (!(ctx instanceof IdentityContext))
12
+ throw new Error('Encrypted key files require a local owner context; hardware/remote export is unavailable');
13
+ const file = req(1, `${cmd} <file> <${cmd === 'key-wrap' ? 'output-file' : 'expected-npub'}>`);
14
+ const target = req(2, `${cmd} <file> <${cmd === 'key-wrap' ? 'output-file' : 'expected-npub'}>`);
15
+ if (cmd === 'key-wrap')
16
+ out(await wrapKeyFile(ctx, file, target));
17
+ else if (cmd === 'key-check')
18
+ out(await checkWrappedKeyFile(ctx, file, target));
19
+ else {
20
+ out(await loadWrappedKeyFile(ctx, file, target));
21
+ console.error('Loaded into this process only; in shell mode, switch to its npub explicitly before signing.');
22
+ }
23
+ break;
24
+ }
6
25
  case 'whoami':
7
26
  console.log(ctx.activeNpub);
8
27
  break;
@@ -41,6 +41,7 @@ export const COMPOUND_COMMANDS = new Set([
41
41
  ]);
42
42
  // Commands that work purely offline — no relay connection needed
43
43
  export const OFFLINE_COMMANDS = new Set([
44
+ 'key-wrap', 'key-check', 'key-load',
44
45
  'whoami', 'create', 'list', 'derive', 'persona', 'switch', 'prove',
45
46
  'backup', 'restore', 'spoken-challenge', 'spoken-verify', 'trust-verify',
46
47
  'ring-verify', 'zap-decode', 'safety-configure', 'safety-activate',
package/dist/cli/index.js CHANGED
@@ -73,6 +73,9 @@ const HELP = `nostr-bray — Sovereign Nostr identities for AI agents
73
73
  Usage: nostr-bray [command] [args]
74
74
 
75
75
  Identity:
76
+ key-wrap <key-file> <backup-file> Encrypt an existing raw key (preview)
77
+ key-check <backup-file> <npub> Verify an exact encrypted account backup
78
+ key-load <backup-file> <npub> Load into this process; switch npub separately
76
79
  whoami Show active identity npub
77
80
  create Generate a fresh identity (mnemonic + npub)
78
81
  list List all identities
@@ -406,6 +409,7 @@ const envDefault = process.env.NOSTR_BRAY_OUTPUT === 'json' ? 'json' : 'human';
406
409
  // Category sets for routing
407
410
  const IDENTITY_CMDS = new Set([
408
411
  'whoami', 'create', 'list', 'derive', 'persona', 'switch', 'prove', 'proof-publish',
412
+ 'key-wrap', 'key-check', 'key-load',
409
413
  'backup', 'restore', 'identity-backup', 'identity-restore', 'migrate',
410
414
  ]);
411
415
  const SOCIAL_CMDS = new Set([
@@ -479,6 +483,7 @@ async function run(cmdArgs) {
479
483
  // === Shell mode ===
480
484
  const ALL_COMMANDS = [
481
485
  'whoami', 'create', 'list', 'derive', 'persona', 'switch', 'prove', 'proof-publish',
486
+ 'key-wrap', 'key-check', 'key-load',
482
487
  'backup', 'restore', 'identity-backup', 'identity-restore', 'migrate',
483
488
  'post', 'reply', 'react', 'delete', 'repost', 'profile', 'profile-set', 'contacts', 'follow', 'unfollow', 'dm', 'dm-read', 'feed', 'notifications', 'nip-publish', 'nip-read',
484
489
  'attest', 'claim', 'trust-read', 'trust-verify', 'trust-revoke', 'trust-request', 'trust-request-list', 'trust-rank',
package/dist/context.d.ts CHANGED
@@ -24,6 +24,7 @@ export declare class IdentityContext implements ExtendedSigningContext {
24
24
  private activeEntry;
25
25
  private maxCacheSize;
26
26
  private forbidden;
27
+ private destroyed;
27
28
  constructor(secretKey: string, format: 'nsec' | 'hex' | 'mnemonic', opts?: ContextOptions);
28
29
  /**
29
30
  * Make an identity the active one, refusing a forbidden key.
@@ -38,6 +39,15 @@ export declare class IdentityContext implements ExtendedSigningContext {
38
39
  * Only the npub is in the message; it is public, and nothing else is.
39
40
  */
40
41
  private activate;
42
+ private assertAllowed;
43
+ /** Recover an encrypted raw key into local memory. Does not activate it or grant MCP authority. */
44
+ importWrappedIdentity(record: string, expectedNpub: string): Promise<PublicIdentity>;
45
+ /** Owner SDK operation: wrap a raw key without loading or activating it. */
46
+ wrapRawIdentity(privateKey: Uint8Array): Promise<string>;
47
+ /** Owner file read-back: authenticate an exact account without retaining or activating it. */
48
+ checkWrappedIdentity(record: string, expectedNpub?: string): Promise<PublicIdentity>;
49
+ /** Rewrap a loaded imported key. Derived identities retain their existing recovery path. */
50
+ wrapImportedIdentity(npub: string): Promise<string>;
41
51
  /** Current active identity's npub (bech32) */
42
52
  get activeNpub(): string;
43
53
  /** Derivation path of the current active identity, for reporting to a human */
package/dist/context.js CHANGED
@@ -1,5 +1,6 @@
1
- import { fromNsec, fromMnemonic, derive, zeroise } from 'nsec-tree';
1
+ import { fromNsec, fromMnemonic, derive } from 'nsec-tree';
2
2
  import { createBlindProof, createFullProof } from 'nsec-tree/proof';
3
+ import { wrapNsec, unwrapNsec } from 'nsec-tree/wrapped';
3
4
  import { finalizeEvent, getPublicKey } from 'nostr-tools/pure';
4
5
  import { decode, npubEncode, nsecEncode } from 'nostr-tools/nip19';
5
6
  import { decode as decodeNip19 } from 'nostr-tools/nip19';
@@ -50,6 +51,7 @@ export class IdentityContext {
50
51
  activeEntry;
51
52
  maxCacheSize;
52
53
  forbidden;
54
+ destroyed = false;
53
55
  constructor(secretKey, format, opts) {
54
56
  this.maxCacheSize = opts?.maxCache ?? 5;
55
57
  // Built before anything is activated, so the constructor's own
@@ -96,14 +98,71 @@ export class IdentityContext {
96
98
  * Only the npub is in the message; it is public, and nothing else is.
97
99
  */
98
100
  activate(entry) {
99
- const hex = Buffer.from(entry.identity.publicKey).toString('hex');
101
+ this.assertAllowed(entry.identity);
102
+ this.activeEntry = entry;
103
+ }
104
+ assertAllowed(identity) {
105
+ const hex = Buffer.from(identity.publicKey).toString('hex');
100
106
  if (this.forbidden.has(hex)) {
101
- throw new Error(`Refusing to activate ${entry.identity.npub}: it is on this process's forbidden list. ` +
107
+ throw new Error(`Refusing to activate ${identity.npub}: it is on this process's forbidden list. ` +
102
108
  'That list is for principals - a person\'s key, never an agent\'s. An agent signing as its ' +
103
109
  'principal can attest that it belongs to itself and approve its own requests, because it is ' +
104
110
  'the principal those checks look for. Point NOSTR_SECRET_KEY at the agent\'s own key.');
105
111
  }
106
- this.activeEntry = entry;
112
+ }
113
+ /** Recover an encrypted raw key into local memory. Does not activate it or grant MCP authority. */
114
+ async importWrappedIdentity(record, expectedNpub) {
115
+ if (this.destroyed)
116
+ throw new Error('IdentityContext has been destroyed');
117
+ const imported = await unwrapNsec(this.root, record, expectedNpub);
118
+ let retained = false;
119
+ try {
120
+ if (this.destroyed)
121
+ throw new Error('IdentityContext has been destroyed');
122
+ this.assertAllowed(imported);
123
+ const existing = this.cache.get(imported.npub);
124
+ if (imported.npub === this.masterEntry.identity.npub || (existing && !existing.imported)) {
125
+ throw new Error('Identity is already loaded with different provenance');
126
+ }
127
+ if (!existing) {
128
+ this.putCache(imported.npub, { identity: imported, imported: true, purpose: '', index: 0, lastUsed: Date.now() });
129
+ retained = true;
130
+ }
131
+ return { npub: imported.npub, origin: 'imported', recovery: 'master-and-record' };
132
+ }
133
+ finally {
134
+ if (!retained)
135
+ imported.privateKey.fill(0);
136
+ }
137
+ }
138
+ /** Owner SDK operation: wrap a raw key without loading or activating it. */
139
+ async wrapRawIdentity(privateKey) {
140
+ if (this.destroyed)
141
+ throw new Error('IdentityContext has been destroyed');
142
+ return wrapNsec(this.root, privateKey);
143
+ }
144
+ /** Owner file read-back: authenticate an exact account without retaining or activating it. */
145
+ async checkWrappedIdentity(record, expectedNpub) {
146
+ if (this.destroyed)
147
+ throw new Error('IdentityContext has been destroyed');
148
+ const imported = await unwrapNsec(this.root, record, expectedNpub);
149
+ try {
150
+ if (this.destroyed)
151
+ throw new Error('IdentityContext has been destroyed');
152
+ return { npub: imported.npub, origin: 'imported', recovery: 'master-and-record' };
153
+ }
154
+ finally {
155
+ imported.privateKey.fill(0);
156
+ }
157
+ }
158
+ /** Rewrap a loaded imported key. Derived identities retain their existing recovery path. */
159
+ async wrapImportedIdentity(npub) {
160
+ if (this.destroyed)
161
+ throw new Error('IdentityContext has been destroyed');
162
+ const entry = this.cache.get(npub);
163
+ if (!entry?.imported)
164
+ throw new Error('Imported identity is not loaded');
165
+ return wrapNsec(this.root, entry.identity.privateKey);
107
166
  }
108
167
  /** Current active identity's npub (bech32) */
109
168
  get activeNpub() {
@@ -121,7 +180,7 @@ export class IdentityContext {
121
180
  async derive(purpose, index) {
122
181
  // Return from cache if already derived
123
182
  for (const [npub, entry] of this.cache) {
124
- if (entry.purpose === purpose && entry.index === index && !entry.personaName) {
183
+ if (!entry.imported && entry.purpose === purpose && entry.index === index && !entry.personaName) {
125
184
  entry.lastUsed = Date.now();
126
185
  return { npub, purpose, index };
127
186
  }
@@ -142,7 +201,7 @@ export class IdentityContext {
142
201
  * key you'd get anywhere else in the ecosystem. */
143
202
  async use(purpose, index = 0) {
144
203
  for (const [, entry] of this.cache) {
145
- if (entry.purpose === purpose && entry.index === index && !entry.personaName) {
204
+ if (!entry.imported && entry.purpose === purpose && entry.index === index && !entry.personaName) {
146
205
  entry.lastUsed = Date.now();
147
206
  this.activate(entry);
148
207
  return;
@@ -157,7 +216,7 @@ export class IdentityContext {
157
216
  async derivePersona(name, index) {
158
217
  // Return from cache if already derived
159
218
  for (const [npub, entry] of this.cache) {
160
- if (entry.personaName === name && entry.index === index) {
219
+ if (!entry.imported && entry.personaName === name && entry.index === index) {
161
220
  entry.lastUsed = Date.now();
162
221
  return { npub, purpose: entry.purpose, index: entry.index, personaName: name };
163
222
  }
@@ -176,13 +235,23 @@ export class IdentityContext {
176
235
  }
177
236
  /** Switch active identity by purpose+index, persona name, or "master" */
178
237
  async switch(purposeOrName, index) {
238
+ if (purposeOrName.startsWith('npub1')) {
239
+ const entry = this.cache.get(purposeOrName);
240
+ if (!entry)
241
+ throw new Error('Identity is not loaded; restore its encrypted record first');
242
+ this.activate(entry);
243
+ entry.lastUsed = Date.now();
244
+ return;
245
+ }
179
246
  if (purposeOrName === 'master') {
180
247
  this.activate(this.masterEntry);
181
248
  this.masterEntry.lastUsed = Date.now();
182
249
  return;
183
250
  }
184
- // Check cache for matching purpose or persona name
251
+ // Imported keys can only be selected explicitly by npub.
185
252
  for (const [, entry] of this.cache) {
253
+ if (entry.imported)
254
+ continue;
186
255
  const matchesPurpose = entry.purpose === purposeOrName && (index === undefined || entry.index === index);
187
256
  const matchesPersona = entry.personaName === purposeOrName && (index === undefined || entry.index === index);
188
257
  if (matchesPurpose || matchesPersona) {
@@ -240,6 +309,10 @@ export class IdentityContext {
240
309
  { npub: this.masterEntry.identity.npub, purpose: 'master', index: 0 },
241
310
  ];
242
311
  for (const [, entry] of this.cache) {
312
+ if (entry.imported) {
313
+ result.push({ npub: entry.identity.npub, origin: 'imported', recovery: 'master-and-record' });
314
+ continue;
315
+ }
243
316
  result.push({
244
317
  npub: entry.identity.npub,
245
318
  purpose: entry.purpose,
@@ -255,6 +328,8 @@ export class IdentityContext {
255
328
  if (this.activeEntry === this.masterEntry) {
256
329
  throw new Error('Cannot prove master identity — it is the raw key, not a derived child. Switch to a derived identity first.');
257
330
  }
331
+ if (this.activeEntry.imported)
332
+ throw new Error('Cannot prove an imported identity as a derived child');
258
333
  const child = this.activeEntry.identity;
259
334
  if (mode === 'full') {
260
335
  return createFullProof(this.root, child);
@@ -299,9 +374,10 @@ export class IdentityContext {
299
374
  }
300
375
  /** Destroy all identities and the tree root */
301
376
  destroy() {
302
- zeroise(this.masterEntry.identity);
377
+ this.destroyed = true;
378
+ this.masterEntry.identity.privateKey.fill(0);
303
379
  for (const [, entry] of this.cache) {
304
- zeroise(entry.identity);
380
+ entry.identity.privateKey.fill(0);
305
381
  }
306
382
  this.cache.clear();
307
383
  this.root.destroy();
@@ -309,6 +385,10 @@ export class IdentityContext {
309
385
  /** Insert into LRU cache, evicting oldest if at capacity */
310
386
  putCache(npub, entry) {
311
387
  if (this.cache.has(npub)) {
388
+ if (this.cache.get(npub).imported && !entry.imported) {
389
+ entry.identity.privateKey.fill(0);
390
+ throw new Error('Identity is already loaded with imported provenance');
391
+ }
312
392
  this.cache.set(npub, entry);
313
393
  return;
314
394
  }
@@ -326,7 +406,7 @@ export class IdentityContext {
326
406
  }
327
407
  if (oldestNpub) {
328
408
  const evicted = this.cache.get(oldestNpub);
329
- zeroise(evicted.identity);
409
+ evicted.identity.privateKey.fill(0);
330
410
  this.cache.delete(oldestNpub);
331
411
  }
332
412
  }
package/dist/format.js CHANGED
@@ -18,6 +18,8 @@ export function sanitiseTerminal(s) {
18
18
  const st = sanitiseTerminal;
19
19
  export function formatIdentity(id) {
20
20
  let line = `${id.npub}`;
21
+ if (id.origin === 'imported')
22
+ return `${line} (imported; recovery needs master + encrypted record)`;
21
23
  if (id.personaName)
22
24
  line += ` (persona: ${id.personaName})`;
23
25
  else if (id.purpose)
package/dist/help.js CHANGED
@@ -1,6 +1,9 @@
1
1
  /** Per-command help with examples and detail */
2
2
  export const COMMAND_HELP = {
3
3
  // Identity
4
+ 'key-wrap': { usage: 'key-wrap <nsec-or-hex-file> <new-backup-file>', description: 'Preview: encrypt an existing raw key with the configured local master. Creates a new 0600 .nstw file and verifies it. Recovery needs the same master/root construction and this file. Keep an independent backup.', examples: ['nostr-bray key-wrap ./existing.key ./account.nstw'] },
5
+ 'key-check': { usage: 'key-check <backup-file> <expected-npub>', description: 'Authenticate an encrypted account backup against the configured local master and exact npub, without retaining the key.', examples: ['nostr-bray key-check ./account.nstw npub1...'] },
6
+ 'key-load': { usage: 'key-load <backup-file> <expected-npub>', description: 'Explicitly load an imported account into this local process without activating it. In shell mode use switch <npub> next. Imported keys cannot receive derivation proofs. No MCP recovery tool is added.', examples: ['key-load ./account.nstw npub1...'] },
4
7
  whoami: { usage: 'whoami', description: 'Show the active identity\'s npub.', examples: ['nostr-bray whoami'] },
5
8
  create: { usage: 'create', description: 'Generate a fresh Nostr identity with a BIP-39 mnemonic seed. Returns the master npub and mnemonic for backup.', examples: ['nostr-bray create'], notes: 'Store the mnemonic securely — it will not be shown again.' },
6
9
  list: { usage: 'list', description: 'List all known identities. Returns npub, purpose, and persona name. Never includes private keys.', examples: ['nostr-bray list'] },
@@ -2,3 +2,4 @@ export * from './handlers.js';
2
2
  export * from './shamir.js';
3
3
  export * from './migration.js';
4
4
  export * from './nip05.js';
5
+ export * from './wrapped-files.js';
@@ -2,3 +2,4 @@ export * from './handlers.js';
2
2
  export * from './shamir.js';
3
3
  export * from './migration.js';
4
4
  export * from './nip05.js';
5
+ export * from './wrapped-files.js';
@@ -0,0 +1,10 @@
1
+ import type { IdentityContext } from '../context.js';
2
+ /** Owner-only offline export. Atomically creates a new file; never overwrites an old backup. */
3
+ export declare function wrapKeyFile(ctx: IdentityContext, input: string, output: string): Promise<{
4
+ file: string;
5
+ npub: string;
6
+ }>;
7
+ /** Verify a selected backup file without loading its account or returning its secret. */
8
+ export declare function checkWrappedKeyFile(ctx: IdentityContext, file: string, expectedNpub: string): Promise<import("../types.js").PublicIdentity>;
9
+ /** Explicit owner restore into this local process; selection still requires switch(npub). */
10
+ export declare function loadWrappedKeyFile(ctx: IdentityContext, file: string, expectedNpub: string): Promise<import("../types.js").PublicIdentity>;
@@ -0,0 +1,96 @@
1
+ import { openSync, closeSync, fstatSync, readSync, writeFileSync, linkSync, unlinkSync, realpathSync } from 'node:fs';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { decode } from 'nostr-tools/nip19';
5
+ import { getInputAllowlist, validateInputPath } from '../validation.js';
6
+ /** Bounded regular-file read; checks the resolved path against Bray's input policy. */
7
+ function resolvedPolicy(path) {
8
+ const roots = getInputAllowlist().flatMap(root => {
9
+ try {
10
+ return [realpathSync(root)];
11
+ }
12
+ catch {
13
+ return [];
14
+ }
15
+ });
16
+ return validateInputPath(path, roots);
17
+ }
18
+ function readSmallFile(path) {
19
+ const checked = resolvedPolicy(realpathSync(validateInputPath(path)));
20
+ const fd = openSync(checked, 'r');
21
+ const buffer = Buffer.alloc(1025);
22
+ try {
23
+ const stat = fstatSync(fd);
24
+ if (!stat.isFile() || stat.size > 1024)
25
+ throw new Error('Key/backup file is too large or is not a regular file');
26
+ const length = readSync(fd, buffer, 0, buffer.length, 0);
27
+ if (length > 1024)
28
+ throw new Error('Key/backup file is too large');
29
+ return Buffer.from(buffer.subarray(0, length));
30
+ }
31
+ finally {
32
+ buffer.fill(0);
33
+ closeSync(fd);
34
+ }
35
+ }
36
+ /** Owner-only offline export. Atomically creates a new file; never overwrites an old backup. */
37
+ export async function wrapKeyFile(ctx, input, output) {
38
+ const file = validateInputPath(resolve(output));
39
+ resolvedPolicy(realpathSync(dirname(file)));
40
+ const encoded = readSmallFile(input);
41
+ let raw;
42
+ let temporary;
43
+ let ownsTemporary = false;
44
+ try {
45
+ const text = encoded.toString('utf8').trim();
46
+ if (/^[0-9a-f]{64}$/i.test(text))
47
+ raw = Buffer.from(text, 'hex');
48
+ else {
49
+ const decoded = decode(text);
50
+ if (decoded.type !== 'nsec')
51
+ throw new Error('Expected an nsec or 32-byte hex key file');
52
+ raw = decoded.data;
53
+ }
54
+ const record = await ctx.wrapRawIdentity(raw);
55
+ const checked = await ctx.checkWrappedIdentity(record);
56
+ temporary = `${file}.${randomUUID()}.tmp`;
57
+ const fd = openSync(temporary, 'wx', 0o600);
58
+ ownsTemporary = true;
59
+ try {
60
+ writeFileSync(fd, record);
61
+ }
62
+ finally {
63
+ closeSync(fd);
64
+ }
65
+ // Authenticate the bytes read back from disk before linking the final name.
66
+ await checkWrappedKeyFile(ctx, temporary, checked.npub);
67
+ linkSync(temporary, file);
68
+ return { file, npub: checked.npub };
69
+ }
70
+ finally {
71
+ raw?.fill(0);
72
+ encoded.fill(0);
73
+ if (temporary && ownsTemporary)
74
+ unlinkSync(temporary);
75
+ }
76
+ }
77
+ /** Verify a selected backup file without loading its account or returning its secret. */
78
+ export async function checkWrappedKeyFile(ctx, file, expectedNpub) {
79
+ const bytes = readSmallFile(file);
80
+ try {
81
+ return await ctx.checkWrappedIdentity(bytes.toString('utf8').trim(), expectedNpub);
82
+ }
83
+ finally {
84
+ bytes.fill(0);
85
+ }
86
+ }
87
+ /** Explicit owner restore into this local process; selection still requires switch(npub). */
88
+ export async function loadWrappedKeyFile(ctx, file, expectedNpub) {
89
+ const bytes = readSmallFile(file);
90
+ try {
91
+ return await ctx.importWrappedIdentity(bytes.toString('utf8').trim(), expectedNpub);
92
+ }
93
+ finally {
94
+ bytes.fill(0);
95
+ }
96
+ }
@@ -1,6 +1,6 @@
1
1
  import type { EventTemplate, VerifiedEvent } from 'nostr-tools';
2
2
  /**
3
- * Guards for two nostr-tools (2.24) behaviours that otherwise mislead or crash
3
+ * Guards for three nostr-tools (2.24) behaviours that otherwise mislead or crash
4
4
  * bray. Every pool bray creates goes through these: the relay pool, the bunker
5
5
  * daemon, the bunker client and bunker pairing.
6
6
  */
@@ -13,6 +13,11 @@ export type ChallengeSigner = (evt: EventTemplate) => Promise<VerifiedEvent>;
13
13
  * answering. Use this rather than setting `pool.automaticallyAuth`.
14
14
  */
15
15
  export declare function setAutomaticAuth(pool: object, signerFor: ((relayUrl: string) => ChallengeSigner | null) | undefined): void;
16
+ /**
17
+ * Guard every relay a nostr-tools SimplePool connects to, as above. Call it
18
+ * once, straight after creating the pool.
19
+ */
20
+ export declare function guardRelaySends(pool: object): void;
16
21
  /**
17
22
  * Whether a resolved per-relay publish result is nostr-tools' report that it
18
23
  * could not connect ("connection failure: ..."), which it resolves with instead
@@ -44,6 +44,67 @@ export function setAutomaticAuth(pool, signerFor) {
44
44
  return sign;
45
45
  });
46
46
  }
47
+ const sendGuardedRelays = new WeakSet();
48
+ /**
49
+ * Keep a send on a closed connection from ending the process.
50
+ *
51
+ * nostr-tools sends an AUTH answer, and a subscription's REQ, without awaiting
52
+ * the send, and `send` rejects once the connection has closed. A relay that
53
+ * dropped the connection while the AUTH signature was still being made (a
54
+ * remote signer can take many seconds) therefore left a rejection nothing
55
+ * handled, and Node exited. Every send gets a handler here. A failed AUTH send
56
+ * also fails that AUTH at once with the send's error, the one nostr-tools'
57
+ * own automatic answer already ignores, instead of leaving it to report
58
+ * "auth timed out" seconds later.
59
+ */
60
+ function guardSends(relay) {
61
+ if (sendGuardedRelays.has(relay))
62
+ return;
63
+ sendGuardedRelays.add(relay);
64
+ const send = relay.send.bind(relay);
65
+ relay.send = message => {
66
+ const sent = send(message);
67
+ sent.catch(err => { if (message.startsWith('["AUTH",'))
68
+ failPendingAuth(relay, message, err); });
69
+ return sent;
70
+ };
71
+ }
72
+ function failPendingAuth(relay, message, err) {
73
+ let id;
74
+ try {
75
+ id = JSON.parse(message)[1]?.id;
76
+ }
77
+ catch {
78
+ return;
79
+ }
80
+ if (typeof id !== 'string')
81
+ return;
82
+ const pending = relay.openEventPublishes;
83
+ const entry = pending.get(id);
84
+ if (!entry)
85
+ return;
86
+ clearTimeout(entry.timeout);
87
+ pending.delete(id);
88
+ entry.reject(err);
89
+ }
90
+ /**
91
+ * Guard every relay a nostr-tools SimplePool connects to, as above. Call it
92
+ * once, straight after creating the pool.
93
+ */
94
+ export function guardRelaySends(pool) {
95
+ // The relay map is protected in nostr-tools' types. ensureRelay is the only
96
+ // place a relay is made, and it adds the relay to the map before it starts
97
+ // connecting, so the relay is guarded before any message can arrive. The map
98
+ // is read on each call because destroy() replaces it.
99
+ const p = pool;
100
+ const ensureRelay = p.ensureRelay.bind(pool);
101
+ p.ensureRelay = (...args) => {
102
+ const ready = ensureRelay(...args);
103
+ for (const relay of p.relays.values())
104
+ guardSends(relay);
105
+ return ready;
106
+ };
107
+ }
47
108
  /**
48
109
  * Whether a resolved per-relay publish result is nostr-tools' report that it
49
110
  * could not connect ("connection failure: ..."), which it resolves with instead
@@ -1,6 +1,6 @@
1
1
  import { validatePublicUrl, validateRelayScheme } from './validation.js';
2
2
  import { brayFetch } from './http-client.js';
3
- import { isConnectionFailure, setAutomaticAuth } from './nostr-tools-guards.js';
3
+ import { guardRelaySends, isConnectionFailure, setAutomaticAuth } from './nostr-tools-guards.js';
4
4
  import { errorMessage } from './error-message.js';
5
5
  // 512 KiB cap on any inbound relay frame. Protects against malicious relays
6
6
  // pushing 100 MB EVENTs that would exhaust memory (ws library defaults to
@@ -61,6 +61,7 @@ async function createRealPool(torProxy) {
61
61
  const WebSocketImpl = webSocketFor(torProxy, { maxPayload: WS_MAX_PAYLOAD });
62
62
  useWebSocketImplementation(WebSocketImpl);
63
63
  const pool = new SimplePool({ websocketImplementation: WebSocketImpl });
64
+ guardRelaySends(pool);
64
65
  const { normalizeURL } = await import('nostr-tools/utils');
65
66
  // nostr-tools reaches every relay through ensureRelay, so this is where a
66
67
  // connection can be refused reuse. The relay map is protected in its types.
package/dist/types.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import type { Event as NostrEvent, EventTemplate } from 'nostr-tools';
2
2
  /** Public identity info returned by tools — never includes private keys */
3
3
  export interface PublicIdentity {
4
+ readonly origin?: 'imported';
5
+ readonly recovery?: 'master-and-record';
4
6
  readonly npub: string;
5
7
  readonly purpose?: string;
6
8
  readonly index?: number;
package/llms-full.txt CHANGED
@@ -1269,3 +1269,15 @@ Execute an action found via search-actions.
1269
1269
  - Migration verifies backup event signatures before re-signing
1270
1270
  - Four-tier auth progression: bunker (NIP-46) > ncryptsec (NIP-49) > file > env var
1271
1271
  - Dispatch trust boundary: only known identities can send/receive tasks
1272
+
1273
+ ## Wrapped existing accounts (preview)
1274
+
1275
+ Owner-only local CLI commands `key-wrap <nsec-or-hex-file> <new-backup-file>`,
1276
+ `key-check <backup-file> <expected-npub>` and `key-load <backup-file>
1277
+ <expected-npub>` preserve an existing raw account. Recovery needs the same
1278
+ master/root construction AND the encrypted file. Load is process-local and
1279
+ does not activate the key; select its npub explicitly in shell mode. Imported
1280
+ identities report origin/recovery metadata, cannot get derivation proofs and
1281
+ retain forbidden-key enforcement. No MCP tool or hardware fallback is added.
1282
+ Pins the published nsec-tree 1.7.0-alpha.1 alpha with verified npm integrity. See docs/wrapped-account-preview.md for the SDK,
1283
+ file policy and release gate.
package/llms.txt CHANGED
@@ -184,3 +184,15 @@ Requires Node.js 24 or later. `npx nostr-bray` with no arguments starts the MCP
184
184
  - Agent scenarios (worked JSON-RPC transcripts): https://github.com/forgesworn/bray/tree/main/examples/agent-scenarios
185
185
  - Trust scoring: https://github.com/forgesworn/bray/blob/main/docs/trust-scoring.md
186
186
  - Dispatch protocol: https://github.com/forgesworn/bray/blob/main/docs/dispatch.md
187
+
188
+ ## Wrapped existing accounts (preview)
189
+
190
+ Owner-only local CLI commands `key-wrap <nsec-or-hex-file> <new-backup-file>`,
191
+ `key-check <backup-file> <expected-npub>` and `key-load <backup-file>
192
+ <expected-npub>` preserve an existing raw account. Recovery needs the same
193
+ master/root construction AND the encrypted file. Load is process-local and
194
+ does not activate the key; select its npub explicitly in shell mode. Imported
195
+ identities report origin/recovery metadata, cannot get derivation proofs and
196
+ retain forbidden-key enforcement. No MCP tool or hardware fallback is added.
197
+ Pins the published nsec-tree 1.7.0-alpha.1 alpha with verified npm integrity. See docs/wrapped-account-preview.md for the SDK,
198
+ file policy and release gate.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nostr-bray",
3
- "version": "3.14.3",
3
+ "version": "3.15.0",
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",
@@ -181,7 +181,7 @@
181
181
  "nostr-attestations": "^3.0.1",
182
182
  "nostr-tools": "2.24.1",
183
183
  "nostr-veil": "^0.34.0",
184
- "nsec-tree": "^1.4.2",
184
+ "nsec-tree": "1.7.0-alpha.1",
185
185
  "signet-protocol": "^1.1.0",
186
186
  "socks-proxy-agent": "^10.0.0",
187
187
  "spoken-token": "^2.0.3",