@johnhenry/browsermesh-core 0.0.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.
@@ -0,0 +1,1349 @@
1
+ /**
2
+ * clawser-mesh-identity.js -- Mesh identity management.
3
+ *
4
+ * Manages multiple Ed25519 cryptographic identities with vault-encrypted
5
+ * storage. Imports primitives from mesh-primitives; adds persistence,
6
+ * vault encryption, and DID support.
7
+ *
8
+ * Browser/Node dual: crypto.subtle calls are gated behind async methods.
9
+ * Storage adapter pattern allows OPFS in browser, in-memory in tests.
10
+ *
11
+ * Run tests:
12
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-identity.test.mjs
13
+ */
14
+
15
+ import { silentCatch } from './silent-catch.mjs'
16
+ import {
17
+ PodIdentity,
18
+ derivePodId,
19
+ encodeBase64url,
20
+ decodeBase64url,
21
+ } from '@johnhenry/browsermesh-primitives';
22
+
23
+ // Re-export primitives used by consumers
24
+ export { PodIdentity, derivePodId, encodeBase64url, decodeBase64url };
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // PBKDF2 / AES-GCM constants (shared with VaultIdentityStorage)
28
+ // ---------------------------------------------------------------------------
29
+
30
+ const VAULT_PBKDF2_ITERATIONS = 310_000;
31
+ const VAULT_SALT_BYTES = 16;
32
+ const VAULT_IV_BYTES = 12;
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // base58btc encoding (Bitcoin alphabet) — used for W3C did:key
36
+ // ---------------------------------------------------------------------------
37
+
38
+ const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
39
+
40
+ /**
41
+ * Encode bytes as base58btc (Bitcoin alphabet) without checksum.
42
+ * Used for W3C did:key URIs (RFC 5234, Multibase 'z' prefix).
43
+ *
44
+ * @param {Uint8Array} bytes
45
+ * @returns {string}
46
+ */
47
+ const base58btcEncode = (bytes) => {
48
+ if (bytes.length === 0) return '';
49
+ // Count leading zeros
50
+ let zeros = 0;
51
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
52
+
53
+ // Convert to base 58 via repeated division
54
+ const input = Array.from(bytes);
55
+ const out = [];
56
+ let start = zeros;
57
+ while (start < input.length) {
58
+ let remainder = 0;
59
+ let i = start;
60
+ for (; i < input.length; i++) {
61
+ const acc = remainder * 256 + input[i];
62
+ input[i] = Math.floor(acc / 58);
63
+ remainder = acc % 58;
64
+ }
65
+ out.push(BASE58_ALPHABET[remainder]);
66
+ while (start < input.length && input[start] === 0) start++;
67
+ }
68
+
69
+ // Each leading zero byte → '1' (alphabet[0])
70
+ let prefix = '';
71
+ for (let i = 0; i < zeros; i++) prefix += BASE58_ALPHABET[0];
72
+
73
+ return prefix + out.reverse().join('');
74
+ };
75
+
76
+ // ---------------------------------------------------------------------------
77
+ // In-memory storage adapter (for tests and standalone use)
78
+ // ---------------------------------------------------------------------------
79
+
80
+ /**
81
+ * In-memory identity storage adapter.
82
+ * Implements the same async interface as OPFS/vault-backed stores.
83
+ */
84
+ export class InMemoryIdentityStorage {
85
+ /** @type {Map<string, *>} */
86
+ #data = new Map();
87
+
88
+ /**
89
+ * @param {string} podId
90
+ * @param {*} data
91
+ */
92
+ async save(podId, data) {
93
+ this.#data.set(podId, structuredClone(data));
94
+ }
95
+
96
+ /**
97
+ * @param {string} podId
98
+ * @returns {Promise<*|null>}
99
+ */
100
+ async load(podId) {
101
+ const val = this.#data.get(podId);
102
+ return val !== undefined ? structuredClone(val) : null;
103
+ }
104
+
105
+ /**
106
+ * @param {string} podId
107
+ * @returns {Promise<boolean>}
108
+ */
109
+ async delete(podId) {
110
+ return this.#data.delete(podId);
111
+ }
112
+
113
+ /** @returns {Promise<string[]>} */
114
+ async list() {
115
+ return [...this.#data.keys()];
116
+ }
117
+
118
+ async clear() {
119
+ this.#data.clear();
120
+ }
121
+ }
122
+
123
+ // ---------------------------------------------------------------------------
124
+ // MeshIdentityManager
125
+ // ---------------------------------------------------------------------------
126
+
127
+ /**
128
+ * @typedef {object} IdentityEntry
129
+ * @property {PodIdentity} identity - The Ed25519 PodIdentity
130
+ * @property {string} label - Human-readable label
131
+ * @property {object} metadata - Arbitrary metadata
132
+ * @property {number} created - Unix timestamp (ms)
133
+ */
134
+
135
+ /**
136
+ * @typedef {object} IdentitySummary
137
+ * @property {string} podId
138
+ * @property {string} label
139
+ * @property {string} did
140
+ * @property {number} created
141
+ * @property {object} metadata
142
+ */
143
+
144
+ /**
145
+ * Multi-identity manager with pluggable storage.
146
+ *
147
+ * Wraps `PodIdentity` from mesh-primitives with:
148
+ * - Named identity management (create, import, delete, list)
149
+ * - DID:key generation
150
+ * - Sign/verify helpers
151
+ * - Persistence via storage adapter
152
+ */
153
+ export class MeshIdentityManager {
154
+ /** @type {Map<string, IdentityEntry>} */
155
+ #identities = new Map();
156
+
157
+ /** @type {string|null} */
158
+ #defaultId = null;
159
+
160
+ /** @type {InMemoryIdentityStorage} */
161
+ #storage;
162
+
163
+ /** @type {Function} */
164
+ #onLog;
165
+
166
+ /**
167
+ * @param {object} [opts]
168
+ * @param {InMemoryIdentityStorage} [opts.storage]
169
+ * @param {Function} [opts.onLog]
170
+ */
171
+ constructor(opts = {}) {
172
+ this.#storage = opts.storage || new InMemoryIdentityStorage();
173
+ this.#onLog = opts.onLog || (() => {});
174
+ }
175
+
176
+ // -- Creation & Import --------------------------------------------------
177
+
178
+ /**
179
+ * Generate a fresh Ed25519 identity.
180
+ *
181
+ * @param {string} label - Human-readable name
182
+ * @param {object} [opts]
183
+ * @param {object} [opts.metadata] - Arbitrary metadata to attach
184
+ * @returns {Promise<IdentitySummary>}
185
+ */
186
+ async create(label, opts = {}) {
187
+ if (!label || typeof label !== 'string') {
188
+ throw new Error('Label is required and must be a non-empty string');
189
+ }
190
+ const identity = await PodIdentity.generate();
191
+ const created = Date.now();
192
+ const metadata = opts.metadata || {};
193
+
194
+ // Cache raw public key bytes for proper W3C did:key encoding.
195
+ let rawPubKey = null;
196
+ try {
197
+ const raw = await crypto.subtle.exportKey('raw', identity.keyPair.publicKey);
198
+ rawPubKey = new Uint8Array(raw);
199
+ } catch { /* exportable: false — fall back to legacy DID form */ }
200
+
201
+ this.#identities.set(identity.podId, { identity, label, metadata, created, rawPubKey });
202
+ this.#onLog('identity:create', { podId: identity.podId, label });
203
+
204
+ // Auto-set default if this is the first identity
205
+ if (this.#identities.size === 1) {
206
+ this.#defaultId = identity.podId;
207
+ }
208
+
209
+ return {
210
+ podId: identity.podId,
211
+ label,
212
+ did: this.toDID(identity.podId),
213
+ created,
214
+ metadata,
215
+ };
216
+ }
217
+
218
+ /**
219
+ * Import an identity from a JWK private key.
220
+ *
221
+ * @param {object} privateKeyJwk - Ed25519 private key in JWK format
222
+ * @param {string} label - Human-readable name
223
+ * @param {object} [opts]
224
+ * @param {object} [opts.metadata]
225
+ * @returns {Promise<IdentitySummary>}
226
+ */
227
+ async import(privateKeyJwk, label, opts = {}) {
228
+ if (!label || typeof label !== 'string') {
229
+ throw new Error('Label is required and must be a non-empty string');
230
+ }
231
+ if (!privateKeyJwk || typeof privateKeyJwk !== 'object') {
232
+ throw new Error('privateKeyJwk must be a valid JWK object');
233
+ }
234
+
235
+ // Import the private key
236
+ const privateKey = await crypto.subtle.importKey(
237
+ 'jwk',
238
+ privateKeyJwk,
239
+ { name: 'Ed25519' },
240
+ true,
241
+ ['sign']
242
+ );
243
+
244
+ // Derive the public key by exporting and re-importing
245
+ const jwkPub = { ...privateKeyJwk };
246
+ delete jwkPub.d; // remove private component
247
+ jwkPub.key_ops = ['verify'];
248
+ const publicKey = await crypto.subtle.importKey(
249
+ 'jwk',
250
+ jwkPub,
251
+ { name: 'Ed25519' },
252
+ true,
253
+ ['verify']
254
+ );
255
+
256
+ const keyPair = { publicKey, privateKey };
257
+ const podId = await derivePodId(publicKey);
258
+ const identity = new PodIdentity({ keyPair, podId });
259
+ const created = Date.now();
260
+ const metadata = opts?.metadata || {};
261
+
262
+ let rawPubKey = null;
263
+ try {
264
+ const raw = await crypto.subtle.exportKey('raw', publicKey);
265
+ rawPubKey = new Uint8Array(raw);
266
+ } catch { /* exportable: false — fall back to legacy DID form */ }
267
+
268
+ this.#identities.set(podId, { identity, label, metadata, created, rawPubKey });
269
+ this.#onLog('identity:import', { podId, label });
270
+
271
+ if (this.#identities.size === 1) {
272
+ this.#defaultId = podId;
273
+ }
274
+
275
+ return {
276
+ podId,
277
+ label,
278
+ did: this.toDID(podId),
279
+ created,
280
+ metadata,
281
+ };
282
+ }
283
+
284
+ // -- Export -------------------------------------------------------------
285
+
286
+ /**
287
+ * Export an identity as a JWK.
288
+ *
289
+ * When a passphrase is provided and PBKDF2 + AES-GCM are available, the
290
+ * JWK is encrypted. Otherwise the raw JWK is returned (suitable for tests
291
+ * or environments without PBKDF2).
292
+ *
293
+ * @param {string} podId
294
+ * @param {string} [passphrase] - Optional encryption passphrase
295
+ * @returns {Promise<object>} JWK (possibly encrypted)
296
+ */
297
+ async export(podId, passphrase) {
298
+ const entry = this.#identities.get(podId);
299
+ if (!entry) throw new Error(`Unknown identity: ${podId}`);
300
+
301
+ const jwk = await crypto.subtle.exportKey('jwk', entry.identity.keyPair.privateKey);
302
+
303
+ if (!passphrase) return jwk;
304
+
305
+ // Attempt PBKDF2 + AES-GCM encryption
306
+ try {
307
+ const enc = new TextEncoder();
308
+ const salt = crypto.getRandomValues(new Uint8Array(16));
309
+ const iv = crypto.getRandomValues(new Uint8Array(12));
310
+
311
+ const baseKey = await crypto.subtle.importKey(
312
+ 'raw',
313
+ enc.encode(passphrase),
314
+ 'PBKDF2',
315
+ false,
316
+ ['deriveKey']
317
+ );
318
+
319
+ const aesKey = await crypto.subtle.deriveKey(
320
+ { name: 'PBKDF2', salt, iterations: 100_000, hash: 'SHA-256' },
321
+ baseKey,
322
+ { name: 'AES-GCM', length: 256 },
323
+ false,
324
+ ['encrypt']
325
+ );
326
+
327
+ const ciphertext = new Uint8Array(
328
+ await crypto.subtle.encrypt(
329
+ { name: 'AES-GCM', iv },
330
+ aesKey,
331
+ enc.encode(JSON.stringify(jwk))
332
+ )
333
+ );
334
+
335
+ return {
336
+ encrypted: true,
337
+ salt: encodeBase64url(salt),
338
+ iv: encodeBase64url(iv),
339
+ ciphertext: encodeBase64url(ciphertext),
340
+ };
341
+ } catch {
342
+ // PBKDF2 or AES-GCM not available -- return raw JWK
343
+ return jwk;
344
+ }
345
+ }
346
+
347
+ // -- Lookup & Enumeration -----------------------------------------------
348
+
349
+ /**
350
+ * List all identities (no private keys).
351
+ *
352
+ * @returns {IdentitySummary[]}
353
+ */
354
+ list() {
355
+ const out = [];
356
+ for (const [podId, entry] of this.#identities) {
357
+ out.push({
358
+ podId,
359
+ label: entry.label,
360
+ did: this.toDID(podId),
361
+ created: entry.created,
362
+ metadata: { ...entry.metadata },
363
+ });
364
+ }
365
+ return out;
366
+ }
367
+
368
+ /**
369
+ * Get a single identity summary (no private key).
370
+ *
371
+ * @param {string} podId
372
+ * @returns {IdentitySummary|null}
373
+ */
374
+ get(podId) {
375
+ const entry = this.#identities.get(podId);
376
+ if (!entry) return null;
377
+ return {
378
+ podId,
379
+ label: entry.label,
380
+ did: this.toDID(podId),
381
+ created: entry.created,
382
+ metadata: { ...entry.metadata },
383
+ };
384
+ }
385
+
386
+ /**
387
+ * Check whether an identity exists.
388
+ *
389
+ * @param {string} podId
390
+ * @returns {boolean}
391
+ */
392
+ has(podId) {
393
+ return this.#identities.has(podId);
394
+ }
395
+
396
+ /**
397
+ * Delete an identity.
398
+ *
399
+ * @param {string} podId
400
+ * @returns {boolean} true if it existed
401
+ */
402
+ delete(podId) {
403
+ const existed = this.#identities.delete(podId);
404
+ if (existed) {
405
+ this.#onLog('identity:delete', { podId });
406
+ if (this.#defaultId === podId) {
407
+ const first = this.#identities.keys().next();
408
+ this.#defaultId = first.done ? null : first.value;
409
+ }
410
+ }
411
+ return existed;
412
+ }
413
+
414
+ // -- Default identity ---------------------------------------------------
415
+
416
+ /**
417
+ * Set the default identity.
418
+ *
419
+ * @param {string} podId
420
+ */
421
+ setDefault(podId) {
422
+ if (!this.#identities.has(podId)) {
423
+ throw new Error(`Unknown identity: ${podId}`);
424
+ }
425
+ this.#defaultId = podId;
426
+ }
427
+
428
+ /**
429
+ * Get the default identity summary.
430
+ *
431
+ * @returns {IdentitySummary|null}
432
+ */
433
+ getDefault() {
434
+ if (this.#defaultId && this.#identities.has(this.#defaultId)) {
435
+ return this.get(this.#defaultId);
436
+ }
437
+ const first = this.#identities.keys().next();
438
+ return first.done ? null : this.get(first.value);
439
+ }
440
+
441
+ // -- Cryptographic operations -------------------------------------------
442
+
443
+ /**
444
+ * Sign data with a specific identity.
445
+ *
446
+ * @param {string} podId
447
+ * @param {BufferSource} data
448
+ * @returns {Promise<Uint8Array>} Ed25519 signature
449
+ */
450
+ async sign(podId, data) {
451
+ const entry = this.#identities.get(podId);
452
+ if (!entry) throw new Error(`Unknown identity: ${podId}`);
453
+ return entry.identity.sign(data);
454
+ }
455
+
456
+ /**
457
+ * Verify a signature against a public key (raw bytes).
458
+ *
459
+ * @param {Uint8Array} publicKeyBytes - Raw Ed25519 public key (32 bytes)
460
+ * @param {BufferSource} data
461
+ * @param {BufferSource} signature
462
+ * @returns {Promise<boolean>}
463
+ */
464
+ async verify(publicKeyBytes, data, signature) {
465
+ const publicKey = await crypto.subtle.importKey(
466
+ 'raw',
467
+ publicKeyBytes,
468
+ { name: 'Ed25519' },
469
+ false,
470
+ ['verify']
471
+ );
472
+ return PodIdentity.verify(publicKey, data, signature);
473
+ }
474
+
475
+ /**
476
+ * Get the raw public key bytes for an identity.
477
+ *
478
+ * @param {string} podId
479
+ * @returns {Promise<Uint8Array>}
480
+ */
481
+ async getPublicKeyBytes(podId) {
482
+ const entry = this.#identities.get(podId);
483
+ if (!entry) throw new Error(`Unknown identity: ${podId}`);
484
+ const raw = await crypto.subtle.exportKey('raw', entry.identity.keyPair.publicKey);
485
+ return new Uint8Array(raw);
486
+ }
487
+
488
+ // -- DID support --------------------------------------------------------
489
+
490
+ /**
491
+ * Convert an identity's public key to a W3C did:key URI.
492
+ *
493
+ * Returns the proper W3C format `did:key:z<base58btc(0xed 0x01 + rawPubKey)>`
494
+ * when the raw Ed25519 public key was cached at create/import time. Falls
495
+ * back to the legacy `did:key:z<podId>` form if no raw key is cached
496
+ * (older in-memory identities loaded before this upgrade).
497
+ *
498
+ * @param {string} podId
499
+ * @returns {string}
500
+ */
501
+ toDID(podId) {
502
+ const entry = this.#identities.get(podId);
503
+ if (!entry) throw new Error(`Unknown identity: ${podId}`);
504
+ if (entry.rawPubKey) {
505
+ const prefixed = new Uint8Array(2 + entry.rawPubKey.length);
506
+ prefixed[0] = 0xed;
507
+ prefixed[1] = 0x01;
508
+ prefixed.set(entry.rawPubKey, 2);
509
+ return `did:key:z${base58btcEncode(prefixed)}`;
510
+ }
511
+ // Backward-compatibility: legacy form for entries without cached raw bytes
512
+ return `did:key:z${podId}`;
513
+ }
514
+
515
+ /**
516
+ * Legacy DID form, retained as a stable identifier alias.
517
+ *
518
+ * @param {string} podId
519
+ * @returns {string}
520
+ */
521
+ toLegacyDID(podId) {
522
+ if (!this.#identities.has(podId)) throw new Error(`Unknown identity: ${podId}`);
523
+ return `did:key:z${podId}`;
524
+ }
525
+
526
+ // -- Size ---------------------------------------------------------------
527
+
528
+ /** @returns {number} */
529
+ get size() {
530
+ return this.#identities.size;
531
+ }
532
+
533
+ // -- Persistence --------------------------------------------------------
534
+
535
+ /**
536
+ * Persist all identities to the storage adapter.
537
+ */
538
+ async save() {
539
+ for (const [podId, entry] of this.#identities) {
540
+ const jwk = await crypto.subtle.exportKey('jwk', entry.identity.keyPair.privateKey);
541
+ await this.#storage.save(podId, {
542
+ podId,
543
+ label: entry.label,
544
+ metadata: entry.metadata,
545
+ created: entry.created,
546
+ privateKeyJwk: jwk,
547
+ });
548
+ }
549
+ // Also persist the default and the list of ids
550
+ await this.#storage.save('__meta__', {
551
+ defaultId: this.#defaultId,
552
+ ids: [...this.#identities.keys()],
553
+ });
554
+ this.#onLog('identity:save', { count: this.#identities.size });
555
+ }
556
+
557
+ /**
558
+ * Load all identities from the storage adapter.
559
+ */
560
+ async load() {
561
+ const meta = await this.#storage.load('__meta__');
562
+ if (!meta || !Array.isArray(meta.ids)) return;
563
+
564
+ for (const podId of meta.ids) {
565
+ const data = await this.#storage.load(podId);
566
+ if (!data || !data.privateKeyJwk) continue;
567
+
568
+ try {
569
+ const privateKey = await crypto.subtle.importKey(
570
+ 'jwk',
571
+ data.privateKeyJwk,
572
+ { name: 'Ed25519' },
573
+ true,
574
+ ['sign']
575
+ );
576
+
577
+ const jwkPub = { ...data.privateKeyJwk };
578
+ delete jwkPub.d;
579
+ jwkPub.key_ops = ['verify'];
580
+ const publicKey = await crypto.subtle.importKey(
581
+ 'jwk',
582
+ jwkPub,
583
+ { name: 'Ed25519' },
584
+ true,
585
+ ['verify']
586
+ );
587
+
588
+ const keyPair = { publicKey, privateKey };
589
+ const identity = new PodIdentity({ keyPair, podId: data.podId });
590
+
591
+ this.#identities.set(data.podId, {
592
+ identity,
593
+ label: data.label,
594
+ metadata: data.metadata || {},
595
+ created: data.created,
596
+ });
597
+ } catch (err) {
598
+ this.#onLog('identity:load:error', { podId, error: err.message });
599
+ }
600
+ }
601
+
602
+ if (meta.defaultId && this.#identities.has(meta.defaultId)) {
603
+ this.#defaultId = meta.defaultId;
604
+ }
605
+ this.#onLog('identity:load', { count: this.#identities.size });
606
+ }
607
+
608
+ // -- Serialization (public-only) ----------------------------------------
609
+
610
+ /**
611
+ * Serialize all identities for JSON (no private keys).
612
+ *
613
+ * @returns {object}
614
+ */
615
+ toJSON() {
616
+ return {
617
+ defaultId: this.#defaultId,
618
+ identities: this.list(),
619
+ };
620
+ }
621
+
622
+ /**
623
+ * Get the internal PodIdentity object (for signing/bridge operations).
624
+ * @param {string} podId
625
+ * @returns {PodIdentity|null}
626
+ */
627
+ getIdentity(podId) {
628
+ const entry = this.#identities.get(podId);
629
+ return entry ? entry.identity : null;
630
+ }
631
+ }
632
+
633
+ // ---------------------------------------------------------------------------
634
+ // IndexedDBIdentityStorage
635
+ // ---------------------------------------------------------------------------
636
+
637
+ /**
638
+ * IndexedDB-backed identity storage adapter.
639
+ * Stores identity data in an "mesh-identities" object store with keyPath: podId.
640
+ * Falls back gracefully when IndexedDB is unavailable (test environments).
641
+ */
642
+ export class IndexedDBIdentityStorage {
643
+ /** @type {string} */
644
+ #dbName;
645
+
646
+ /** @type {IDBDatabase|null} */
647
+ #db = null;
648
+
649
+ /** @type {string} */
650
+ #storeName = 'identities';
651
+
652
+ /**
653
+ * @param {object} [opts]
654
+ * @param {string} [opts.dbName='mesh-identities'] - IndexedDB database name
655
+ */
656
+ constructor(opts = {}) {
657
+ this.#dbName = opts.dbName || 'mesh-identities';
658
+ }
659
+
660
+ /**
661
+ * Open the IndexedDB database.
662
+ * @returns {Promise<void>}
663
+ */
664
+ async open() {
665
+ if (this.#db) return;
666
+ if (typeof indexedDB === 'undefined') {
667
+ throw new Error('IndexedDB not available');
668
+ }
669
+
670
+ return new Promise((resolve, reject) => {
671
+ const request = indexedDB.open(this.#dbName, 1);
672
+
673
+ request.onupgradeneeded = (event) => {
674
+ const db = event.target.result;
675
+ if (!db.objectStoreNames.contains(this.#storeName)) {
676
+ db.createObjectStore(this.#storeName, { keyPath: 'podId' });
677
+ }
678
+ };
679
+
680
+ request.onsuccess = (event) => {
681
+ this.#db = event.target.result;
682
+ this.#db.onclose = () => { this.#db = null; };
683
+ resolve();
684
+ };
685
+
686
+ request.onerror = () => {
687
+ reject(new Error(`Failed to open IndexedDB "${this.#dbName}": ${request.error?.message}`));
688
+ };
689
+ });
690
+ }
691
+
692
+ /**
693
+ * @param {string} podId
694
+ * @param {*} data - Must include podId field
695
+ * @returns {Promise<void>}
696
+ */
697
+ async save(podId, data) {
698
+ if (!this.#db) await this.open();
699
+ const record = { ...data, podId };
700
+ return new Promise((resolve, reject) => {
701
+ const tx = this.#db.transaction(this.#storeName, 'readwrite');
702
+ const store = tx.objectStore(this.#storeName);
703
+ const req = store.put(record);
704
+ req.onsuccess = () => resolve();
705
+ req.onerror = () => reject(new Error(`Failed to save identity "${podId}": ${req.error?.message}`));
706
+ });
707
+ }
708
+
709
+ /**
710
+ * @param {string} podId
711
+ * @returns {Promise<*|null>}
712
+ */
713
+ async load(podId) {
714
+ if (!this.#db) await this.open();
715
+ return new Promise((resolve, reject) => {
716
+ const tx = this.#db.transaction(this.#storeName, 'readonly');
717
+ const store = tx.objectStore(this.#storeName);
718
+ const req = store.get(podId);
719
+ req.onsuccess = () => resolve(req.result || null);
720
+ req.onerror = () => reject(new Error(`Failed to load identity "${podId}": ${req.error?.message}`));
721
+ });
722
+ }
723
+
724
+ /**
725
+ * @param {string} podId
726
+ * @returns {Promise<boolean>}
727
+ */
728
+ async delete(podId) {
729
+ if (!this.#db) await this.open();
730
+ const existing = await this.load(podId);
731
+ if (!existing) return false;
732
+ return new Promise((resolve, reject) => {
733
+ const tx = this.#db.transaction(this.#storeName, 'readwrite');
734
+ const store = tx.objectStore(this.#storeName);
735
+ const req = store.delete(podId);
736
+ req.onsuccess = () => resolve(true);
737
+ req.onerror = () => reject(new Error(`Failed to delete identity "${podId}": ${req.error?.message}`));
738
+ });
739
+ }
740
+
741
+ /**
742
+ * @returns {Promise<string[]>} List of podIds
743
+ */
744
+ async list() {
745
+ if (!this.#db) await this.open();
746
+ return new Promise((resolve, reject) => {
747
+ const tx = this.#db.transaction(this.#storeName, 'readonly');
748
+ const store = tx.objectStore(this.#storeName);
749
+ const req = store.getAllKeys();
750
+ req.onsuccess = () => resolve(req.result || []);
751
+ req.onerror = () => reject(new Error(`Failed to list identities: ${req.error?.message}`));
752
+ });
753
+ }
754
+
755
+ /** @returns {Promise<void>} */
756
+ async clear() {
757
+ if (!this.#db) await this.open();
758
+ return new Promise((resolve, reject) => {
759
+ const tx = this.#db.transaction(this.#storeName, 'readwrite');
760
+ const store = tx.objectStore(this.#storeName);
761
+ const req = store.clear();
762
+ req.onsuccess = () => resolve();
763
+ req.onerror = () => reject(new Error(`Failed to clear identities: ${req.error?.message}`));
764
+ });
765
+ }
766
+
767
+ /** Close the database connection. */
768
+ close() {
769
+ if (this.#db) {
770
+ this.#db.close();
771
+ this.#db = null;
772
+ }
773
+ }
774
+ }
775
+
776
+ // ---------------------------------------------------------------------------
777
+ // VaultIdentityStorage
778
+ // ---------------------------------------------------------------------------
779
+
780
+ /**
781
+ * Wraps another identity storage with passphrase-based encryption.
782
+ * Only the privateKey field is encrypted; publicKey + metadata stored cleartext.
783
+ * Uses PBKDF2(310k, SHA-256) → AES-256-GCM.
784
+ */
785
+ export class VaultIdentityStorage {
786
+ /** @type {InMemoryIdentityStorage|IndexedDBIdentityStorage} */
787
+ #inner;
788
+
789
+ /** @type {Function} */
790
+ #getPassphrase;
791
+
792
+ /**
793
+ * @param {InMemoryIdentityStorage|IndexedDBIdentityStorage} inner - Inner storage adapter
794
+ * @param {object} opts
795
+ * @param {Function} opts.getPassphrase - Async function that returns the vault passphrase
796
+ */
797
+ constructor(inner, { getPassphrase }) {
798
+ if (!inner) throw new Error('inner storage is required');
799
+ if (typeof getPassphrase !== 'function') throw new Error('getPassphrase must be a function');
800
+ this.#inner = inner;
801
+ this.#getPassphrase = getPassphrase;
802
+ }
803
+
804
+ /**
805
+ * Save identity data, encrypting the privateKeyJwk field.
806
+ * @param {string} podId
807
+ * @param {*} data
808
+ * @returns {Promise<void>}
809
+ */
810
+ async save(podId, data) {
811
+ // Skip encryption for meta records
812
+ if (podId === '__meta__') {
813
+ return this.#inner.save(podId, data);
814
+ }
815
+
816
+ const passphrase = await this.#getPassphrase();
817
+ const record = { ...data };
818
+
819
+ if (record.privateKeyJwk) {
820
+ const enc = new TextEncoder();
821
+ const salt = crypto.getRandomValues(new Uint8Array(VAULT_SALT_BYTES));
822
+ const iv = crypto.getRandomValues(new Uint8Array(VAULT_IV_BYTES));
823
+
824
+ const baseKey = await crypto.subtle.importKey(
825
+ 'raw',
826
+ enc.encode(passphrase),
827
+ 'PBKDF2',
828
+ false,
829
+ ['deriveKey']
830
+ );
831
+
832
+ const aesKey = await crypto.subtle.deriveKey(
833
+ { name: 'PBKDF2', salt, iterations: VAULT_PBKDF2_ITERATIONS, hash: 'SHA-256' },
834
+ baseKey,
835
+ { name: 'AES-GCM', length: 256 },
836
+ false,
837
+ ['encrypt']
838
+ );
839
+
840
+ const ciphertext = new Uint8Array(
841
+ await crypto.subtle.encrypt(
842
+ { name: 'AES-GCM', iv },
843
+ aesKey,
844
+ enc.encode(JSON.stringify(record.privateKeyJwk))
845
+ )
846
+ );
847
+
848
+ record.privateKeyJwk = null;
849
+ record.encryptedPrivateKey = {
850
+ salt: encodeBase64url(salt),
851
+ iv: encodeBase64url(iv),
852
+ ciphertext: encodeBase64url(ciphertext),
853
+ };
854
+ }
855
+
856
+ return this.#inner.save(podId, record);
857
+ }
858
+
859
+ /**
860
+ * Load identity data, decrypting the privateKeyJwk field.
861
+ * @param {string} podId
862
+ * @returns {Promise<*|null>}
863
+ */
864
+ async load(podId) {
865
+ const record = await this.#inner.load(podId);
866
+ if (!record) return null;
867
+
868
+ // Skip decryption for meta records
869
+ if (podId === '__meta__') return record;
870
+
871
+ if (record.encryptedPrivateKey) {
872
+ const passphrase = await this.#getPassphrase();
873
+ const enc = new TextEncoder();
874
+ const { salt, iv, ciphertext } = record.encryptedPrivateKey;
875
+
876
+ const baseKey = await crypto.subtle.importKey(
877
+ 'raw',
878
+ enc.encode(passphrase),
879
+ 'PBKDF2',
880
+ false,
881
+ ['deriveKey']
882
+ );
883
+
884
+ const aesKey = await crypto.subtle.deriveKey(
885
+ { name: 'PBKDF2', salt: decodeBase64url(salt), iterations: VAULT_PBKDF2_ITERATIONS, hash: 'SHA-256' },
886
+ baseKey,
887
+ { name: 'AES-GCM', length: 256 },
888
+ false,
889
+ ['decrypt']
890
+ );
891
+
892
+ const plaintext = await crypto.subtle.decrypt(
893
+ { name: 'AES-GCM', iv: decodeBase64url(iv) },
894
+ aesKey,
895
+ decodeBase64url(ciphertext)
896
+ );
897
+
898
+ record.privateKeyJwk = JSON.parse(new TextDecoder().decode(plaintext));
899
+ delete record.encryptedPrivateKey;
900
+ }
901
+
902
+ return record;
903
+ }
904
+
905
+ /** @param {string} podId */
906
+ async delete(podId) {
907
+ return this.#inner.delete(podId);
908
+ }
909
+
910
+ /** @returns {Promise<string[]>} */
911
+ async list() {
912
+ return this.#inner.list();
913
+ }
914
+
915
+ /** @returns {Promise<void>} */
916
+ async clear() {
917
+ return this.#inner.clear();
918
+ }
919
+ }
920
+
921
+ // ---------------------------------------------------------------------------
922
+ // IdentitySyncCoordinator
923
+ // ---------------------------------------------------------------------------
924
+
925
+ /**
926
+ * Cross-tab identity coordination using BroadcastChannel.
927
+ * Prevents race conditions when multiple tabs create identities simultaneously.
928
+ */
929
+ export class IdentitySyncCoordinator {
930
+ /** @type {BroadcastChannel} */
931
+ #channel;
932
+
933
+ /** @type {Map<string, string>} podId -> our local tiebreaker token */
934
+ #pendingCreates = new Map();
935
+
936
+ /** @type {Function[]} */
937
+ #changeListeners = [];
938
+
939
+ /**
940
+ * @param {BroadcastChannel} [channel]
941
+ */
942
+ constructor(channel) {
943
+ this.#channel = channel || new BroadcastChannel('mesh-identity-sync');
944
+ this.#channel.onmessage = (event) => this.#handleMessage(event.data);
945
+ }
946
+
947
+ /**
948
+ * Attempt to acquire a "create lock" for a pod ID.
949
+ *
950
+ * Broadcasts intent and waits briefly for conflicts. Includes a
951
+ * tiebreaker token so two tabs racing to create the same podId
952
+ * resolve deterministically (lower token wins) — without it, both
953
+ * tabs would yield to the other and neither would acquire.
954
+ *
955
+ * @param {string} podId
956
+ * @returns {Promise<boolean>} true if lock acquired
957
+ */
958
+ async acquireCreateLock(podId) {
959
+ // Random token bound to this attempt. Lexicographic compare → lower wins.
960
+ const myToken = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
961
+ this.#pendingCreates.set(podId, myToken);
962
+ this.#channel.postMessage({ type: 'create-intent', podId, token: myToken });
963
+
964
+ // Wait 100ms for conflict signals
965
+ await new Promise(r => setTimeout(r, 100));
966
+
967
+ if (this.#pendingCreates.has(podId)) {
968
+ this.#pendingCreates.delete(podId);
969
+ return true;
970
+ }
971
+ return false;
972
+ }
973
+
974
+ /**
975
+ * Broadcast that an identity was created.
976
+ * @param {string} podId
977
+ */
978
+ broadcastCreated(podId) {
979
+ this.#channel.postMessage({ type: 'created', podId });
980
+ }
981
+
982
+ /**
983
+ * Broadcast that an identity was deleted.
984
+ * @param {string} podId
985
+ */
986
+ broadcastDeleted(podId) {
987
+ this.#channel.postMessage({ type: 'deleted', podId });
988
+ }
989
+
990
+ /**
991
+ * Register a callback for remote changes.
992
+ * @param {Function} cb - Receives { type, podId }
993
+ */
994
+ onRemoteChange(cb) {
995
+ this.#changeListeners.push(cb);
996
+ }
997
+
998
+ /** Close the broadcast channel. */
999
+ close() {
1000
+ this.#channel.close();
1001
+ }
1002
+
1003
+ /**
1004
+ * Handle incoming broadcast messages.
1005
+ * @param {object} msg
1006
+ */
1007
+ #handleMessage(msg) {
1008
+ if (!msg || !msg.type) return;
1009
+
1010
+ if (msg.type === 'create-intent') {
1011
+ // Two tabs racing for the same podId both broadcast intent. The
1012
+ // tab whose intent arrives FIRST at the other has its handler
1013
+ // fire when the other's pendingCreates is empty (no-op). Without
1014
+ // a response, the first tab never sees the second's intent.
1015
+ //
1016
+ // Resolution: when we see a conflicting intent, ALWAYS reply with
1017
+ // our own intent — this way both tabs eventually see each other,
1018
+ // and the deterministic token comparison resolves it identically
1019
+ // on both sides. Lower token wins.
1020
+ const myToken = this.#pendingCreates.get(msg.podId);
1021
+ if (myToken) {
1022
+ const theirToken = typeof msg.token === 'string' ? msg.token : '';
1023
+ if (theirToken && theirToken < myToken) {
1024
+ // We lose — yield.
1025
+ this.#pendingCreates.delete(msg.podId);
1026
+ } else if (msg._isResponse !== true) {
1027
+ // We win (or peer is on old code without a token). Respond
1028
+ // with our own intent so the peer can compare and yield.
1029
+ // The `_isResponse` flag prevents infinite ping-pong.
1030
+ this.#channel.postMessage({
1031
+ type: 'create-intent',
1032
+ podId: msg.podId,
1033
+ token: myToken,
1034
+ _isResponse: true,
1035
+ });
1036
+ }
1037
+ }
1038
+ }
1039
+
1040
+ if (msg.type === 'created' || msg.type === 'deleted') {
1041
+ for (const cb of this.#changeListeners) {
1042
+ try { cb(msg); } catch (e) { silentCatch('clawser-mesh-identity', 'swallow', e) }
1043
+ }
1044
+ }
1045
+ }
1046
+ }
1047
+
1048
+ // ---------------------------------------------------------------------------
1049
+ // AutoIdentityManager
1050
+ // ---------------------------------------------------------------------------
1051
+
1052
+ /**
1053
+ * Automatic identity lifecycle manager.
1054
+ * Boots from storage, ensures a default identity exists, and provides
1055
+ * identity switching with listener notifications.
1056
+ */
1057
+ export class AutoIdentityManager {
1058
+ /** @type {MeshIdentityManager} */
1059
+ #identityManager;
1060
+
1061
+ /** @type {InMemoryIdentityStorage|IndexedDBIdentityStorage|VaultIdentityStorage} */
1062
+ #storage;
1063
+
1064
+ /** @type {IdentitySyncCoordinator|null} */
1065
+ #syncCoordinator;
1066
+
1067
+ /** @type {string|null} */
1068
+ #activeId = null;
1069
+
1070
+ /** @type {Function[]} */
1071
+ #switchListeners = [];
1072
+
1073
+ /** @type {boolean} */
1074
+ #booted = false;
1075
+
1076
+ /**
1077
+ * @param {MeshIdentityManager} identityManager
1078
+ * @param {*} storage
1079
+ * @param {IdentitySyncCoordinator|null} [syncCoordinator]
1080
+ */
1081
+ constructor(identityManager, storage, syncCoordinator = null) {
1082
+ this.#identityManager = identityManager;
1083
+ this.#storage = storage;
1084
+ this.#syncCoordinator = syncCoordinator;
1085
+ }
1086
+
1087
+ /**
1088
+ * Boot the identity system for a workspace.
1089
+ * Loads from storage, creates a default if none exist.
1090
+ * @param {string} workspaceId
1091
+ * @returns {Promise<void>}
1092
+ */
1093
+ async boot(workspaceId) {
1094
+ // Load existing identities from storage
1095
+ await this.#identityManager.load();
1096
+
1097
+ // Create a default identity if none exist
1098
+ if (this.#identityManager.size === 0) {
1099
+ const summary = await this.#identityManager.create('default', {
1100
+ metadata: { workspaceId, autoCreated: true },
1101
+ });
1102
+ await this.#identityManager.save();
1103
+
1104
+ if (this.#syncCoordinator) {
1105
+ this.#syncCoordinator.broadcastCreated(summary.podId);
1106
+ }
1107
+ }
1108
+
1109
+ // Set active to the default identity
1110
+ const def = this.#identityManager.getDefault();
1111
+ if (def) {
1112
+ this.#activeId = def.podId;
1113
+ }
1114
+
1115
+ this.#booted = true;
1116
+ }
1117
+
1118
+ /**
1119
+ * Ensure an identity is available, creating one if needed.
1120
+ * @returns {Promise<PodIdentity|null>}
1121
+ */
1122
+ async ensureIdentity() {
1123
+ if (this.#activeId && this.#identityManager.has(this.#activeId)) {
1124
+ return this.#identityManager.getIdentity(this.#activeId);
1125
+ }
1126
+
1127
+ if (this.#identityManager.size === 0) {
1128
+ const summary = await this.#identityManager.create('default');
1129
+ await this.#identityManager.save();
1130
+ this.#activeId = summary.podId;
1131
+ }
1132
+
1133
+ const def = this.#identityManager.getDefault();
1134
+ if (def) {
1135
+ this.#activeId = def.podId;
1136
+ return this.#identityManager.getIdentity(def.podId);
1137
+ }
1138
+ return null;
1139
+ }
1140
+
1141
+ /**
1142
+ * Switch the active identity.
1143
+ * @param {string} podId
1144
+ */
1145
+ async switchIdentity(podId) {
1146
+ if (!this.#identityManager.has(podId)) {
1147
+ throw new Error(`Unknown identity: ${podId}`);
1148
+ }
1149
+ const oldId = this.#activeId;
1150
+ this.#activeId = podId;
1151
+ this.#identityManager.setDefault(podId);
1152
+
1153
+ for (const cb of this.#switchListeners) {
1154
+ try { cb({ oldId, newId: podId }); } catch (e) { silentCatch('clawser-mesh-identity', 'swallow', e) }
1155
+ }
1156
+ }
1157
+
1158
+ /**
1159
+ * Get the active identity summary (no private keys).
1160
+ * @returns {import('./identity.mjs').IdentitySummary|null}
1161
+ */
1162
+ getActive() {
1163
+ if (this.#activeId) {
1164
+ return this.#identityManager.get(this.#activeId);
1165
+ }
1166
+ return this.#identityManager.getDefault();
1167
+ }
1168
+
1169
+ /**
1170
+ * Get the active PodIdentity object (with keys).
1171
+ * @returns {PodIdentity|null}
1172
+ */
1173
+ getActiveIdentity() {
1174
+ if (this.#activeId) {
1175
+ return this.#identityManager.getIdentity(this.#activeId);
1176
+ }
1177
+ return null;
1178
+ }
1179
+
1180
+ /**
1181
+ * List all identities with active status.
1182
+ * @returns {Array<{podId: string, label: string, isActive: boolean}>}
1183
+ */
1184
+ listIdentities() {
1185
+ return this.#identityManager.list().map(s => ({
1186
+ podId: s.podId,
1187
+ label: s.label,
1188
+ isActive: s.podId === this.#activeId,
1189
+ }));
1190
+ }
1191
+
1192
+ /**
1193
+ * Register a listener for identity switches.
1194
+ * @param {Function} cb - Receives { oldId, newId }
1195
+ */
1196
+ onSwitch(cb) {
1197
+ this.#switchListeners.push(cb);
1198
+ }
1199
+
1200
+ /** @returns {boolean} */
1201
+ get booted() {
1202
+ return this.#booted;
1203
+ }
1204
+
1205
+ /** @returns {MeshIdentityManager} */
1206
+ get identityManager() {
1207
+ return this.#identityManager;
1208
+ }
1209
+
1210
+ /**
1211
+ * Serialize auto-manager state.
1212
+ * @returns {object}
1213
+ */
1214
+ toJSON() {
1215
+ return {
1216
+ activeId: this.#activeId,
1217
+ booted: this.#booted,
1218
+ };
1219
+ }
1220
+
1221
+ /**
1222
+ * Restore auto-manager state from serialized data.
1223
+ * @param {object} data
1224
+ */
1225
+ fromJSON(data) {
1226
+ if (data?.activeId) this.#activeId = data.activeId;
1227
+ if (data?.booted !== undefined) this.#booted = data.booted;
1228
+ }
1229
+ }
1230
+
1231
+ // ---------------------------------------------------------------------------
1232
+ // IdentitySelector
1233
+ // ---------------------------------------------------------------------------
1234
+
1235
+ /**
1236
+ * Per-peer/per-scope identity selection.
1237
+ * Resolves which identity to use when connecting to a specific peer.
1238
+ */
1239
+ export class IdentitySelector {
1240
+ /** @type {AutoIdentityManager} */
1241
+ #autoIdMgr;
1242
+
1243
+ /** @type {Map<string, string>} peerId -> podId */
1244
+ #peerRules = new Map();
1245
+
1246
+ /** @type {Map<string, string>} scope -> podId */
1247
+ #scopeRules = new Map();
1248
+
1249
+ /**
1250
+ * @param {AutoIdentityManager} autoIdentityManager
1251
+ */
1252
+ constructor(autoIdentityManager) {
1253
+ this.#autoIdMgr = autoIdentityManager;
1254
+ }
1255
+
1256
+ /**
1257
+ * Set a rule: use identity podId when connecting to peerId.
1258
+ * @param {string} peerId
1259
+ * @param {string} podId
1260
+ */
1261
+ setRule(peerId, podId) {
1262
+ this.#peerRules.set(peerId, podId);
1263
+ }
1264
+
1265
+ /**
1266
+ * Set a default rule for a scope.
1267
+ * @param {string} scope
1268
+ * @param {string} podId
1269
+ */
1270
+ setDefaultRule(scope, podId) {
1271
+ this.#scopeRules.set(scope, podId);
1272
+ }
1273
+
1274
+ /**
1275
+ * Remove a peer-specific rule.
1276
+ * @param {string} peerId
1277
+ * @returns {boolean}
1278
+ */
1279
+ removeRule(peerId) {
1280
+ return this.#peerRules.delete(peerId);
1281
+ }
1282
+
1283
+ /**
1284
+ * Resolve which identity to use for a given peer and scope.
1285
+ * Priority: peer rule > scope rule > active identity.
1286
+ * @param {string} peerId
1287
+ * @param {string} [scope]
1288
+ * @returns {PodIdentity|null}
1289
+ */
1290
+ resolve(peerId, scope) {
1291
+ // Check peer-specific rule
1292
+ const peerPodId = this.#peerRules.get(peerId);
1293
+ if (peerPodId) {
1294
+ const identity = this.#autoIdMgr.identityManager.getIdentity(peerPodId);
1295
+ if (identity) return identity;
1296
+ }
1297
+
1298
+ // Check scope rule
1299
+ if (scope) {
1300
+ const scopePodId = this.#scopeRules.get(scope);
1301
+ if (scopePodId) {
1302
+ const identity = this.#autoIdMgr.identityManager.getIdentity(scopePodId);
1303
+ if (identity) return identity;
1304
+ }
1305
+ }
1306
+
1307
+ // Fallback to active identity
1308
+ return this.#autoIdMgr.getActiveIdentity();
1309
+ }
1310
+
1311
+ /**
1312
+ * List all configured rules.
1313
+ * @returns {Array<{peerId?: string, scope?: string, podId: string}>}
1314
+ */
1315
+ listRules() {
1316
+ const rules = [];
1317
+ for (const [peerId, podId] of this.#peerRules) {
1318
+ rules.push({ peerId, podId });
1319
+ }
1320
+ for (const [scope, podId] of this.#scopeRules) {
1321
+ rules.push({ scope, podId });
1322
+ }
1323
+ return rules;
1324
+ }
1325
+
1326
+ /**
1327
+ * Serialize rules.
1328
+ * @returns {object}
1329
+ */
1330
+ toJSON() {
1331
+ return {
1332
+ peerRules: Object.fromEntries(this.#peerRules),
1333
+ scopeRules: Object.fromEntries(this.#scopeRules),
1334
+ };
1335
+ }
1336
+
1337
+ /**
1338
+ * Restore rules from serialized data.
1339
+ * @param {object} data
1340
+ */
1341
+ fromJSON(data) {
1342
+ if (data?.peerRules) {
1343
+ this.#peerRules = new Map(Object.entries(data.peerRules));
1344
+ }
1345
+ if (data?.scopeRules) {
1346
+ this.#scopeRules = new Map(Object.entries(data.scopeRules));
1347
+ }
1348
+ }
1349
+ }