@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,505 @@
1
+ /**
2
+ * clawser-identity-wallet.js -- High-level multi-identity wallet.
3
+ *
4
+ * Wraps MeshIdentityManager and IdentitySelector to provide a unified
5
+ * API for identity lifecycle, contact management, and access grants.
6
+ *
7
+ * No browser-only imports at module level.
8
+ *
9
+ * Run tests:
10
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-identity-wallet.test.mjs
11
+ */
12
+
13
+ // ---------------------------------------------------------------------------
14
+ // Contact shape
15
+ // ---------------------------------------------------------------------------
16
+
17
+ /**
18
+ * @typedef {object} Contact
19
+ * @property {string} publicKeyHex - Hex-encoded public key
20
+ * @property {string} label - Human-readable name
21
+ * @property {number} trustLevel - Trust in [0.0, 1.0]
22
+ * @property {number} addedAt - Unix timestamp (ms)
23
+ * @property {object} metadata - Arbitrary metadata
24
+ */
25
+
26
+ /**
27
+ * Create a fresh Contact object.
28
+ *
29
+ * @param {string} publicKeyHex
30
+ * @param {string} label
31
+ * @param {number} [trustLevel=0.5]
32
+ * @returns {Contact}
33
+ */
34
+ function createContact(publicKeyHex, label, trustLevel = 0.5) {
35
+ return {
36
+ publicKeyHex,
37
+ label,
38
+ trustLevel: Math.max(0, Math.min(1, trustLevel)),
39
+ addedAt: Date.now(),
40
+ metadata: {},
41
+ };
42
+ }
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // IdentityWallet
46
+ // ---------------------------------------------------------------------------
47
+
48
+ /**
49
+ * High-level wallet that combines identity management, per-peer identity
50
+ * selection, contact storage, and capability-based access grants.
51
+ */
52
+ export class IdentityWallet {
53
+ /** @type {import('./identity.mjs').MeshIdentityManager} */
54
+ #identityManager;
55
+
56
+ /** @type {import('./identity.mjs').IdentitySelector|null} */
57
+ #identitySelector;
58
+
59
+ /** @type {Map<string, Contact>} publicKeyHex → Contact */
60
+ #contacts = new Map();
61
+
62
+ /** @type {Map<string, string[]>} publicKeyHex → granted capability scopes */
63
+ #grants = new Map();
64
+
65
+ /** @type {Function} */
66
+ #onLog;
67
+
68
+ /**
69
+ * @param {object} opts
70
+ * @param {import('./identity.mjs').MeshIdentityManager} opts.identityManager
71
+ * @param {import('./identity.mjs').IdentitySelector} [opts.identitySelector]
72
+ * @param {Function} [opts.onLog]
73
+ */
74
+ constructor({ identityManager, identitySelector, onLog }) {
75
+ if (!identityManager) {
76
+ throw new Error('identityManager is required');
77
+ }
78
+ this.#identityManager = identityManager;
79
+ this.#identitySelector = identitySelector || null;
80
+ this.#onLog = onLog || (() => {});
81
+ }
82
+
83
+ // -----------------------------------------------------------------------
84
+ // Identity CRUD (delegates to identityManager)
85
+ // -----------------------------------------------------------------------
86
+
87
+ /**
88
+ * Create a new identity.
89
+ *
90
+ * @param {string} label
91
+ * @param {object} [opts]
92
+ * @returns {Promise<import('./identity.mjs').IdentitySummary>}
93
+ */
94
+ async createIdentity(label, opts) {
95
+ const summary = await this.#identityManager.create(label, opts);
96
+ this.#onLog('wallet:identity:create', { podId: summary.podId, label });
97
+ return summary;
98
+ }
99
+
100
+ /**
101
+ * Import an identity from an exported key (JWK).
102
+ *
103
+ * @param {object} exportedKey - JWK private key
104
+ * @param {string} label
105
+ * @param {object} [opts]
106
+ * @returns {Promise<import('./identity.mjs').IdentitySummary>}
107
+ */
108
+ async importIdentity(exportedKey, label, opts) {
109
+ const summary = await this.#identityManager.import(exportedKey, label, opts);
110
+ this.#onLog('wallet:identity:import', { podId: summary.podId, label });
111
+ return summary;
112
+ }
113
+
114
+ /**
115
+ * Export an identity as JWK, optionally encrypted with a passphrase.
116
+ *
117
+ * @param {string} podId
118
+ * @param {string} [passphrase]
119
+ * @returns {Promise<object>}
120
+ */
121
+ async exportIdentity(podId, passphrase) {
122
+ return this.#identityManager.export(podId, passphrase);
123
+ }
124
+
125
+ /**
126
+ * Delete an identity.
127
+ *
128
+ * @param {string} podId
129
+ * @returns {boolean}
130
+ */
131
+ deleteIdentity(podId) {
132
+ const deleted = this.#identityManager.delete(podId);
133
+ if (deleted) {
134
+ this.#onLog('wallet:identity:delete', { podId });
135
+ }
136
+ return deleted;
137
+ }
138
+
139
+ /**
140
+ * List all identity summaries.
141
+ *
142
+ * @returns {import('./identity.mjs').IdentitySummary[]}
143
+ */
144
+ listIdentities() {
145
+ return this.#identityManager.list();
146
+ }
147
+
148
+ /**
149
+ * Get a single identity summary.
150
+ *
151
+ * @param {string} podId
152
+ * @returns {import('./identity.mjs').IdentitySummary|null}
153
+ */
154
+ getIdentity(podId) {
155
+ return this.#identityManager.get(podId);
156
+ }
157
+
158
+ /**
159
+ * Get the default identity summary.
160
+ *
161
+ * @returns {import('./identity.mjs').IdentitySummary|null}
162
+ */
163
+ getDefault() {
164
+ return this.#identityManager.getDefault();
165
+ }
166
+
167
+ /**
168
+ * Set the default identity.
169
+ *
170
+ * @param {string} podId
171
+ */
172
+ setDefault(podId) {
173
+ this.#identityManager.setDefault(podId);
174
+ this.#onLog('wallet:identity:setDefault', { podId });
175
+ }
176
+
177
+ // -----------------------------------------------------------------------
178
+ // Per-peer identity selection (delegates to identitySelector)
179
+ // -----------------------------------------------------------------------
180
+
181
+ /**
182
+ * Resolve which identity to use for a given peer.
183
+ * Returns null if no selector is configured.
184
+ *
185
+ * @param {string} peerId
186
+ * @returns {import('./packages/mesh-primitives/src/index.mjs').PodIdentity|null}
187
+ */
188
+ selectForPeer(peerId) {
189
+ if (!this.#identitySelector) return null;
190
+ return this.#identitySelector.resolve(peerId);
191
+ }
192
+
193
+ /**
194
+ * Set a per-peer identity rule.
195
+ * Throws if no selector is configured.
196
+ *
197
+ * @param {string} peerId
198
+ * @param {string} podId
199
+ */
200
+ setIdentityForPeer(peerId, podId) {
201
+ if (!this.#identitySelector) {
202
+ throw new Error('No IdentitySelector configured');
203
+ }
204
+ this.#identitySelector.setRule(peerId, podId);
205
+ this.#onLog('wallet:selector:set', { peerId, podId });
206
+ }
207
+
208
+ /**
209
+ * Remove a per-peer identity rule.
210
+ * Returns false if no selector is configured.
211
+ *
212
+ * @param {string} peerId
213
+ * @returns {boolean}
214
+ */
215
+ removeIdentityForPeer(peerId) {
216
+ if (!this.#identitySelector) return false;
217
+ const removed = this.#identitySelector.removeRule(peerId);
218
+ if (removed) {
219
+ this.#onLog('wallet:selector:remove', { peerId });
220
+ }
221
+ return removed;
222
+ }
223
+
224
+ // -----------------------------------------------------------------------
225
+ // Contact management
226
+ // -----------------------------------------------------------------------
227
+
228
+ /**
229
+ * Add a contact by their public key hex.
230
+ *
231
+ * @param {string} publicKeyHex
232
+ * @param {string} label
233
+ * @param {number} [trustLevel=0.5]
234
+ * @returns {Contact}
235
+ */
236
+ addContact(publicKeyHex, label, trustLevel = 0.5) {
237
+ if (!publicKeyHex || typeof publicKeyHex !== 'string') {
238
+ throw new Error('publicKeyHex is required and must be a non-empty string');
239
+ }
240
+ if (!label || typeof label !== 'string') {
241
+ throw new Error('label is required and must be a non-empty string');
242
+ }
243
+ if (this.#contacts.has(publicKeyHex)) {
244
+ throw new Error(`Contact already exists: ${publicKeyHex.slice(0, 16)}...`);
245
+ }
246
+
247
+ const contact = createContact(publicKeyHex, label, trustLevel);
248
+ this.#contacts.set(publicKeyHex, contact);
249
+ this.#onLog('wallet:contact:add', { publicKeyHex: publicKeyHex.slice(0, 16), label });
250
+ return { ...contact };
251
+ }
252
+
253
+ /**
254
+ * Remove a contact and revoke all their access grants.
255
+ *
256
+ * @param {string} publicKeyHex
257
+ * @returns {boolean}
258
+ */
259
+ removeContact(publicKeyHex) {
260
+ const existed = this.#contacts.delete(publicKeyHex);
261
+ if (existed) {
262
+ this.#grants.delete(publicKeyHex);
263
+ this.#onLog('wallet:contact:remove', { publicKeyHex: publicKeyHex.slice(0, 16) });
264
+ }
265
+ return existed;
266
+ }
267
+
268
+ /**
269
+ * Get a contact by public key hex.
270
+ *
271
+ * @param {string} publicKeyHex
272
+ * @returns {Contact|null}
273
+ */
274
+ getContact(publicKeyHex) {
275
+ const contact = this.#contacts.get(publicKeyHex);
276
+ return contact ? { ...contact } : null;
277
+ }
278
+
279
+ /**
280
+ * List all contacts.
281
+ *
282
+ * @returns {Contact[]}
283
+ */
284
+ listContacts() {
285
+ return [...this.#contacts.values()].map(c => ({ ...c }));
286
+ }
287
+
288
+ /**
289
+ * Update a contact's mutable fields (label, trustLevel, metadata).
290
+ *
291
+ * @param {string} publicKeyHex
292
+ * @param {object} updates
293
+ * @param {string} [updates.label]
294
+ * @param {number} [updates.trustLevel]
295
+ * @param {object} [updates.metadata]
296
+ * @returns {Contact|null}
297
+ */
298
+ updateContact(publicKeyHex, updates) {
299
+ const contact = this.#contacts.get(publicKeyHex);
300
+ if (!contact) return null;
301
+
302
+ if (updates.label !== undefined) {
303
+ if (typeof updates.label !== 'string' || !updates.label) {
304
+ throw new Error('label must be a non-empty string');
305
+ }
306
+ contact.label = updates.label;
307
+ }
308
+ if (updates.trustLevel !== undefined) {
309
+ contact.trustLevel = Math.max(0, Math.min(1, updates.trustLevel));
310
+ }
311
+ if (updates.metadata !== undefined) {
312
+ contact.metadata = { ...contact.metadata, ...updates.metadata };
313
+ }
314
+
315
+ this.#onLog('wallet:contact:update', { publicKeyHex: publicKeyHex.slice(0, 16) });
316
+ return { ...contact };
317
+ }
318
+
319
+ // -----------------------------------------------------------------------
320
+ // Access grants
321
+ // -----------------------------------------------------------------------
322
+
323
+ /**
324
+ * Grant capability scopes to a contact.
325
+ * Capabilities are additive — duplicates are ignored.
326
+ *
327
+ * @param {string} contactPubKey
328
+ * @param {string[]} capabilities - Scope strings to grant
329
+ */
330
+ grantAccess(contactPubKey, capabilities) {
331
+ if (!this.#contacts.has(contactPubKey)) {
332
+ throw new Error('Contact not found — add the contact first');
333
+ }
334
+ if (!Array.isArray(capabilities) || capabilities.length === 0) {
335
+ throw new Error('capabilities must be a non-empty array of strings');
336
+ }
337
+
338
+ const existing = this.#grants.get(contactPubKey) || [];
339
+ const merged = [...new Set([...existing, ...capabilities])];
340
+ this.#grants.set(contactPubKey, merged);
341
+ this.#onLog('wallet:grant', {
342
+ publicKeyHex: contactPubKey.slice(0, 16),
343
+ capabilities,
344
+ });
345
+ }
346
+
347
+ /**
348
+ * Revoke specific capability scopes from a contact.
349
+ *
350
+ * @param {string} contactPubKey
351
+ * @param {string[]} capabilities - Scope strings to revoke
352
+ */
353
+ revokeAccess(contactPubKey, capabilities) {
354
+ if (!Array.isArray(capabilities) || capabilities.length === 0) {
355
+ throw new Error('capabilities must be a non-empty array of strings');
356
+ }
357
+
358
+ const existing = this.#grants.get(contactPubKey);
359
+ if (!existing) return;
360
+
361
+ const revoked = new Set(capabilities);
362
+ const remaining = existing.filter(c => !revoked.has(c));
363
+
364
+ if (remaining.length === 0) {
365
+ this.#grants.delete(contactPubKey);
366
+ } else {
367
+ this.#grants.set(contactPubKey, remaining);
368
+ }
369
+ this.#onLog('wallet:revoke', {
370
+ publicKeyHex: contactPubKey.slice(0, 16),
371
+ capabilities,
372
+ });
373
+ }
374
+
375
+ /**
376
+ * Get all granted capability scopes for a contact.
377
+ *
378
+ * @param {string} contactPubKey
379
+ * @returns {string[]}
380
+ */
381
+ getGrantedAccess(contactPubKey) {
382
+ return [...(this.#grants.get(contactPubKey) || [])];
383
+ }
384
+
385
+ // -----------------------------------------------------------------------
386
+ // Crypto operations (delegates to identityManager)
387
+ // -----------------------------------------------------------------------
388
+
389
+ /**
390
+ * Sign data with a specific identity.
391
+ *
392
+ * @param {string} podId
393
+ * @param {BufferSource} data
394
+ * @returns {Promise<Uint8Array>}
395
+ */
396
+ async sign(podId, data) {
397
+ return this.#identityManager.sign(podId, data);
398
+ }
399
+
400
+ /**
401
+ * Verify a signature against a public key (raw bytes).
402
+ *
403
+ * @param {Uint8Array} pubKeyBytes
404
+ * @param {BufferSource} data
405
+ * @param {BufferSource} sig
406
+ * @returns {Promise<boolean>}
407
+ */
408
+ async verify(pubKeyBytes, data, sig) {
409
+ return this.#identityManager.verify(pubKeyBytes, data, sig);
410
+ }
411
+
412
+ /**
413
+ * Get the raw public key bytes for an identity.
414
+ *
415
+ * @param {string} podId
416
+ * @returns {Promise<Uint8Array>}
417
+ */
418
+ async getPublicKeyBytes(podId) {
419
+ return this.#identityManager.getPublicKeyBytes(podId);
420
+ }
421
+
422
+ // -----------------------------------------------------------------------
423
+ // Persistence helpers
424
+ // -----------------------------------------------------------------------
425
+
426
+ /**
427
+ * Number of managed identities.
428
+ *
429
+ * @returns {number}
430
+ */
431
+ get size() {
432
+ return this.#identityManager.size;
433
+ }
434
+
435
+ /**
436
+ * Serialize wallet state (contacts, grants, selector rules).
437
+ * Identity data itself is serialized via the identity manager.
438
+ *
439
+ * @returns {object}
440
+ */
441
+ toJSON() {
442
+ const contacts = [];
443
+ for (const c of this.#contacts.values()) {
444
+ contacts.push({ ...c });
445
+ }
446
+
447
+ const grants = {};
448
+ for (const [key, caps] of this.#grants) {
449
+ grants[key] = [...caps];
450
+ }
451
+
452
+ return {
453
+ contacts,
454
+ grants,
455
+ identities: this.#identityManager.toJSON(),
456
+ selector: this.#identitySelector ? this.#identitySelector.toJSON() : null,
457
+ };
458
+ }
459
+
460
+ /**
461
+ * Restore wallet state from serialized data.
462
+ *
463
+ * @param {object} data - Output of toJSON()
464
+ * @param {import('./identity.mjs').MeshIdentityManager} identityManager
465
+ * @param {import('./identity.mjs').IdentitySelector} [identitySelector]
466
+ * @returns {IdentityWallet}
467
+ */
468
+ static fromJSON(data, identityManager, identitySelector) {
469
+ const wallet = new IdentityWallet({
470
+ identityManager,
471
+ identitySelector,
472
+ });
473
+
474
+ // Restore contacts
475
+ if (Array.isArray(data?.contacts)) {
476
+ for (const c of data.contacts) {
477
+ if (c.publicKeyHex) {
478
+ wallet.#contacts.set(c.publicKeyHex, {
479
+ publicKeyHex: c.publicKeyHex,
480
+ label: c.label || '',
481
+ trustLevel: typeof c.trustLevel === 'number' ? c.trustLevel : 0.5,
482
+ addedAt: c.addedAt || 0,
483
+ metadata: c.metadata || {},
484
+ });
485
+ }
486
+ }
487
+ }
488
+
489
+ // Restore grants
490
+ if (data?.grants && typeof data.grants === 'object') {
491
+ for (const [key, caps] of Object.entries(data.grants)) {
492
+ if (Array.isArray(caps)) {
493
+ wallet.#grants.set(key, [...caps]);
494
+ }
495
+ }
496
+ }
497
+
498
+ // Restore selector rules
499
+ if (identitySelector && data?.selector) {
500
+ identitySelector.fromJSON(data.selector);
501
+ }
502
+
503
+ return wallet;
504
+ }
505
+ }