@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,741 @@
1
+ /**
2
+ * clawser-mesh-keyring.js -- Key hierarchy and linking.
3
+ *
4
+ * Manages parent-child relationships between mesh identities
5
+ * (device, delegate, org, alias, recovery). Provides chain
6
+ * traversal, authority resolution, and expiration pruning.
7
+ *
8
+ * No browser-only imports at module level.
9
+ *
10
+ * Run tests:
11
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-keyring.test.mjs
12
+ */
13
+
14
+ import { encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives';
15
+
16
+ // Re-export for consumers
17
+ export { encodeBase64url, decodeBase64url };
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Constants
21
+ // ---------------------------------------------------------------------------
22
+
23
+ /** Valid relationship types between linked identities. */
24
+ export const VALID_RELATIONS = Object.freeze([
25
+ 'device', // Same person, different device
26
+ 'delegate', // Delegated authority
27
+ 'org', // Organization membership
28
+ 'alias', // Alternative identity
29
+ 'recovery', // Recovery key
30
+ ]);
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // KeyLink
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /**
37
+ * Represents a directed link between two identities.
38
+ *
39
+ * @class
40
+ */
41
+ export class KeyLink {
42
+ /**
43
+ * @param {object} opts
44
+ * @param {string} opts.parent - Parent identity pod ID
45
+ * @param {string} opts.child - Child identity pod ID
46
+ * @param {string} opts.relation - One of VALID_RELATIONS
47
+ * @param {string[]|null} [opts.scope] - Optional scope restrictions
48
+ * @param {number|null} [opts.expires] - Optional expiration timestamp (ms)
49
+ * @param {number} [opts.created] - Creation timestamp (ms)
50
+ */
51
+ constructor({ parent, child, relation, scope, expires, created }) {
52
+ /** @type {string} */
53
+ this.parent = parent;
54
+ /** @type {string} */
55
+ this.child = child;
56
+ /** @type {string} */
57
+ this.relation = relation;
58
+ /** @type {string[]|null} */
59
+ this.scope = scope || null;
60
+ /** @type {number|null} */
61
+ this.expires = expires ?? null;
62
+ /** @type {number} */
63
+ this.created = created || Date.now();
64
+ }
65
+
66
+ /**
67
+ * Check whether this link has expired.
68
+ *
69
+ * @param {number} [now=Date.now()]
70
+ * @returns {boolean}
71
+ */
72
+ isExpired(now = Date.now()) {
73
+ return this.expires !== null && now >= this.expires;
74
+ }
75
+
76
+ /**
77
+ * Serialize to a plain object.
78
+ *
79
+ * @returns {object}
80
+ */
81
+ toJSON() {
82
+ return {
83
+ parent: this.parent,
84
+ child: this.child,
85
+ relation: this.relation,
86
+ scope: this.scope,
87
+ expires: this.expires,
88
+ created: this.created,
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Deserialize from a plain object.
94
+ *
95
+ * @param {object} data
96
+ * @returns {KeyLink}
97
+ */
98
+ static fromJSON(data) {
99
+ return new KeyLink(data);
100
+ }
101
+ }
102
+
103
+ // ---------------------------------------------------------------------------
104
+ // SignedKeyLink
105
+ // ---------------------------------------------------------------------------
106
+
107
+ /**
108
+ * A KeyLink with cryptographic Ed25519 signatures from both parent and child.
109
+ * The signed payload is: `parent|child|relation|timestamp` encoded as UTF-8.
110
+ */
111
+ export class SignedKeyLink extends KeyLink {
112
+ /** @type {Uint8Array|null} */
113
+ parentSignature;
114
+
115
+ /** @type {Uint8Array|null} */
116
+ childSignature;
117
+
118
+ /**
119
+ * @param {object} opts - KeyLink fields + signatures
120
+ * @param {Uint8Array|null} [opts.parentSignature]
121
+ * @param {Uint8Array|null} [opts.childSignature]
122
+ */
123
+ constructor(opts) {
124
+ super(opts);
125
+ this.parentSignature = opts.parentSignature || null;
126
+ this.childSignature = opts.childSignature || null;
127
+ }
128
+
129
+ /**
130
+ * Get the canonical signed payload bytes.
131
+ * @returns {Uint8Array}
132
+ */
133
+ get signedPayload() {
134
+ const str = `${this.parent}|${this.child}|${this.relation}|${this.created}`;
135
+ return new TextEncoder().encode(str);
136
+ }
137
+
138
+ /**
139
+ * Create a signed link between two identities.
140
+ * Both parent and child sign the canonical payload.
141
+ *
142
+ * @param {import('./identity.mjs').PodIdentity} parentIdentity
143
+ * @param {import('./identity.mjs').PodIdentity} childIdentity
144
+ * @param {string} relation - One of VALID_RELATIONS
145
+ * @param {object} [opts]
146
+ * @param {string[]} [opts.scope]
147
+ * @param {number} [opts.expires]
148
+ * @returns {Promise<SignedKeyLink>}
149
+ */
150
+ static async create(parentIdentity, childIdentity, relation, opts = {}) {
151
+ const created = Date.now();
152
+ const link = new SignedKeyLink({
153
+ parent: parentIdentity.podId,
154
+ child: childIdentity.podId,
155
+ relation,
156
+ scope: opts.scope,
157
+ expires: opts.expires,
158
+ created,
159
+ });
160
+
161
+ const payload = link.signedPayload;
162
+ link.parentSignature = await parentIdentity.sign(payload);
163
+ link.childSignature = await childIdentity.sign(payload);
164
+
165
+ return link;
166
+ }
167
+
168
+ /**
169
+ * Verify the parent's signature.
170
+ * @param {CryptoKey} publicKey - Parent's Ed25519 public key
171
+ * @returns {Promise<boolean>}
172
+ */
173
+ async verifyParent(publicKey) {
174
+ if (!this.parentSignature) return false;
175
+ return crypto.subtle.verify(
176
+ 'Ed25519',
177
+ publicKey,
178
+ this.parentSignature,
179
+ this.signedPayload
180
+ );
181
+ }
182
+
183
+ /**
184
+ * Verify the child's signature.
185
+ * @param {CryptoKey} publicKey - Child's Ed25519 public key
186
+ * @returns {Promise<boolean>}
187
+ */
188
+ async verifyChild(publicKey) {
189
+ if (!this.childSignature) return false;
190
+ return crypto.subtle.verify(
191
+ 'Ed25519',
192
+ publicKey,
193
+ this.childSignature,
194
+ this.signedPayload
195
+ );
196
+ }
197
+
198
+ /**
199
+ * Verify both parent and child signatures.
200
+ * @param {CryptoKey} parentPub - Parent's Ed25519 public key
201
+ * @param {CryptoKey} childPub - Child's Ed25519 public key
202
+ * @returns {Promise<boolean>}
203
+ */
204
+ async verifyBoth(parentPub, childPub) {
205
+ const [parentOk, childOk] = await Promise.all([
206
+ this.verifyParent(parentPub),
207
+ this.verifyChild(childPub),
208
+ ]);
209
+ return parentOk && childOk;
210
+ }
211
+
212
+ /**
213
+ * Serialize to a plain object (signatures as base64url).
214
+ * @returns {object}
215
+ */
216
+ toJSON() {
217
+ return {
218
+ ...super.toJSON(),
219
+ parentSignature: this.parentSignature ? encodeBase64url(this.parentSignature) : null,
220
+ childSignature: this.childSignature ? encodeBase64url(this.childSignature) : null,
221
+ signed: true,
222
+ };
223
+ }
224
+
225
+ /**
226
+ * Deserialize from a plain object.
227
+ * @param {object} data
228
+ * @returns {SignedKeyLink}
229
+ */
230
+ static fromJSON(data) {
231
+ return new SignedKeyLink({
232
+ ...data,
233
+ parentSignature: data.parentSignature ? decodeBase64url(data.parentSignature) : null,
234
+ childSignature: data.childSignature ? decodeBase64url(data.childSignature) : null,
235
+ });
236
+ }
237
+ }
238
+
239
+ // ---------------------------------------------------------------------------
240
+ // SuccessionPolicy
241
+ // ---------------------------------------------------------------------------
242
+
243
+ /** Valid succession actions. */
244
+ const VALID_SUCCESSION_ACTIONS = ['transfer', 'revoke', 'notify'];
245
+
246
+ /**
247
+ * Defines a dead-man's-switch policy: if `primaryId` is inactive
248
+ * longer than `inactivityThresholdMs`, the chosen action fires.
249
+ *
250
+ * @class
251
+ */
252
+ export class SuccessionPolicy {
253
+ /**
254
+ * @param {object} opts
255
+ * @param {string} opts.primaryId - Identity that must remain active
256
+ * @param {string} opts.successorId - Identity that takes over
257
+ * @param {number} opts.inactivityThresholdMs - Inactivity window (ms)
258
+ * @param {'transfer'|'revoke'|'notify'} [opts.action='transfer']
259
+ * @param {number} [opts.createdAt]
260
+ */
261
+ constructor({ primaryId, successorId, inactivityThresholdMs, action = 'transfer', createdAt }) {
262
+ if (!primaryId) throw new Error('primaryId is required');
263
+ if (!successorId) throw new Error('successorId is required');
264
+ if (typeof inactivityThresholdMs !== 'number' || inactivityThresholdMs <= 0) {
265
+ throw new Error('inactivityThresholdMs must be a positive number');
266
+ }
267
+ if (!VALID_SUCCESSION_ACTIONS.includes(action)) {
268
+ throw new Error(
269
+ `Invalid action: ${action}. Must be one of: ${VALID_SUCCESSION_ACTIONS.join(', ')}`
270
+ );
271
+ }
272
+ this.primaryId = primaryId;
273
+ this.successorId = successorId;
274
+ this.inactivityThresholdMs = inactivityThresholdMs;
275
+ this.action = action;
276
+ this.createdAt = createdAt ?? Date.now();
277
+ }
278
+
279
+ /**
280
+ * Whether the switch is armed (primary has been inactive too long).
281
+ *
282
+ * @param {number} [now=Date.now()]
283
+ * @param {number|undefined} lastActive - Last activity timestamp
284
+ * @returns {boolean}
285
+ */
286
+ isArmed(now = Date.now(), lastActive) {
287
+ if (lastActive === undefined || lastActive === null) return true;
288
+ return (now - lastActive) >= this.inactivityThresholdMs;
289
+ }
290
+
291
+ /**
292
+ * Serialize to a plain object.
293
+ * @returns {object}
294
+ */
295
+ toJSON() {
296
+ return {
297
+ primaryId: this.primaryId,
298
+ successorId: this.successorId,
299
+ inactivityThresholdMs: this.inactivityThresholdMs,
300
+ action: this.action,
301
+ createdAt: this.createdAt,
302
+ };
303
+ }
304
+
305
+ /**
306
+ * Deserialize from a plain object.
307
+ * @param {object} data
308
+ * @returns {SuccessionPolicy}
309
+ */
310
+ static fromJSON(data) {
311
+ return new SuccessionPolicy(data);
312
+ }
313
+ }
314
+
315
+ // ---------------------------------------------------------------------------
316
+ // MeshKeyring
317
+ // ---------------------------------------------------------------------------
318
+
319
+ /**
320
+ * Manages a graph of KeyLink relationships between identities.
321
+ *
322
+ * @class
323
+ */
324
+ export class MeshKeyring {
325
+ /** @type {KeyLink[]} */
326
+ #links = [];
327
+
328
+ /** @type {*} */
329
+ #storage;
330
+
331
+ /** @type {Map<string, SuccessionPolicy>} primaryId -> policy */
332
+ #successions = new Map();
333
+
334
+ /** @type {Map<string, number>} podId -> lastActiveTimestamp */
335
+ #activityLog = new Map();
336
+
337
+ /**
338
+ * @param {object} [opts]
339
+ * @param {*} [opts.storage] - Optional persistence adapter
340
+ */
341
+ constructor(opts = {}) {
342
+ this.#storage = opts.storage || null;
343
+ }
344
+
345
+ // -- Link management ----------------------------------------------------
346
+
347
+ /**
348
+ * Create a link from parent to child with the given relation.
349
+ *
350
+ * @param {string} parentId - Parent identity pod ID
351
+ * @param {string} childId - Child identity pod ID
352
+ * @param {string} relation - One of VALID_RELATIONS
353
+ * @param {object} [opts]
354
+ * @param {string[]} [opts.scope] - Scope restrictions
355
+ * @param {number} [opts.expires] - Expiration timestamp (ms)
356
+ * @returns {KeyLink}
357
+ */
358
+ link(parentId, childId, relation, opts = {}) {
359
+ if (!VALID_RELATIONS.includes(relation)) {
360
+ throw new Error(
361
+ `Invalid relation: ${relation}. Must be one of: ${VALID_RELATIONS.join(', ')}`
362
+ );
363
+ }
364
+ if (parentId === childId) {
365
+ throw new Error('Cannot link identity to itself');
366
+ }
367
+ const existing = this.#links.find(
368
+ (l) => l.parent === parentId && l.child === childId
369
+ );
370
+ if (existing) {
371
+ throw new Error(`Link already exists: ${parentId} -> ${childId}`);
372
+ }
373
+
374
+ const link = new KeyLink({
375
+ parent: parentId,
376
+ child: childId,
377
+ relation,
378
+ scope: opts.scope,
379
+ expires: opts.expires,
380
+ });
381
+ this.#links.push(link);
382
+ return link;
383
+ }
384
+
385
+ /**
386
+ * Remove a link between parent and child.
387
+ *
388
+ * @param {string} parentId
389
+ * @param {string} childId
390
+ * @returns {boolean} true if a link was removed
391
+ */
392
+ unlink(parentId, childId) {
393
+ const idx = this.#links.findIndex(
394
+ (l) => l.parent === parentId && l.child === childId
395
+ );
396
+ if (idx === -1) return false;
397
+ this.#links.splice(idx, 1);
398
+ return true;
399
+ }
400
+
401
+ // -- Chain traversal ----------------------------------------------------
402
+
403
+ /**
404
+ * Walk up the link chain from `id` towards the root.
405
+ * Returns the ordered list of KeyLinks from child to root.
406
+ *
407
+ * @param {string} id - Starting identity pod ID
408
+ * @returns {KeyLink[]}
409
+ */
410
+ getChain(id) {
411
+ const chain = [];
412
+ let current = id;
413
+ const visited = new Set();
414
+ while (true) {
415
+ if (visited.has(current)) break; // cycle guard
416
+ visited.add(current);
417
+ const link = this.#links.find((l) => l.child === current);
418
+ if (!link) break;
419
+ chain.push(link);
420
+ current = link.parent;
421
+ }
422
+ return chain;
423
+ }
424
+
425
+ /**
426
+ * Get all direct children of an identity.
427
+ *
428
+ * @param {string} id
429
+ * @returns {KeyLink[]}
430
+ */
431
+ getChildren(id) {
432
+ return this.#links.filter((l) => l.parent === id);
433
+ }
434
+
435
+ /**
436
+ * Get the direct parent link of an identity (or null).
437
+ *
438
+ * @param {string} id
439
+ * @returns {KeyLink|null}
440
+ */
441
+ getParent(id) {
442
+ return this.#links.find((l) => l.child === id) || null;
443
+ }
444
+
445
+ /**
446
+ * Check whether `descendantId` is a descendant of `ancestorId`.
447
+ *
448
+ * @param {string} ancestorId
449
+ * @param {string} descendantId
450
+ * @returns {boolean}
451
+ */
452
+ isDescendant(ancestorId, descendantId) {
453
+ const chain = this.getChain(descendantId);
454
+ return chain.some((l) => l.parent === ancestorId);
455
+ }
456
+
457
+ /**
458
+ * Walk to the root of the chain and return the root identity ID.
459
+ *
460
+ * @param {string} id
461
+ * @returns {string} The root (ultimate authority) pod ID
462
+ */
463
+ resolveAuthority(id) {
464
+ const chain = this.getChain(id);
465
+ return chain.length > 0 ? chain[chain.length - 1].parent : id;
466
+ }
467
+
468
+ /**
469
+ * Verify a chain for expiration.
470
+ *
471
+ * @param {KeyLink[]} chain
472
+ * @param {number} [now=Date.now()]
473
+ * @returns {{ valid: boolean, depth: number, expired: KeyLink[] }}
474
+ */
475
+ verifyChain(chain, now = Date.now()) {
476
+ let valid = true;
477
+ const expired = [];
478
+ for (const link of chain) {
479
+ if (link.isExpired(now)) {
480
+ valid = false;
481
+ expired.push(link);
482
+ }
483
+ }
484
+ return { valid, depth: chain.length, expired };
485
+ }
486
+
487
+ // -- Signed link support ------------------------------------------------
488
+
489
+ /**
490
+ * Add a signed link after verifying its signatures.
491
+ *
492
+ * @param {SignedKeyLink} signedLink
493
+ * @param {CryptoKey} parentPub - Parent's Ed25519 public key
494
+ * @param {CryptoKey} childPub - Child's Ed25519 public key
495
+ * @returns {Promise<SignedKeyLink>}
496
+ */
497
+ async addVerifiedLink(signedLink, parentPub, childPub) {
498
+ if (!(signedLink instanceof SignedKeyLink)) {
499
+ throw new Error('Expected a SignedKeyLink instance');
500
+ }
501
+ if (!VALID_RELATIONS.includes(signedLink.relation)) {
502
+ throw new Error(`Invalid relation: ${signedLink.relation}`);
503
+ }
504
+ if (signedLink.parent === signedLink.child) {
505
+ throw new Error('Cannot link identity to itself');
506
+ }
507
+
508
+ const valid = await signedLink.verifyBoth(parentPub, childPub);
509
+ if (!valid) {
510
+ throw new Error('Signature verification failed');
511
+ }
512
+
513
+ const existing = this.#links.find(
514
+ (l) => l.parent === signedLink.parent && l.child === signedLink.child
515
+ );
516
+ if (existing) {
517
+ throw new Error(`Link already exists: ${signedLink.parent} -> ${signedLink.child}`);
518
+ }
519
+
520
+ this.#links.push(signedLink);
521
+ return signedLink;
522
+ }
523
+
524
+ /**
525
+ * Verify an entire chain cryptographically (signatures + expiration).
526
+ *
527
+ * @param {string} fromId - Starting identity (leaf)
528
+ * @param {string} toId - Target identity (root/ancestor)
529
+ * @param {Function} getPublicKey - async (podId) => CryptoKey
530
+ * @returns {Promise<{valid: boolean, chain: KeyLink[], brokenAt?: string}>}
531
+ */
532
+ async verifyCryptoChain(fromId, toId, getPublicKey) {
533
+ const chain = this.getChain(fromId);
534
+ const relevantChain = [];
535
+
536
+ // Walk chain until we reach toId
537
+ let found = false;
538
+ for (const link of chain) {
539
+ relevantChain.push(link);
540
+ if (link.parent === toId) {
541
+ found = true;
542
+ break;
543
+ }
544
+ }
545
+
546
+ if (!found) {
547
+ return { valid: false, chain: relevantChain, brokenAt: 'no-path' };
548
+ }
549
+
550
+ // Verify each link in the chain
551
+ for (const link of relevantChain) {
552
+ if (link.isExpired()) {
553
+ return { valid: false, chain: relevantChain, brokenAt: link.child };
554
+ }
555
+
556
+ if (link instanceof SignedKeyLink) {
557
+ try {
558
+ const parentPub = await getPublicKey(link.parent);
559
+ const childPub = await getPublicKey(link.child);
560
+ const ok = await link.verifyBoth(parentPub, childPub);
561
+ if (!ok) {
562
+ return { valid: false, chain: relevantChain, brokenAt: link.child };
563
+ }
564
+ } catch {
565
+ return { valid: false, chain: relevantChain, brokenAt: link.child };
566
+ }
567
+ }
568
+ }
569
+
570
+ return { valid: true, chain: relevantChain };
571
+ }
572
+
573
+ // -- Succession / Dead Man's Switch -------------------------------------
574
+
575
+ /**
576
+ * Register a succession policy for a primary identity.
577
+ *
578
+ * @param {string} primaryId - Identity that must remain active
579
+ * @param {string} successorId - Identity that takes over
580
+ * @param {number} thresholdMs - Inactivity threshold in milliseconds
581
+ * @param {'transfer'|'revoke'|'notify'} [action='transfer']
582
+ * @returns {SuccessionPolicy}
583
+ */
584
+ setSuccessor(primaryId, successorId, thresholdMs, action = 'transfer') {
585
+ const policy = new SuccessionPolicy({
586
+ primaryId,
587
+ successorId,
588
+ inactivityThresholdMs: thresholdMs,
589
+ action,
590
+ });
591
+ this.#successions.set(primaryId, policy);
592
+ return policy;
593
+ }
594
+
595
+ /**
596
+ * Remove a succession policy.
597
+ *
598
+ * @param {string} primaryId
599
+ * @returns {boolean} true if a policy was removed
600
+ */
601
+ removeSuccessor(primaryId) {
602
+ return this.#successions.delete(primaryId);
603
+ }
604
+
605
+ /**
606
+ * Record activity for a pod identity (resets the dead-man timer).
607
+ *
608
+ * @param {string} podId
609
+ */
610
+ recordActivity(podId) {
611
+ this.#activityLog.set(podId, Date.now());
612
+ }
613
+
614
+ /**
615
+ * Check all succession policies and return those that are armed.
616
+ *
617
+ * @param {number} [now=Date.now()]
618
+ * @returns {{ policy: SuccessionPolicy, lastActive: number|undefined }[]}
619
+ */
620
+ checkSuccession(now = Date.now()) {
621
+ const armed = [];
622
+ for (const policy of this.#successions.values()) {
623
+ const lastActive = this.#activityLog.get(policy.primaryId);
624
+ if (policy.isArmed(now, lastActive)) {
625
+ armed.push({ policy, lastActive });
626
+ }
627
+ }
628
+ return armed;
629
+ }
630
+
631
+ /**
632
+ * Execute a succession policy for the given primary identity.
633
+ *
634
+ * - **transfer**: re-links all children of primaryId to successorId,
635
+ * removes old links.
636
+ * - **revoke**: removes all child links of primaryId.
637
+ * - **notify**: returns a notification signal without modifying links.
638
+ *
639
+ * The policy is removed after execution.
640
+ *
641
+ * @param {string} primaryId
642
+ * @returns {{ action: string, primaryId: string, successorId: string, affected: number }}
643
+ */
644
+ executeSuccession(primaryId) {
645
+ const policy = this.#successions.get(primaryId);
646
+ if (!policy) {
647
+ throw new Error(`No succession policy for: ${primaryId}`);
648
+ }
649
+
650
+ const children = this.getChildren(primaryId);
651
+ let affected = 0;
652
+
653
+ if (policy.action === 'transfer') {
654
+ for (const child of children) {
655
+ this.unlink(primaryId, child.child);
656
+ // Only re-link if it won't create a self-link or duplicate
657
+ if (policy.successorId !== child.child) {
658
+ const existing = this.#links.find(
659
+ (l) => l.parent === policy.successorId && l.child === child.child
660
+ );
661
+ if (!existing) {
662
+ this.link(policy.successorId, child.child, child.relation, {
663
+ scope: child.scope || undefined,
664
+ expires: child.expires || undefined,
665
+ });
666
+ }
667
+ }
668
+ affected++;
669
+ }
670
+ } else if (policy.action === 'revoke') {
671
+ for (const child of children) {
672
+ this.unlink(primaryId, child.child);
673
+ affected++;
674
+ }
675
+ } else if (policy.action === 'notify') {
676
+ affected = children.length;
677
+ }
678
+
679
+ this.#successions.delete(primaryId);
680
+
681
+ return {
682
+ action: policy.action,
683
+ primaryId: policy.primaryId,
684
+ successorId: policy.successorId,
685
+ affected,
686
+ };
687
+ }
688
+
689
+ // -- Maintenance --------------------------------------------------------
690
+
691
+ /**
692
+ * Remove all expired links.
693
+ *
694
+ * @param {number} [now=Date.now()]
695
+ * @returns {number} Number of links pruned
696
+ */
697
+ pruneExpired(now = Date.now()) {
698
+ const before = this.#links.length;
699
+ this.#links = this.#links.filter((l) => !l.isExpired(now));
700
+ return before - this.#links.length;
701
+ }
702
+
703
+ /** @returns {number} */
704
+ get size() {
705
+ return this.#links.length;
706
+ }
707
+
708
+ /**
709
+ * Return a copy of all links.
710
+ *
711
+ * @returns {KeyLink[]}
712
+ */
713
+ listLinks() {
714
+ return [...this.#links];
715
+ }
716
+
717
+ // -- Serialization ------------------------------------------------------
718
+
719
+ /**
720
+ * Serialize all links.
721
+ *
722
+ * @returns {object[]}
723
+ */
724
+ toJSON() {
725
+ return this.#links.map((l) => l.toJSON());
726
+ }
727
+
728
+ /**
729
+ * Deserialize from an array of link data.
730
+ *
731
+ * @param {object[]} data
732
+ * @returns {MeshKeyring}
733
+ */
734
+ static fromJSON(data) {
735
+ const kr = new MeshKeyring();
736
+ for (const d of data) {
737
+ kr.#links.push(KeyLink.fromJSON(d));
738
+ }
739
+ return kr;
740
+ }
741
+ }