@johnhenry/browsermesh-core 0.8.0 → 0.10.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
@@ -26,7 +26,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
26
26
  |--------|-------------|
27
27
  | identity | `MeshIdentityManager`, `AutoIdentityManager`, `IdentitySelector`, `PodIdentity`, `derivePodId` |
28
28
  | identity-tools | `IdentityCreateTool`, `IdentityListTool`, `IdentitySwitchTool`, `registerIdentityTools` |
29
- | keyring | `MeshKeyring`, `KeyLink`, `SignedKeyLink`, `SuccessionPolicy` |
29
+ | keyring | `MeshKeyring`, `KeyLink`, `SignedKeyLink`, `SignedKeyUnlink`, `SuccessionPolicy` |
30
30
  | group-keys | `GroupKeyManager`, `GroupState` |
31
31
  | peer | `PeerState`, `MeshPeerManager` |
32
32
  | peer-tools | `MeshPeerToolsContext`, `registerMeshPeerTools` + 30 BrowserTool subclasses |
@@ -50,6 +50,34 @@ npm install @johnhenry/browsermesh-core @johnhenry/browsermesh-primitives
50
50
  import { MeshIdentityManager, MeshKeyring, TrustGraph } from '@johnhenry/browsermesh-core';
51
51
  ```
52
52
 
53
+ ## Verifying key links and capabilities from peers
54
+
55
+ - `MeshKeyring#verifyCryptoChain(from, to, getPublicKey)` requires every link
56
+ on the path to be a `SignedKeyLink` signed by both ends, unexpired, in the
57
+ keyring's `namespace` and not revoked. Unsigned `KeyLink`s (from `link()`)
58
+ are refused unless you pass `{ requireSigned: false }`.
59
+ - `SignedKeyLink`s sign `"browsermesh/keylink/v3\n"` + sorted-key canonical
60
+ JSON, including an optional `namespace`. Give the keyring and its links the
61
+ same namespace (`new MeshKeyring({ namespace })`,
62
+ `SignedKeyLink.create(p, c, rel, { namespace })`) so a link issued for one
63
+ keyring is refused by another.
64
+ - Revoke an edge with `SignedKeyUnlink.create(parentIdentity, childId)` and
65
+ `keyring.applyUnlink(unlink, parentPub)`. Unlinks serialise, can be relayed
66
+ to peers, and cut off every descendant of the child. `unlink()` is local only.
67
+ - `executeSuccession(primary, { links, getPublicKey })` with a `transfer`
68
+ policy needs successor-signed replacement links (`{ localOnly: true }` keeps
69
+ the old unsigned behaviour).
70
+ - Before a capability chain crosses peers, sign it (`CapabilityToken.issue`,
71
+ `token.attenuateSigned`) and check it on arrival with
72
+ `chain.verifySignatures(getPublicKey, { rootIssuer })`.
73
+
74
+ **Migrating links signed before 0.10 (v2 payload).** They no longer verify by
75
+ default. To migrate, load them into a keyring with `{ acceptLegacyV2: true }`
76
+ (verification only, never for signing), find them with
77
+ `link.signatureVersion(parentPub, childPub) === 2`, and re-sign each with
78
+ `link.resign(parentIdentity, childIdentity, { namespace })`. v1
79
+ (`a|b|c|d`) signatures are no longer accepted at all; re-create those links.
80
+
53
81
  ## Padding group-key envelopes
54
82
 
55
83
  `GroupKeyManager.encrypt()` leaks the exact plaintext length to anything that
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-core",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "Identity, crypto, peer management, and trust primitives for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -19,6 +19,9 @@
19
19
  "url": "https://github.com/johnhenry/browsermesh",
20
20
  "directory": "packages/browsermesh-core"
21
21
  },
22
+ "dependencies": {
23
+ "@johnhenry/keyvault": "^0.1.0"
24
+ },
22
25
  "peerDependencies": {
23
26
  "@johnhenry/browsermesh-primitives": ">=0.3.0 <1.0.0",
24
27
  "@johnhenry/browsermesh-apps": ">=0.4.0 <1.0.0"
@@ -0,0 +1,62 @@
1
+ /**
2
+ * canonical.mjs -- Deterministic, domain-separated signing payloads.
3
+ *
4
+ * Internal helper (not re-exported from index.mjs). Used by
5
+ * SignedKeyLink, SignedKeyUnlink and signed CapabilityTokens so that every
6
+ * signature this package produces:
7
+ *
8
+ * - is over a canonical encoding: JSON with object keys sorted (recursively),
9
+ * no whitespace, `undefined` object members omitted, and only finite
10
+ * numbers — so two implementations that agree on the value agree on the
11
+ * bytes, regardless of property insertion order;
12
+ * - carries a domain prefix (`<namespace>/<type>/v<n>\n`) so a signature
13
+ * minted for one message type can never be replayed as another, even when
14
+ * the two bodies happen to encode identically.
15
+ */
16
+
17
+ /**
18
+ * Canonical JSON encoding with sorted keys.
19
+ *
20
+ * @param {*} value
21
+ * @returns {string}
22
+ */
23
+ export function canonicalize(value) {
24
+ if (value === null) return 'null';
25
+ switch (typeof value) {
26
+ case 'boolean':
27
+ case 'string':
28
+ return JSON.stringify(value);
29
+ case 'number':
30
+ if (!Number.isFinite(value)) {
31
+ throw new TypeError(`Cannot canonicalize non-finite number: ${value}`);
32
+ }
33
+ return JSON.stringify(value);
34
+ case 'object': {
35
+ if (Array.isArray(value)) {
36
+ return `[${value.map((v) => {
37
+ if (v === undefined) throw new TypeError('Cannot canonicalize undefined array element');
38
+ return canonicalize(v);
39
+ }).join(',')}]`;
40
+ }
41
+ const proto = Object.getPrototypeOf(value);
42
+ if (proto !== Object.prototype && proto !== null) {
43
+ throw new TypeError('Can only canonicalize plain objects');
44
+ }
45
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
46
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize(value[k])}`).join(',')}}`;
47
+ }
48
+ default:
49
+ throw new TypeError(`Cannot canonicalize value of type ${typeof value}`);
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Bytes to sign: `prefix ‖ canonicalize(body)`, UTF-8 encoded.
55
+ *
56
+ * @param {string} prefix - Domain prefix, ending in `\n`
57
+ * @param {object} body
58
+ * @returns {Uint8Array}
59
+ */
60
+ export function domainPayload(prefix, body) {
61
+ return new TextEncoder().encode(prefix + canonicalize(body));
62
+ }
@@ -17,10 +17,16 @@
17
17
  * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-capabilities.test.mjs
18
18
  */
19
19
 
20
+ import { encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives';
21
+ import { domainPayload } from './canonical.mjs';
22
+
20
23
  // ---------------------------------------------------------------------------
21
24
  // Wire Constants
22
25
  // ---------------------------------------------------------------------------
23
26
 
27
+ /** Domain prefix of the bytes a signed {@link CapabilityToken} signs. */
28
+ export const CAPABILITY_DOMAIN = 'browsermesh/capability/v1\n';
29
+
24
30
  /** Wire type for capability grant message. */
25
31
  export const CAP_GRANT = 0xDC;
26
32
 
@@ -105,8 +111,17 @@ export function expiryNarrows(parentExpiry, childExpiry) {
105
111
  let _tokenSeq = 0;
106
112
 
107
113
  /**
108
- * An unforgeable capability token granting specific access rights.
114
+ * A capability token granting specific access rights.
109
115
  * Tokens can be attenuated (narrowed) but never amplified.
116
+ *
117
+ * A token built with `new CapabilityToken(...)` is unsigned: fine for a
118
+ * single process, but not something another peer should trust. Before a
119
+ * token or chain crosses peers, sign it: {@link CapabilityToken.issue} for a
120
+ * root, {@link CapabilityToken#attenuateSigned} for a delegation. The issuer
121
+ * signs `"browsermesh/capability/v1\n" ‖ canonical(body)` over every field
122
+ * except the local `revoked` flag — including `parentId` and `depth`, so a
123
+ * signed token is bound to its place in the chain. Verify a chain received
124
+ * from a peer with {@link CapabilityChain#verifySignatures}.
110
125
  */
111
126
  export class CapabilityToken {
112
127
  /**
@@ -123,6 +138,7 @@ export class CapabilityToken {
123
138
  * @param {boolean} [opts.revoked] Whether token has been revoked
124
139
  * @param {number} [opts.depth] Delegation depth (0 for root)
125
140
  * @param {number|null} [opts.maxDepth] Maximum delegation depth (null = unlimited)
141
+ * @param {Uint8Array|null} [opts.signature] Issuer's Ed25519 signature over {@link CapabilityToken#signedPayload}
126
142
  */
127
143
  constructor({
128
144
  id,
@@ -137,6 +153,7 @@ export class CapabilityToken {
137
153
  revoked = false,
138
154
  depth = 0,
139
155
  maxDepth = null,
156
+ signature = null,
140
157
  }) {
141
158
  if (!issuer || typeof issuer !== 'string') {
142
159
  throw new Error('issuer is required and must be a non-empty string');
@@ -163,6 +180,76 @@ export class CapabilityToken {
163
180
  this.revoked = revoked;
164
181
  this.depth = depth;
165
182
  this.maxDepth = maxDepth;
183
+ /** @type {Uint8Array|null} */
184
+ this.signature = signature || null;
185
+ }
186
+
187
+ /**
188
+ * Bytes the issuer signs: domain prefix plus sorted-key canonical JSON of
189
+ * every field except `revoked` (local state) and `signature`.
190
+ *
191
+ * @returns {Uint8Array}
192
+ */
193
+ get signedPayload() {
194
+ return domainPayload(CAPABILITY_DOMAIN, {
195
+ id: this.id,
196
+ issuer: this.issuer,
197
+ holder: this.holder,
198
+ resource: this.resource,
199
+ permissions: [...this.permissions],
200
+ constraints: { ...this.constraints },
201
+ parentId: this.parentId,
202
+ createdAt: this.createdAt,
203
+ expiresAt: this.expiresAt,
204
+ depth: this.depth,
205
+ maxDepth: this.maxDepth,
206
+ });
207
+ }
208
+
209
+ /** Whether the token carries a signature (not whether it verifies). */
210
+ get isSigned() {
211
+ return this.signature !== null;
212
+ }
213
+
214
+ /**
215
+ * Sign this token as its issuer. The identity must be the issuer.
216
+ *
217
+ * @param {{ podId: string, sign: (data: Uint8Array) => Promise<Uint8Array> }} issuerIdentity
218
+ * @returns {Promise<this>}
219
+ */
220
+ async sign(issuerIdentity) {
221
+ if (!issuerIdentity || issuerIdentity.podId !== this.issuer) {
222
+ throw new Error('Only the issuer can sign a capability token');
223
+ }
224
+ this.signature = await issuerIdentity.sign(this.signedPayload);
225
+ return this;
226
+ }
227
+
228
+ /**
229
+ * Verify the issuer's signature.
230
+ *
231
+ * @param {CryptoKey} issuerPub
232
+ * @returns {Promise<boolean>}
233
+ */
234
+ async verifySignature(issuerPub) {
235
+ if (!this.signature) return false;
236
+ try {
237
+ return await crypto.subtle.verify('Ed25519', issuerPub, this.signature, this.signedPayload);
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Issue a signed root token. `issuer` is the identity's pod ID.
245
+ *
246
+ * @param {{ podId: string, sign: Function }} issuerIdentity
247
+ * @param {object} opts - Constructor options other than `issuer`
248
+ * @returns {Promise<CapabilityToken>}
249
+ */
250
+ static async issue(issuerIdentity, opts) {
251
+ const token = new CapabilityToken({ ...opts, issuer: issuerIdentity.podId, signature: null });
252
+ return token.sign(issuerIdentity);
166
253
  }
167
254
 
168
255
  /** Check whether this token has expired. */
@@ -261,6 +348,21 @@ export class CapabilityToken {
261
348
  });
262
349
  }
263
350
 
351
+ /**
352
+ * {@link CapabilityToken#attenuate}, then sign the child as its issuer
353
+ * (this token's holder).
354
+ *
355
+ * @param {{ podId: string, sign: Function }} holderIdentity - This token's holder
356
+ * @param {object} opts - As for attenuate()
357
+ * @returns {Promise<CapabilityToken>}
358
+ */
359
+ async attenuateSigned(holderIdentity, opts) {
360
+ if (!holderIdentity || holderIdentity.podId !== this.holder) {
361
+ throw new Error('Only the holder can delegate a capability token');
362
+ }
363
+ return this.attenuate(opts).sign(holderIdentity);
364
+ }
365
+
264
366
  /** Revoke this token. */
265
367
  revoke() {
266
368
  this.revoked = true;
@@ -280,11 +382,15 @@ export class CapabilityToken {
280
382
  revoked: this.revoked,
281
383
  depth: this.depth,
282
384
  maxDepth: this.maxDepth,
385
+ ...(this.signature ? { signature: encodeBase64url(this.signature) } : {}),
283
386
  };
284
387
  }
285
388
 
286
389
  static fromJSON(data) {
287
- return new CapabilityToken(data);
390
+ return new CapabilityToken({
391
+ ...data,
392
+ signature: data.signature ? decodeBase64url(data.signature) : null,
393
+ });
288
394
  }
289
395
  }
290
396
 
@@ -415,6 +521,56 @@ export class CapabilityChain {
415
521
  return { valid: true };
416
522
  }
417
523
 
524
+ /**
525
+ * Structural {@link CapabilityChain#verify} plus signatures — use this for
526
+ * any chain that came from another peer. Additionally requires:
527
+ * - every token is signed by its `issuer` (key from `getPublicKey`);
528
+ * - each delegated token's `issuer` is the `holder` of its parent, so
529
+ * only the holder of a capability can delegate it;
530
+ * - optionally, the root's issuer is `opts.rootIssuer`.
531
+ *
532
+ * Because each signature covers `parentId` and `depth`, a signed token
533
+ * cannot be re-parented into another chain.
534
+ *
535
+ * @param {(podId: string) => CryptoKey|Promise<CryptoKey>} getPublicKey
536
+ * @param {object} [opts]
537
+ * @param {boolean} [opts.checkValidity=true]
538
+ * @param {string} [opts.rootIssuer] - Required issuer of the root token
539
+ * @returns {Promise<{ valid: boolean, error?: string, brokenAt?: number }>}
540
+ */
541
+ async verifySignatures(getPublicKey, opts = {}) {
542
+ const structural = this.verify(opts.checkValidity ?? true);
543
+ if (!structural.valid) return structural;
544
+
545
+ if (opts.rootIssuer !== undefined && this.#tokens[0].issuer !== opts.rootIssuer) {
546
+ return { valid: false, error: 'Root token issuer is not trusted', brokenAt: 0 };
547
+ }
548
+
549
+ for (let i = 0; i < this.#tokens.length; i++) {
550
+ const token = this.#tokens[i];
551
+ if (!token.signature) {
552
+ return { valid: false, error: `Token at index ${i} is unsigned`, brokenAt: i };
553
+ }
554
+ if (i > 0 && token.issuer !== this.#tokens[i - 1].holder) {
555
+ return {
556
+ valid: false,
557
+ error: `Token at index ${i} was issued by "${token.issuer}", not by its parent's holder`,
558
+ brokenAt: i,
559
+ };
560
+ }
561
+ let pub;
562
+ try {
563
+ pub = await getPublicKey(token.issuer);
564
+ } catch {
565
+ pub = null;
566
+ }
567
+ if (!pub || !(await token.verifySignature(pub))) {
568
+ return { valid: false, error: `Bad signature at index ${i}`, brokenAt: i };
569
+ }
570
+ }
571
+ return { valid: true };
572
+ }
573
+
418
574
  /** Get all tokens as array. */
419
575
  toArray() {
420
576
  return [...this.#tokens];
package/src/identity.mjs CHANGED
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  import { silentCatch } from './silent-catch.mjs'
16
+ import { seal, open as openRecord, needsUpgrade, VaultError } from '@johnhenry/keyvault';
16
17
  import {
17
18
  PodIdentity,
18
19
  derivePodId,
@@ -24,13 +25,18 @@ import {
24
25
  export { PodIdentity, derivePodId, encodeBase64url, decodeBase64url };
25
26
 
26
27
  // ---------------------------------------------------------------------------
27
- // PBKDF2 / AES-GCM constants (shared with VaultIdentityStorage)
28
+ // Passphrase encryption (via @johnhenry/keyvault)
28
29
  // ---------------------------------------------------------------------------
29
30
 
30
- const VAULT_PBKDF2_ITERATIONS = 310_000;
31
- const VAULT_SALT_BYTES = 16;
32
- const VAULT_IV_BYTES = 12;
33
- const VAULT_KDF = 'PBKDF2-SHA256';
31
+ /** Record type of an encrypted private key stored by VaultIdentityStorage. */
32
+ const VAULT_TYPE = 'browsermesh-vault';
33
+ /** Record type of an encrypted identity export (`export(podId, passphrase)`). */
34
+ const EXPORT_TYPE = 'browsermesh-identity-export';
35
+ /**
36
+ * The only KDF name the pre-keyvault envelope (`kdf` was a string) could carry.
37
+ * Kept to refuse any other string with the message callers have always seen.
38
+ */
39
+ const LEGACY_VAULT_KDF = 'PBKDF2-SHA256';
34
40
 
35
41
  /**
36
42
  * Reject a passphrase that would not actually protect anything.
@@ -57,94 +63,56 @@ function requirePassphrase(passphrase, source) {
57
63
  }
58
64
 
59
65
  /**
60
- * PBKDF2(SHA-256) → AES-256-GCM over a UTF-8 string.
61
- *
62
- * The KDF name and iteration count travel with the ciphertext so a future
63
- * change of parameters does not orphan envelopes written under the old ones.
66
+ * Encrypt a UTF-8 string under a passphrase with keyvault (PBKDF2-SHA256 at
67
+ * keyvault's current default, AES-256-GCM, KDF parameters and `header`
68
+ * authenticated and stored in the record).
64
69
  *
65
70
  * @param {string} plaintext
66
71
  * @param {string} passphrase
67
- * @returns {Promise<{ kdf: string, iterations: number, salt: string, iv: string, ciphertext: string }>}
72
+ * @param {string} type - Record type
73
+ * @param {object} [header] - Extra readable, authenticated fields
74
+ * @returns {Promise<object>} A keyvault record (plain JSON object)
68
75
  */
69
- async function encryptWithPassphrase(plaintext, passphrase) {
70
- const enc = new TextEncoder();
71
- const salt = crypto.getRandomValues(new Uint8Array(VAULT_SALT_BYTES));
72
- const iv = crypto.getRandomValues(new Uint8Array(VAULT_IV_BYTES));
73
-
74
- const baseKey = await crypto.subtle.importKey(
75
- 'raw',
76
- enc.encode(passphrase),
77
- 'PBKDF2',
78
- false,
79
- ['deriveKey']
80
- );
81
-
82
- const aesKey = await crypto.subtle.deriveKey(
83
- { name: 'PBKDF2', salt, iterations: VAULT_PBKDF2_ITERATIONS, hash: 'SHA-256' },
84
- baseKey,
85
- { name: 'AES-GCM', length: 256 },
86
- false,
87
- ['encrypt']
88
- );
89
-
90
- const ciphertext = new Uint8Array(
91
- await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, enc.encode(plaintext))
92
- );
93
-
94
- return {
95
- kdf: VAULT_KDF,
96
- iterations: VAULT_PBKDF2_ITERATIONS,
97
- salt: encodeBase64url(salt),
98
- iv: encodeBase64url(iv),
99
- ciphertext: encodeBase64url(ciphertext),
100
- };
76
+ async function encryptWithPassphrase(plaintext, passphrase, type, header) {
77
+ return JSON.parse(await seal(plaintext, passphrase, { type, header }));
101
78
  }
102
79
 
103
80
  /**
104
- * Inverse of {@link encryptWithPassphrase}.
81
+ * Inverse of {@link encryptWithPassphrase}. Also opens envelopes written by
82
+ * browsermesh-core <= 0.8.0 (`{ kdf?, iterations?, salt, iv, ciphertext }`,
83
+ * 310k iterations when `iterations` is absent, passphrase used as typed).
105
84
  *
106
- * `iterations` is read from the envelope so blobs written before the count
107
- * was recorded (and before it was raised to match the documented 310k) still
108
- * open.
85
+ * Errors keep the shapes this API has always had: a wrong passphrase (or a
86
+ * modified record) rejects with a DOMException named `OperationError`, an
87
+ * unknown string `kdf` with `Unsupported key derivation function: <kdf>`.
88
+ * Anything else keyvault reports is rethrown as its `VaultError`.
109
89
  *
110
- * @param {{ kdf?: string, iterations?: number, salt: string, iv: string, ciphertext: string }} envelope
90
+ * @param {object} envelope
111
91
  * @param {string} passphrase
112
- * @returns {Promise<string>}
92
+ * @param {string[]} types - Accepted record types
93
+ * @returns {Promise<{ plaintext: string, upgrade: boolean }>}
113
94
  */
114
- async function decryptWithPassphrase(envelope, passphrase) {
115
- const { kdf, iterations, salt, iv, ciphertext } = envelope;
116
- if (kdf !== undefined && kdf !== VAULT_KDF) {
117
- throw new Error(`Unsupported key derivation function: ${kdf}`);
118
- }
119
-
120
- const baseKey = await crypto.subtle.importKey(
121
- 'raw',
122
- new TextEncoder().encode(passphrase),
123
- 'PBKDF2',
124
- false,
125
- ['deriveKey']
126
- );
127
-
128
- const aesKey = await crypto.subtle.deriveKey(
129
- {
130
- name: 'PBKDF2',
131
- salt: decodeBase64url(salt),
132
- iterations: iterations ?? VAULT_PBKDF2_ITERATIONS,
133
- hash: 'SHA-256',
134
- },
135
- baseKey,
136
- { name: 'AES-GCM', length: 256 },
137
- false,
138
- ['decrypt']
139
- );
140
-
141
- const plaintext = await crypto.subtle.decrypt(
142
- { name: 'AES-GCM', iv: decodeBase64url(iv) },
143
- aesKey,
144
- decodeBase64url(ciphertext)
145
- );
146
-
147
- return new TextDecoder().decode(plaintext);
95
+ async function decryptWithPassphrase(envelope, passphrase, types) {
96
+ if (typeof envelope?.kdf === 'string' && envelope.kdf !== LEGACY_VAULT_KDF) {
97
+ throw new Error(`Unsupported key derivation function: ${envelope.kdf}`);
98
+ }
99
+ try {
100
+ const r = await openRecord(envelope, passphrase);
101
+ if (!types.includes(r.type)) {
102
+ throw new VaultError('wrong_type', `unexpected record type ${JSON.stringify(String(r.type).slice(0, 60))}`);
103
+ }
104
+ return {
105
+ plaintext: new TextDecoder().decode(r.payload),
106
+ upgrade: needsUpgrade(envelope),
107
+ };
108
+ } catch (err) {
109
+ if (err instanceof VaultError && err.code === 'bad_passphrase') {
110
+ const e = new DOMException('The operation failed for an operation-specific reason', 'OperationError');
111
+ e.cause = err;
112
+ throw e;
113
+ }
114
+ throw err;
115
+ }
148
116
  }
149
117
 
150
118
  // ---------------------------------------------------------------------------
@@ -375,7 +343,7 @@ export class MeshIdentityManager {
375
343
  );
376
344
  let plaintext;
377
345
  try {
378
- plaintext = await decryptWithPassphrase(keyData, passphrase);
346
+ ({ plaintext } = await decryptWithPassphrase(keyData, passphrase, [VAULT_TYPE, EXPORT_TYPE]));
379
347
  } catch (err) {
380
348
  throw unreadable(err);
381
349
  }
@@ -456,8 +424,11 @@ export class MeshIdentityManager {
456
424
  * is the documented plaintext-export path, and the caller is responsible
457
425
  * for what happens to it next.
458
426
  *
459
- * Called with a passphrase, it returns an encrypted envelope
460
- * (`{ encrypted: true, kdf, iterations, salt, iv, ciphertext }`) or it
427
+ * Called with a passphrase, it returns an encrypted envelope, a
428
+ * `@johnhenry/keyvault` record
429
+ * (`{ v, t, encrypted: true, kdf: { name, iterations, salt }, iv, ct }`;
430
+ * browsermesh-core <= 0.8.0 wrote `{ encrypted: true, kdf, iterations,
431
+ * salt, iv, ciphertext }`, which `import()` still reads) or it
461
432
  * throws. It never quietly hands back the plaintext key instead: a caller
462
433
  * who asked for encryption and got an unlabelled JWK would have no way to
463
434
  * tell, and would go on to write, paste or QR-encode a private key it
@@ -488,7 +459,7 @@ export class MeshIdentityManager {
488
459
 
489
460
  let envelope;
490
461
  try {
491
- envelope = await encryptWithPassphrase(JSON.stringify(jwk), passphrase);
462
+ envelope = await encryptWithPassphrase(JSON.stringify(jwk), passphrase, EXPORT_TYPE, { encrypted: true });
492
463
  } catch (err) {
493
464
  // Deliberately not falling back to the plaintext JWK. Encryption was
494
465
  // asked for; if it cannot be done, the caller has to know.
@@ -499,7 +470,7 @@ export class MeshIdentityManager {
499
470
  );
500
471
  }
501
472
 
502
- return { encrypted: true, ...envelope };
473
+ return envelope;
503
474
  }
504
475
 
505
476
  // -- Lookup & Enumeration -----------------------------------------------
@@ -943,7 +914,9 @@ export class IndexedDBIdentityStorage {
943
914
  /**
944
915
  * Wraps another identity storage with passphrase-based encryption.
945
916
  * Only the privateKey field is encrypted; publicKey + metadata stored cleartext.
946
- * Uses PBKDF2(310k, SHA-256) → AES-256-GCM.
917
+ * Uses @johnhenry/keyvault (PBKDF2-SHA256 → AES-256-GCM). Records written by
918
+ * browsermesh-core <= 0.8.0 (310k iterations) still open and are re-encrypted
919
+ * with keyvault's current defaults on the first successful load.
947
920
  *
948
921
  * `getPassphrase` must resolve to a non-empty string. An empty string or a
949
922
  * missing value is refused rather than used: PBKDF2 accepts an empty key and
@@ -987,7 +960,8 @@ export class VaultIdentityStorage {
987
960
  const passphrase = requirePassphrase(await this.#getPassphrase(), 'getPassphrase');
988
961
  record.encryptedPrivateKey = await encryptWithPassphrase(
989
962
  JSON.stringify(record.privateKeyJwk),
990
- passphrase
963
+ passphrase,
964
+ VAULT_TYPE
991
965
  );
992
966
  record.privateKeyJwk = null;
993
967
  }
@@ -1009,10 +983,26 @@ export class VaultIdentityStorage {
1009
983
 
1010
984
  if (record.encryptedPrivateKey) {
1011
985
  const passphrase = requirePassphrase(await this.#getPassphrase(), 'getPassphrase');
1012
- record.privateKeyJwk = JSON.parse(
1013
- await decryptWithPassphrase(record.encryptedPrivateKey, passphrase)
1014
- );
986
+ const stored = record.encryptedPrivateKey;
987
+ const { plaintext, upgrade } = await decryptWithPassphrase(stored, passphrase, [VAULT_TYPE]);
988
+ record.privateKeyJwk = JSON.parse(plaintext);
1015
989
  delete record.encryptedPrivateKey;
990
+
991
+ // Re-encrypt records written under older parameters (310k iterations,
992
+ // no kdf recorded, the pre-keyvault envelope) with the current defaults.
993
+ // Best effort: the unlock has succeeded either way, and the old record
994
+ // stays valid if the write-back fails.
995
+ if (upgrade) {
996
+ try {
997
+ await this.#inner.save(podId, {
998
+ ...record,
999
+ privateKeyJwk: null,
1000
+ encryptedPrivateKey: await encryptWithPassphrase(plaintext, passphrase, VAULT_TYPE),
1001
+ });
1002
+ } catch (err) {
1003
+ silentCatch('clawser-mesh-identity', 'vault-upgrade', err);
1004
+ }
1005
+ }
1016
1006
  }
1017
1007
 
1018
1008
  return record;