@johnhenry/browsermesh-core 0.9.0 → 0.11.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/src/keyring.mjs CHANGED
@@ -3,15 +3,17 @@
3
3
  *
4
4
  * Manages parent-child relationships between mesh identities
5
5
  * (device, delegate, org, alias, recovery). Provides chain
6
- * traversal, authority resolution, and expiration pruning.
6
+ * traversal, authority resolution, signed revocation and expiration
7
+ * pruning.
7
8
  *
8
9
  * No browser-only imports at module level.
9
10
  *
10
11
  * Run tests:
11
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-keyring.test.mjs
12
+ * node --import ./test/_setup-globals.mjs --test test/keyring.test.mjs
12
13
  */
13
14
 
14
15
  import { encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives';
16
+ import { domainPayload } from './canonical.mjs';
15
17
 
16
18
  // Re-export for consumers
17
19
  export { encodeBase64url, decodeBase64url };
@@ -29,6 +31,12 @@ export const VALID_RELATIONS = Object.freeze([
29
31
  'recovery', // Recovery key
30
32
  ]);
31
33
 
34
+ /** Domain prefix of the bytes a {@link SignedKeyLink} signs (version 3). */
35
+ export const KEYLINK_DOMAIN = 'browsermesh/keylink/v3\n';
36
+
37
+ /** Domain prefix of the bytes a {@link SignedKeyUnlink} signs. */
38
+ export const KEYUNLINK_DOMAIN = 'browsermesh/keyunlink/v2\n';
39
+
32
40
  // ---------------------------------------------------------------------------
33
41
  // KeyLink
34
42
  // ---------------------------------------------------------------------------
@@ -36,6 +44,9 @@ export const VALID_RELATIONS = Object.freeze([
36
44
  /**
37
45
  * Represents a directed link between two identities.
38
46
  *
47
+ * A bare `KeyLink` carries no signatures: it is a local assertion only.
48
+ * {@link MeshKeyring#verifyCryptoChain} refuses it by default.
49
+ *
39
50
  * @class
40
51
  */
41
52
  export class KeyLink {
@@ -47,8 +58,9 @@ export class KeyLink {
47
58
  * @param {string[]|null} [opts.scope] - Optional scope restrictions
48
59
  * @param {number|null} [opts.expires] - Optional expiration timestamp (ms)
49
60
  * @param {number} [opts.created] - Creation timestamp (ms)
61
+ * @param {string|null} [opts.namespace] - Keyring/context the link belongs to
50
62
  */
51
- constructor({ parent, child, relation, scope, expires, created }) {
63
+ constructor({ parent, child, relation, scope, expires, created, namespace }) {
52
64
  /** @type {string} */
53
65
  this.parent = parent;
54
66
  /** @type {string} */
@@ -61,6 +73,8 @@ export class KeyLink {
61
73
  this.expires = expires ?? null;
62
74
  /** @type {number} */
63
75
  this.created = created || Date.now();
76
+ /** @type {string|null} */
77
+ this.namespace = namespace ?? null;
64
78
  }
65
79
 
66
80
  /**
@@ -86,6 +100,7 @@ export class KeyLink {
86
100
  scope: this.scope,
87
101
  expires: this.expires,
88
102
  created: this.created,
103
+ namespace: this.namespace,
89
104
  };
90
105
  }
91
106
 
@@ -107,10 +122,17 @@ export class KeyLink {
107
122
  /**
108
123
  * A KeyLink with cryptographic Ed25519 signatures from both parent and child.
109
124
  *
110
- * The signed payload is canonical JSON over every asserted field —
111
- * `parent`, `child`, `relation`, `scope`, `expires` and `created` — so a
112
- * signature that verifies vouches for the delegation's limits, not just for
113
- * who linked to whom. See {@link SignedKeyLink#signedPayload}.
125
+ * Both parties sign `"browsermesh/keylink/v3\n" ‖ canonical(body)`, where
126
+ * `body` holds every asserted field — `parent`, `child`, `relation`,
127
+ * `scope`, `expires`, `created` and `namespace` — and `canonical` is JSON
128
+ * with sorted keys. See {@link SignedKeyLink#signedPayload}.
129
+ *
130
+ * Earlier payload versions:
131
+ * - v1 (`parent|child|relation|created`) is no longer accepted at all.
132
+ * - v2 (literal-order JSON with `v: 2`, no prefix, no namespace) verifies
133
+ * only when the caller opts in with `acceptLegacyV2: true`, and only for
134
+ * links with no namespace. New links are always signed with v3; re-sign
135
+ * old ones with {@link SignedKeyLink#resign}.
114
136
  */
115
137
  export class SignedKeyLink extends KeyLink {
116
138
  /** @type {Uint8Array|null} */
@@ -131,87 +153,67 @@ export class SignedKeyLink extends KeyLink {
131
153
  }
132
154
 
133
155
  /**
134
- * Get the canonical signed payload bytes.
156
+ * The canonical signed payload bytes (version 3).
135
157
  *
136
- * Version 2. Covers **every** field the link asserts, including `scope`
137
- * and `expires`. Version 1 (`parent|child|relation|created`) left those
138
- * two out, which meant a holder of a signed link could widen its scope
139
- * and push out its expiry without invalidating either signature — see
140
- * {@link legacySignedPayload}.
141
- *
142
- * JSON is used rather than a delimiter-joined string because `scope`
143
- * holds caller-supplied strings: `['a|b']` and `['a', 'b']` must not
144
- * canonicalise to the same bytes. Key order is fixed by the literal, so
145
- * the encoding is deterministic.
158
+ * `"browsermesh/keylink/v3\n"` followed by sorted-key canonical JSON of
159
+ * every field the link asserts. The prefix keeps a link signature from
160
+ * being replayed as any other signed browsermesh message; `namespace`
161
+ * keeps a link minted for one keyring from being valid in another.
146
162
  *
147
163
  * @returns {Uint8Array}
148
164
  */
149
165
  get signedPayload() {
150
- return new TextEncoder().encode(JSON.stringify({
151
- v: 2,
166
+ return domainPayload(KEYLINK_DOMAIN, {
152
167
  parent: this.parent,
153
168
  child: this.child,
154
169
  relation: this.relation,
155
170
  scope: this.scope,
156
171
  expires: this.expires,
157
172
  created: this.created,
158
- }));
173
+ namespace: this.namespace,
174
+ });
159
175
  }
160
176
 
161
177
  /**
162
- * The version-1 payload bytes, kept only so links signed before `scope`
163
- * and `expires` were covered still verify.
164
- *
165
- * A v1 signature is accepted **only** when the link carries no scope and
166
- * no expiry — i.e. when there is nothing v1 failed to cover. A link that
167
- * has either field must carry a v2 signature over it.
178
+ * The version-2 payload bytes (browsermesh-core 0.5–0.9), kept only so
179
+ * persisted links can be verified during a migration when the caller
180
+ * explicitly passes `acceptLegacyV2: true`. Never used for signing.
168
181
  *
169
182
  * @returns {Uint8Array}
170
183
  */
171
- get legacySignedPayload() {
172
- const str = `${this.parent}|${this.child}|${this.relation}|${this.created}`;
173
- return new TextEncoder().encode(str);
174
- }
175
-
176
- /**
177
- * True when a v1 signature may stand in for a v2 one: the link asserts
178
- * nothing that the v1 payload left unsigned.
179
- *
180
- * @returns {boolean}
181
- */
182
- get #legacyAcceptable() {
183
- return this.scope === null && this.expires === null;
184
+ get legacyV2SignedPayload() {
185
+ return new TextEncoder().encode(JSON.stringify({
186
+ v: 2,
187
+ parent: this.parent,
188
+ child: this.child,
189
+ relation: this.relation,
190
+ scope: this.scope,
191
+ expires: this.expires,
192
+ created: this.created,
193
+ }));
184
194
  }
185
195
 
186
196
  /**
187
- * Verify one signature against the canonical payload, falling back to the
188
- * legacy payload only for links with nothing outside its coverage.
197
+ * Verify one signature against the v3 payload, or — only when opted in
198
+ * and the link has no namespace (v2 could not bind one) — the v2 payload.
189
199
  *
190
200
  * @param {CryptoKey} publicKey
191
201
  * @param {Uint8Array|null} signature
202
+ * @param {{ acceptLegacyV2?: boolean }} [opts]
192
203
  * @returns {Promise<boolean>}
193
204
  */
194
- async #verifyOne(publicKey, signature) {
205
+ async #verifyOne(publicKey, signature, { acceptLegacyV2 = false } = {}) {
195
206
  if (!signature) return false;
196
- const current = await crypto.subtle.verify(
197
- 'Ed25519',
198
- publicKey,
199
- signature,
200
- this.signedPayload
201
- );
202
- if (current) return true;
203
- if (!this.#legacyAcceptable) return false;
204
- return crypto.subtle.verify(
205
- 'Ed25519',
206
- publicKey,
207
- signature,
208
- this.legacySignedPayload
209
- );
207
+ if (await crypto.subtle.verify('Ed25519', publicKey, signature, this.signedPayload)) {
208
+ return true;
209
+ }
210
+ if (!acceptLegacyV2 || this.namespace !== null) return false;
211
+ return crypto.subtle.verify('Ed25519', publicKey, signature, this.legacyV2SignedPayload);
210
212
  }
211
213
 
212
214
  /**
213
215
  * Create a signed link between two identities.
214
- * Both parent and child sign the canonical payload.
216
+ * Both parent and child sign the canonical v3 payload.
215
217
  *
216
218
  * @param {import('./identity.mjs').PodIdentity} parentIdentity
217
219
  * @param {import('./identity.mjs').PodIdentity} childIdentity
@@ -219,17 +221,19 @@ export class SignedKeyLink extends KeyLink {
219
221
  * @param {object} [opts]
220
222
  * @param {string[]} [opts.scope]
221
223
  * @param {number} [opts.expires]
224
+ * @param {string} [opts.namespace] - Keyring/context this link is valid in
225
+ * @param {number} [opts.created] - Creation timestamp (defaults to now)
222
226
  * @returns {Promise<SignedKeyLink>}
223
227
  */
224
228
  static async create(parentIdentity, childIdentity, relation, opts = {}) {
225
- const created = Date.now();
226
229
  const link = new SignedKeyLink({
227
230
  parent: parentIdentity.podId,
228
231
  child: childIdentity.podId,
229
232
  relation,
230
233
  scope: opts.scope,
231
234
  expires: opts.expires,
232
- created,
235
+ namespace: opts.namespace,
236
+ created: opts.created ?? Date.now(),
233
237
  });
234
238
 
235
239
  const payload = link.signedPayload;
@@ -239,34 +243,73 @@ export class SignedKeyLink extends KeyLink {
239
243
  return link;
240
244
  }
241
245
 
246
+ /**
247
+ * Re-sign this link's fields with the current (v3) payload, e.g. to
248
+ * migrate a persisted v2 link. Needs both private keys. `created` is kept;
249
+ * `namespace` may be set (a v2 link had none).
250
+ *
251
+ * @param {import('./identity.mjs').PodIdentity} parentIdentity
252
+ * @param {import('./identity.mjs').PodIdentity} childIdentity
253
+ * @param {{ namespace?: string|null }} [opts]
254
+ * @returns {Promise<SignedKeyLink>} A new link; this one is unchanged.
255
+ */
256
+ async resign(parentIdentity, childIdentity, opts = {}) {
257
+ if (parentIdentity.podId !== this.parent || childIdentity.podId !== this.child) {
258
+ throw new Error('resign() needs the identities of this link\'s parent and child');
259
+ }
260
+ return SignedKeyLink.create(parentIdentity, childIdentity, this.relation, {
261
+ scope: this.scope || undefined,
262
+ expires: this.expires ?? undefined,
263
+ namespace: 'namespace' in opts ? opts.namespace : this.namespace,
264
+ created: this.created,
265
+ });
266
+ }
267
+
268
+ /**
269
+ * Which payload version both signatures verify under: `3`, `2` (legacy,
270
+ * needs migration), or `null` (neither). Useful for migration tooling.
271
+ *
272
+ * @param {CryptoKey} parentPub
273
+ * @param {CryptoKey} childPub
274
+ * @returns {Promise<3|2|null>}
275
+ */
276
+ async signatureVersion(parentPub, childPub) {
277
+ if (await this.verifyBoth(parentPub, childPub)) return 3;
278
+ if (await this.verifyBoth(parentPub, childPub, { acceptLegacyV2: true })) return 2;
279
+ return null;
280
+ }
281
+
242
282
  /**
243
283
  * Verify the parent's signature.
244
284
  * @param {CryptoKey} publicKey - Parent's Ed25519 public key
285
+ * @param {{ acceptLegacyV2?: boolean }} [opts]
245
286
  * @returns {Promise<boolean>}
246
287
  */
247
- async verifyParent(publicKey) {
248
- return this.#verifyOne(publicKey, this.parentSignature);
288
+ async verifyParent(publicKey, opts) {
289
+ return this.#verifyOne(publicKey, this.parentSignature, opts);
249
290
  }
250
291
 
251
292
  /**
252
293
  * Verify the child's signature.
253
294
  * @param {CryptoKey} publicKey - Child's Ed25519 public key
295
+ * @param {{ acceptLegacyV2?: boolean }} [opts]
254
296
  * @returns {Promise<boolean>}
255
297
  */
256
- async verifyChild(publicKey) {
257
- return this.#verifyOne(publicKey, this.childSignature);
298
+ async verifyChild(publicKey, opts) {
299
+ return this.#verifyOne(publicKey, this.childSignature, opts);
258
300
  }
259
301
 
260
302
  /**
261
303
  * Verify both parent and child signatures.
262
304
  * @param {CryptoKey} parentPub - Parent's Ed25519 public key
263
305
  * @param {CryptoKey} childPub - Child's Ed25519 public key
306
+ * @param {{ acceptLegacyV2?: boolean }} [opts]
264
307
  * @returns {Promise<boolean>}
265
308
  */
266
- async verifyBoth(parentPub, childPub) {
309
+ async verifyBoth(parentPub, childPub, opts) {
267
310
  const [parentOk, childOk] = await Promise.all([
268
- this.verifyParent(parentPub),
269
- this.verifyChild(childPub),
311
+ this.verifyParent(parentPub, opts),
312
+ this.verifyChild(childPub, opts),
270
313
  ]);
271
314
  return parentOk && childOk;
272
315
  }
@@ -298,6 +341,185 @@ export class SignedKeyLink extends KeyLink {
298
341
  }
299
342
  }
300
343
 
344
+ // ---------------------------------------------------------------------------
345
+ // SignedKeyUnlink
346
+ // ---------------------------------------------------------------------------
347
+
348
+ /**
349
+ * A signed, transferable revocation of the `parent -> child` edge.
350
+ *
351
+ * The parent signs `"browsermesh/keyunlink/v2\n" ‖ canonical(body)` over
352
+ * `parent`, `child`, `namespace`, `created`, `reason` and `expires`.
353
+ * `expires` is REQUIRED (ms epoch): a revocation that cannot lapse is not
354
+ * supported, and v1 unlinks (no `expires`, domain `keyunlink/v1`) are no
355
+ * longer accepted anywhere. It revokes every
356
+ * link on that edge (in that namespace) created at or before `created`, so
357
+ * a re-link signed later by both parties is not affected, but replaying the
358
+ * old link is. Because authority flows down the chain, every descendant of
359
+ * `child` loses whatever authority it derived through the revoked edge.
360
+ *
361
+ * Unlike {@link MeshKeyring#unlink} (local only), an unlink can be relayed
362
+ * to peers and applied with {@link MeshKeyring#applyUnlink}.
363
+ */
364
+ export class SignedKeyUnlink {
365
+ /**
366
+ * @param {object} opts
367
+ * @param {string} opts.parent
368
+ * @param {string} opts.child
369
+ * @param {string|null} [opts.namespace]
370
+ * @param {number} [opts.created]
371
+ * @param {string|null} [opts.reason]
372
+ * @param {number|null} [opts.expires] - Optional expiry (ms epoch, same
373
+ * convention as `KeyLink#expires`), covered by the signature. After it
374
+ * the revocation is dropped by the keyring.
375
+ * @param {Uint8Array|null} [opts.signature]
376
+ */
377
+ constructor({ parent, child, namespace, created, reason, expires, signature }) {
378
+ if (!parent || !child) throw new Error('parent and child are required');
379
+ if (expires != null && !Number.isFinite(expires)) {
380
+ throw new TypeError('expires must be a finite number (ms epoch)');
381
+ }
382
+ this.expires = expires ?? null;
383
+ this.parent = parent;
384
+ this.child = child;
385
+ this.namespace = namespace ?? null;
386
+ this.created = created || Date.now();
387
+ this.reason = reason ?? null;
388
+ this.signature = signature || null;
389
+ }
390
+
391
+ /**
392
+ * Signed bytes: the `keyunlink/v2` domain plus canonical JSON of every
393
+ * field including `expires`. The v2 domain means a v1 signature can never
394
+ * validate here, and a v2 signature is not a valid v1 message.
395
+ *
396
+ * @returns {Uint8Array}
397
+ */
398
+ get signedPayload() {
399
+ return domainPayload(KEYUNLINK_DOMAIN, {
400
+ parent: this.parent,
401
+ child: this.child,
402
+ namespace: this.namespace,
403
+ created: this.created,
404
+ reason: this.reason,
405
+ expires: this.expires,
406
+ });
407
+ }
408
+
409
+ /**
410
+ * Whether this unlink's expiry has passed (`now >= expires`, as for links).
411
+ * @param {number} [now=Date.now()]
412
+ * @returns {boolean}
413
+ */
414
+ isExpired(now = Date.now()) {
415
+ return this.expires !== null && now >= this.expires;
416
+ }
417
+
418
+ /**
419
+ * Create an unlink signed by the parent.
420
+ *
421
+ * @param {import('./identity.mjs').PodIdentity} parentIdentity
422
+ * @param {string} childId
423
+ * @param {{ namespace?: string, reason?: string, created?: number, expires?: number }} [opts]
424
+ * @returns {Promise<SignedKeyUnlink>}
425
+ */
426
+ static async create(parentIdentity, childId, opts = {}) {
427
+ if (!Number.isFinite(opts.expires)) {
428
+ throw new TypeError('SignedKeyUnlink requires a signed expires (ms epoch)');
429
+ }
430
+ const unlink = new SignedKeyUnlink({
431
+ parent: parentIdentity.podId,
432
+ child: childId,
433
+ namespace: opts.namespace,
434
+ created: opts.created ?? Date.now(),
435
+ reason: opts.reason,
436
+ expires: opts.expires,
437
+ });
438
+ unlink.signature = await parentIdentity.sign(unlink.signedPayload);
439
+ return unlink;
440
+ }
441
+
442
+ /**
443
+ * Create an unlink for a known link: same child and namespace, and
444
+ * `expires` set to the link's expiry, so the revocation lives exactly as
445
+ * long as the link it revokes. A link that never expires needs an explicit
446
+ * `opts.expires` (throws otherwise). `opts` may also override `reason` and
447
+ * `created`.
448
+ *
449
+ * @param {import('./identity.mjs').PodIdentity} parentIdentity
450
+ * @param {KeyLink} link
451
+ * @param {{ reason?: string, created?: number, expires?: number }} [opts]
452
+ * @returns {Promise<SignedKeyUnlink>}
453
+ */
454
+ static async forLink(parentIdentity, link, opts = {}) {
455
+ if (link.parent !== parentIdentity.podId) {
456
+ throw new Error('Link was not issued by this parent');
457
+ }
458
+ return SignedKeyUnlink.create(parentIdentity, link.child, {
459
+ namespace: link.namespace ?? undefined,
460
+ reason: opts.reason,
461
+ created: Math.max(opts.created ?? Date.now(), link.created),
462
+ expires: opts.expires ?? link.expires ?? undefined,
463
+ });
464
+ }
465
+
466
+ /**
467
+ * Verify the parent's signature.
468
+ * @param {CryptoKey} parentPub
469
+ * @returns {Promise<boolean>}
470
+ */
471
+ async verify(parentPub) {
472
+ if (!this.signature || !Number.isFinite(this.expires)) return false;
473
+ return crypto.subtle.verify('Ed25519', parentPub, this.signature, this.signedPayload);
474
+ }
475
+
476
+ /**
477
+ * Why this unlink cannot be used, or null if it is well formed.
478
+ * @returns {string|null}
479
+ */
480
+ get defect() {
481
+ return Number.isFinite(this.expires) ? null : 'missing signed expires (v1 unlink)';
482
+ }
483
+
484
+ /**
485
+ * Whether this unlink revokes `link` (same edge and namespace, and the
486
+ * link was created at or before the unlink).
487
+ *
488
+ * @param {KeyLink} link
489
+ * @returns {boolean}
490
+ */
491
+ revokes(link) {
492
+ return link.parent === this.parent &&
493
+ link.child === this.child &&
494
+ (link.namespace ?? null) === this.namespace &&
495
+ link.created <= this.created;
496
+ }
497
+
498
+ toJSON() {
499
+ return {
500
+ type: 'unlink',
501
+ parent: this.parent,
502
+ child: this.child,
503
+ namespace: this.namespace,
504
+ created: this.created,
505
+ reason: this.reason,
506
+ expires: this.expires,
507
+ signature: this.signature ? encodeBase64url(this.signature) : null,
508
+ };
509
+ }
510
+
511
+ /**
512
+ * @param {object} data
513
+ * @returns {SignedKeyUnlink}
514
+ */
515
+ static fromJSON(data) {
516
+ return new SignedKeyUnlink({
517
+ ...data,
518
+ signature: data.signature ? decodeBase64url(data.signature) : null,
519
+ });
520
+ }
521
+ }
522
+
301
523
  // ---------------------------------------------------------------------------
302
524
  // SuccessionPolicy
303
525
  // ---------------------------------------------------------------------------
@@ -378,18 +600,57 @@ export class SuccessionPolicy {
378
600
  // MeshKeyring
379
601
  // ---------------------------------------------------------------------------
380
602
 
603
+ /**
604
+ * Whether `child` scope is no wider than `parent` scope (null = unrestricted).
605
+ * @param {string[]|null} parent
606
+ * @param {string[]|null} child
607
+ */
608
+ function scopeNarrows(parent, child) {
609
+ if (parent === null) return true;
610
+ if (child === null) return false;
611
+ return child.every((s) => parent.includes(s));
612
+ }
613
+
614
+ /**
615
+ * Whether `child` expiry is no later than `parent` expiry (null = never).
616
+ * @param {number|null} parent
617
+ * @param {number|null} child
618
+ */
619
+ function expiresNarrows(parent, child) {
620
+ if (parent === null) return true;
621
+ if (child === null) return false;
622
+ return child <= parent;
623
+ }
624
+
381
625
  /**
382
626
  * Manages a graph of KeyLink relationships between identities.
383
627
  *
628
+ * A keyring may be bound to a `namespace` (any string naming the context:
629
+ * an account, an app, a mesh). Signed links and unlinks carry the namespace
630
+ * inside their signature, and the keyring only accepts ones whose namespace
631
+ * equals its own (`null` matches only `null`), so a link issued for one
632
+ * keyring cannot be replayed into another.
633
+ *
384
634
  * @class
385
635
  */
386
636
  export class MeshKeyring {
387
637
  /** @type {KeyLink[]} */
388
638
  #links = [];
389
639
 
640
+ /** @type {SignedKeyUnlink[]} */
641
+ #revocations = [];
642
+ /** @type {{ data: object, reason: string }[]} */
643
+ #dropped = [];
644
+
390
645
  /** @type {*} */
391
646
  #storage;
392
647
 
648
+ /** @type {string|null} */
649
+ #namespace;
650
+
651
+ /** @type {boolean} */
652
+ #acceptLegacyV2;
653
+
393
654
  /** @type {Map<string, SuccessionPolicy>} primaryId -> policy */
394
655
  #successions = new Map();
395
656
 
@@ -399,15 +660,31 @@ export class MeshKeyring {
399
660
  /**
400
661
  * @param {object} [opts]
401
662
  * @param {*} [opts.storage] - Optional persistence adapter
663
+ * @param {string|null} [opts.namespace=null] - Context this keyring accepts links for
664
+ * @param {boolean} [opts.acceptLegacyV2=false] - Migration aid: also verify
665
+ * signatures over the pre-0.10 v2 payload (namespace-less links only).
666
+ * Off by default; turn it on only while re-signing persisted links.
402
667
  */
403
668
  constructor(opts = {}) {
404
669
  this.#storage = opts.storage || null;
670
+ this.#namespace = opts.namespace ?? null;
671
+ this.#acceptLegacyV2 = opts.acceptLegacyV2 === true;
672
+ }
673
+
674
+ /** The namespace this keyring accepts signed links and unlinks for. */
675
+ get namespace() {
676
+ return this.#namespace;
405
677
  }
406
678
 
407
679
  // -- Link management ----------------------------------------------------
408
680
 
409
681
  /**
410
- * Create a link from parent to child with the given relation.
682
+ * Create an **unsigned, local-only** link from parent to child.
683
+ *
684
+ * Unsigned links are useful for local bookkeeping but carry no proof:
685
+ * {@link MeshKeyring#verifyCryptoChain} refuses them unless called with
686
+ * `requireSigned: false`. Use {@link SignedKeyLink.create} plus
687
+ * {@link MeshKeyring#addVerifiedLink} for anything another party relies on.
411
688
  *
412
689
  * @param {string} parentId - Parent identity pod ID
413
690
  * @param {string} childId - Child identity pod ID
@@ -439,13 +716,17 @@ export class MeshKeyring {
439
716
  relation,
440
717
  scope: opts.scope,
441
718
  expires: opts.expires,
719
+ namespace: this.#namespace,
442
720
  });
443
721
  this.#links.push(link);
444
722
  return link;
445
723
  }
446
724
 
447
725
  /**
448
- * Remove a link between parent and child.
726
+ * Remove a link between parent and child. **Local only**: nothing is
727
+ * signed and peers are not told. To revoke a link in a way peers can
728
+ * verify and relay, create a {@link SignedKeyUnlink} and
729
+ * {@link MeshKeyring#applyUnlink} it.
449
730
  *
450
731
  * @param {string} parentId
451
732
  * @param {string} childId
@@ -460,6 +741,130 @@ export class MeshKeyring {
460
741
  return true;
461
742
  }
462
743
 
744
+ // -- Revocation ---------------------------------------------------------
745
+
746
+ /**
747
+ * Whether a recorded, unexpired {@link SignedKeyUnlink} revokes `link`.
748
+ * An expired revocation no longer counts. If it expires before the link
749
+ * does, the link is live again; give the unlink an `expires` at least as
750
+ * late as the link's ({@link SignedKeyUnlink.forLink}). A link that is
751
+ * itself expired stays unusable regardless (`verifyCryptoChain` checks it).
752
+ *
753
+ * @param {KeyLink} link
754
+ * @param {number} [now=Date.now()]
755
+ * @returns {boolean}
756
+ */
757
+ isRevoked(link, now = Date.now()) {
758
+ return this.#revocations.some((r) => !r.isExpired(now) && r.revokes(link));
759
+ }
760
+
761
+ /**
762
+ * Revocations `fromJSON` refused to restore (v1 / expiry-less or
763
+ * malformed), with the reason, so callers can log or re-request them.
764
+ *
765
+ * @returns {{ data: object, reason: string }[]}
766
+ */
767
+ get droppedRevocations() {
768
+ return [...this.#dropped];
769
+ }
770
+
771
+ /**
772
+ * Drop recorded revocations that have expired.
773
+ *
774
+ * @param {number} [now=Date.now()]
775
+ * @returns {number} How many were dropped
776
+ */
777
+ pruneRevocations(now = Date.now()) {
778
+ const before = this.#revocations.length;
779
+ this.#revocations = this.#revocations.filter((r) => !r.isExpired(now));
780
+ return before - this.#revocations.length;
781
+ }
782
+
783
+ /**
784
+ * Apply a signed revocation: verify the parent's signature, record it
785
+ * (so the revoked link cannot be re-added or verified later, even if it
786
+ * arrives after the unlink), and remove the edge.
787
+ *
788
+ * Cascades: every descendant of the child loses the authority it derived
789
+ * through the revoked edge — {@link MeshKeyring#verifyCryptoChain} from
790
+ * any of them to an ancestor above the edge fails. The descendants are
791
+ * returned so callers can react (re-enroll, notify).
792
+ *
793
+ * @param {SignedKeyUnlink} unlink
794
+ * @param {CryptoKey} parentPub - The unlink's parent's Ed25519 public key
795
+ * @returns {Promise<{ removed: boolean, descendants: string[] }>}
796
+ */
797
+ async applyUnlink(unlink, parentPub) {
798
+ if (!(unlink instanceof SignedKeyUnlink)) {
799
+ throw new Error('Expected a SignedKeyUnlink instance');
800
+ }
801
+ if (unlink.namespace !== this.#namespace) {
802
+ throw new Error(
803
+ `Namespace mismatch: unlink is for ${JSON.stringify(unlink.namespace)}, keyring is ${JSON.stringify(this.#namespace)}`
804
+ );
805
+ }
806
+ if (unlink.defect) throw new Error(`Unlink refused: ${unlink.defect}`);
807
+ let ok = false;
808
+ try {
809
+ ok = await unlink.verify(parentPub);
810
+ } catch {
811
+ ok = false;
812
+ }
813
+ if (!ok) throw new Error('Signature verification failed');
814
+
815
+ // Already expired: it no longer counts, so record and relay nothing.
816
+ if (unlink.isExpired()) return { removed: false, descendants: [] };
817
+
818
+ const descendants = this.#descendantsOf(unlink.child);
819
+
820
+ const same = (r) =>
821
+ r.parent === unlink.parent && r.child === unlink.child && r.created === unlink.created;
822
+ const idx = this.#revocations.findIndex(same);
823
+ if (idx < 0) {
824
+ this.#revocations.push(unlink);
825
+ } else {
826
+ // Same revocation, possibly with a different expiry: keep the longer-lived.
827
+ if (unlink.expires > this.#revocations[idx].expires) {
828
+ this.#revocations[idx] = unlink;
829
+ }
830
+ }
831
+
832
+ const before = this.#links.length;
833
+ this.#links = this.#links.filter((l) => !unlink.revokes(l));
834
+ return { removed: this.#links.length < before, descendants };
835
+ }
836
+
837
+ /**
838
+ * Recorded signed revocations that have not expired (copies of the list,
839
+ * same objects); expired ones are dropped from the keyring first. Relay
840
+ * these to peers so they can {@link MeshKeyring#applyUnlink} them.
841
+ *
842
+ * @param {{ now?: number }} [opts]
843
+ * @returns {SignedKeyUnlink[]}
844
+ */
845
+ listRevocations(opts = {}) {
846
+ this.pruneRevocations(opts.now ?? Date.now());
847
+ return [...this.#revocations];
848
+ }
849
+
850
+ /** @param {string} id @returns {string[]} */
851
+ #descendantsOf(id) {
852
+ const out = [];
853
+ const seen = new Set([id]);
854
+ const queue = [id];
855
+ while (queue.length) {
856
+ const cur = queue.shift();
857
+ for (const l of this.#links) {
858
+ if (l.parent === cur && !seen.has(l.child)) {
859
+ seen.add(l.child);
860
+ out.push(l.child);
861
+ queue.push(l.child);
862
+ }
863
+ }
864
+ }
865
+ return out;
866
+ }
867
+
463
868
  // -- Chain traversal ----------------------------------------------------
464
869
 
465
870
  /**
@@ -528,7 +933,8 @@ export class MeshKeyring {
528
933
  }
529
934
 
530
935
  /**
531
- * Verify a chain for expiration.
936
+ * Verify a chain for expiration (structure only, no signatures; see
937
+ * {@link MeshKeyring#verifyCryptoChain}).
532
938
  *
533
939
  * @param {KeyLink[]} chain
534
940
  * @param {number} [now=Date.now()]
@@ -549,7 +955,8 @@ export class MeshKeyring {
549
955
  // -- Signed link support ------------------------------------------------
550
956
 
551
957
  /**
552
- * Add a signed link after verifying its signatures.
958
+ * Add a signed link after verifying its signatures, its namespace and
959
+ * that no recorded unlink revokes it.
553
960
  *
554
961
  * @param {SignedKeyLink} signedLink
555
962
  * @param {CryptoKey} parentPub - Parent's Ed25519 public key
@@ -566,8 +973,18 @@ export class MeshKeyring {
566
973
  if (signedLink.parent === signedLink.child) {
567
974
  throw new Error('Cannot link identity to itself');
568
975
  }
976
+ if (signedLink.namespace !== this.#namespace) {
977
+ throw new Error(
978
+ `Namespace mismatch: link is for ${JSON.stringify(signedLink.namespace)}, keyring is ${JSON.stringify(this.#namespace)}`
979
+ );
980
+ }
981
+ if (this.isRevoked(signedLink)) {
982
+ throw new Error(`Link has been revoked: ${signedLink.parent} -> ${signedLink.child}`);
983
+ }
569
984
 
570
- const valid = await signedLink.verifyBoth(parentPub, childPub);
985
+ const valid = await signedLink.verifyBoth(parentPub, childPub, {
986
+ acceptLegacyV2: this.#acceptLegacyV2,
987
+ });
571
988
  if (!valid) {
572
989
  throw new Error('Signature verification failed');
573
990
  }
@@ -584,14 +1001,30 @@ export class MeshKeyring {
584
1001
  }
585
1002
 
586
1003
  /**
587
- * Verify an entire chain cryptographically (signatures + expiration).
1004
+ * Verify an entire chain cryptographically: every link on the path from
1005
+ * `fromId` up to `toId` must be signed by both ends, unexpired, in this
1006
+ * keyring's namespace, and not revoked by a recorded {@link SignedKeyUnlink}.
1007
+ *
1008
+ * On failure, `brokenAt` is the child ID of the offending link (or
1009
+ * `'no-path'`) and `reason` is one of `'no-path'`, `'expired'`,
1010
+ * `'revoked'`, `'namespace'`, `'unsigned'` or `'bad-signature'`.
588
1011
  *
589
1012
  * @param {string} fromId - Starting identity (leaf)
590
1013
  * @param {string} toId - Target identity (root/ancestor)
591
1014
  * @param {Function} getPublicKey - async (podId) => CryptoKey
592
- * @returns {Promise<{valid: boolean, chain: KeyLink[], brokenAt?: string}>}
1015
+ * @param {object} [opts]
1016
+ * @param {boolean} [opts.requireSigned=true] - Refuse unsigned KeyLinks.
1017
+ * `false` restores the pre-0.10 behaviour of skipping them; only for
1018
+ * purely local graphs.
1019
+ * @param {boolean} [opts.acceptLegacyV2] - Defaults to the keyring's setting
1020
+ * @param {number} [opts.now=Date.now()]
1021
+ * @returns {Promise<{valid: boolean, chain: KeyLink[], brokenAt?: string, reason?: string}>}
593
1022
  */
594
- async verifyCryptoChain(fromId, toId, getPublicKey) {
1023
+ async verifyCryptoChain(fromId, toId, getPublicKey, opts = {}) {
1024
+ const requireSigned = opts.requireSigned ?? true;
1025
+ const acceptLegacyV2 = opts.acceptLegacyV2 ?? this.#acceptLegacyV2;
1026
+ const now = opts.now ?? Date.now();
1027
+
595
1028
  const chain = this.getChain(fromId);
596
1029
  const relevantChain = [];
597
1030
 
@@ -606,26 +1039,28 @@ export class MeshKeyring {
606
1039
  }
607
1040
 
608
1041
  if (!found) {
609
- return { valid: false, chain: relevantChain, brokenAt: 'no-path' };
1042
+ return { valid: false, chain: relevantChain, brokenAt: 'no-path', reason: 'no-path' };
610
1043
  }
611
1044
 
612
- // Verify each link in the chain
1045
+ const fail = (link, reason) => ({ valid: false, chain: relevantChain, brokenAt: link.child, reason });
1046
+
613
1047
  for (const link of relevantChain) {
614
- if (link.isExpired()) {
615
- return { valid: false, chain: relevantChain, brokenAt: link.child };
1048
+ if (link.isExpired(now)) return fail(link, 'expired');
1049
+ if (this.isRevoked(link, now)) return fail(link, 'revoked');
1050
+ if ((link.namespace ?? null) !== this.#namespace) return fail(link, 'namespace');
1051
+
1052
+ if (!(link instanceof SignedKeyLink)) {
1053
+ if (requireSigned) return fail(link, 'unsigned');
1054
+ continue;
616
1055
  }
617
1056
 
618
- if (link instanceof SignedKeyLink) {
619
- try {
620
- const parentPub = await getPublicKey(link.parent);
621
- const childPub = await getPublicKey(link.child);
622
- const ok = await link.verifyBoth(parentPub, childPub);
623
- if (!ok) {
624
- return { valid: false, chain: relevantChain, brokenAt: link.child };
625
- }
626
- } catch {
627
- return { valid: false, chain: relevantChain, brokenAt: link.child };
628
- }
1057
+ try {
1058
+ const parentPub = await getPublicKey(link.parent);
1059
+ const childPub = await getPublicKey(link.child);
1060
+ const ok = await link.verifyBoth(parentPub, childPub, { acceptLegacyV2 });
1061
+ if (!ok) return fail(link, 'bad-signature');
1062
+ } catch {
1063
+ return fail(link, 'bad-signature');
629
1064
  }
630
1065
  }
631
1066
 
@@ -637,6 +1072,9 @@ export class MeshKeyring {
637
1072
  /**
638
1073
  * Register a succession policy for a primary identity.
639
1074
  *
1075
+ * The policy and the activity log are **local state**: nothing about them
1076
+ * is signed. They decide when this keyring acts, not what peers accept.
1077
+ *
640
1078
  * @param {string} primaryId - Identity that must remain active
641
1079
  * @param {string} successorId - Identity that takes over
642
1080
  * @param {number} thresholdMs - Inactivity threshold in milliseconds
@@ -693,17 +1131,30 @@ export class MeshKeyring {
693
1131
  /**
694
1132
  * Execute a succession policy for the given primary identity.
695
1133
  *
696
- * - **transfer**: re-links all children of primaryId to successorId,
697
- * removes old links.
698
- * - **revoke**: removes all child links of primaryId.
1134
+ * - **transfer**: moves every child of `primaryId` under `successorId`.
1135
+ * The keyring cannot sign on anyone's behalf, so the caller supplies
1136
+ * `opts.links`: one {@link SignedKeyLink} per child, signed by the
1137
+ * successor (as parent) and the child, with the same relation and a
1138
+ * scope/expiry no wider than the link it replaces, in this keyring's
1139
+ * namespace. They are all verified (via `opts.getPublicKey`) before
1140
+ * anything changes; if any is missing or invalid, the call rejects and
1141
+ * the keyring is untouched. Pass `{ localOnly: true }` instead to get
1142
+ * the pre-0.10 behaviour of re-linking with **unsigned** local links,
1143
+ * which `verifyCryptoChain` refuses by default.
1144
+ * - **revoke**: removes all child links of primaryId (locally; to tell
1145
+ * peers, distribute {@link SignedKeyUnlink}s signed by the primary).
699
1146
  * - **notify**: returns a notification signal without modifying links.
700
1147
  *
701
- * The policy is removed after execution.
1148
+ * The policy is removed after successful execution.
702
1149
  *
703
1150
  * @param {string} primaryId
704
- * @returns {{ action: string, primaryId: string, successorId: string, affected: number }}
1151
+ * @param {object} [opts]
1152
+ * @param {SignedKeyLink[]} [opts.links] - Successor-signed replacement links (transfer)
1153
+ * @param {Function} [opts.getPublicKey] - async (podId) => CryptoKey (transfer)
1154
+ * @param {boolean} [opts.localOnly=false] - transfer with unsigned local links
1155
+ * @returns {Promise<{ action: string, primaryId: string, successorId: string, affected: number }>}
705
1156
  */
706
- executeSuccession(primaryId) {
1157
+ async executeSuccession(primaryId, opts = {}) {
707
1158
  const policy = this.#successions.get(primaryId);
708
1159
  if (!policy) {
709
1160
  throw new Error(`No succession policy for: ${primaryId}`);
@@ -713,21 +1164,84 @@ export class MeshKeyring {
713
1164
  let affected = 0;
714
1165
 
715
1166
  if (policy.action === 'transfer') {
716
- for (const child of children) {
717
- this.unlink(primaryId, child.child);
718
- // Only re-link if it won't create a self-link or duplicate
719
- if (policy.successorId !== child.child) {
720
- const existing = this.#links.find(
721
- (l) => l.parent === policy.successorId && l.child === child.child
1167
+ const successorId = policy.successorId;
1168
+ if (opts.localOnly === true) {
1169
+ for (const child of children) {
1170
+ this.unlink(primaryId, child.child);
1171
+ if (successorId !== child.child) {
1172
+ const existing = this.#links.find(
1173
+ (l) => l.parent === successorId && l.child === child.child
1174
+ );
1175
+ if (!existing) {
1176
+ this.link(successorId, child.child, child.relation, {
1177
+ scope: child.scope || undefined,
1178
+ expires: child.expires ?? undefined,
1179
+ });
1180
+ }
1181
+ }
1182
+ affected++;
1183
+ }
1184
+ } else {
1185
+ const supplied = opts.links || [];
1186
+ const plan = [];
1187
+ for (const child of children) {
1188
+ if (child.child === successorId) {
1189
+ plan.push({ child, replacement: null });
1190
+ continue;
1191
+ }
1192
+ const alreadyLinked = this.#links.some(
1193
+ (l) => l.parent === successorId && l.child === child.child
722
1194
  );
723
- if (!existing) {
724
- this.link(policy.successorId, child.child, child.relation, {
725
- scope: child.scope || undefined,
726
- expires: child.expires || undefined,
727
- });
1195
+ if (alreadyLinked) {
1196
+ plan.push({ child, replacement: null });
1197
+ continue;
1198
+ }
1199
+ const replacement = supplied.find(
1200
+ (l) => l && l.parent === successorId && l.child === child.child
1201
+ );
1202
+ if (!(replacement instanceof SignedKeyLink)) {
1203
+ throw new Error(
1204
+ `transfer needs a SignedKeyLink ${successorId} -> ${child.child} signed by both (or pass localOnly: true)`
1205
+ );
1206
+ }
1207
+ if (replacement.relation !== child.relation) {
1208
+ throw new Error(`Replacement link for ${child.child} changes relation`);
1209
+ }
1210
+ if (!scopeNarrows(child.scope, replacement.scope) ||
1211
+ !expiresNarrows(child.expires, replacement.expires)) {
1212
+ throw new Error(`Replacement link for ${child.child} is wider than the link it replaces`);
1213
+ }
1214
+ if (replacement.namespace !== this.#namespace) {
1215
+ throw new Error(`Replacement link for ${child.child} has the wrong namespace`);
1216
+ }
1217
+ if (this.isRevoked(replacement)) {
1218
+ throw new Error(`Replacement link for ${child.child} has been revoked`);
1219
+ }
1220
+ if (typeof opts.getPublicKey !== 'function') {
1221
+ throw new Error('transfer needs opts.getPublicKey to verify replacement links');
728
1222
  }
1223
+ let ok = false;
1224
+ try {
1225
+ ok = await replacement.verifyBoth(
1226
+ await opts.getPublicKey(replacement.parent),
1227
+ await opts.getPublicKey(replacement.child),
1228
+ { acceptLegacyV2: this.#acceptLegacyV2 }
1229
+ );
1230
+ } catch {
1231
+ ok = false;
1232
+ }
1233
+ if (!ok) {
1234
+ throw new Error(`Replacement link for ${child.child}: signature verification failed`);
1235
+ }
1236
+ plan.push({ child, replacement });
1237
+ }
1238
+
1239
+ // Every replacement verified: now mutate.
1240
+ for (const { child, replacement } of plan) {
1241
+ this.unlink(primaryId, child.child);
1242
+ if (replacement) this.#links.push(replacement);
1243
+ affected++;
729
1244
  }
730
- affected++;
731
1245
  }
732
1246
  } else if (policy.action === 'revoke') {
733
1247
  for (const child of children) {
@@ -779,34 +1293,53 @@ export class MeshKeyring {
779
1293
  // -- Serialization ------------------------------------------------------
780
1294
 
781
1295
  /**
782
- * Serialize all links.
1296
+ * Serialize the keyring.
1297
+ *
1298
+ * Shape (since 0.10): `{ v: 3, namespace, links, revocations }`. Before
1299
+ * 0.10 this was a bare array of links; {@link MeshKeyring.fromJSON} still
1300
+ * reads that. An older browsermesh-core given the new object fails to
1301
+ * load it (it is not iterable) rather than misreading revocations as links.
783
1302
  *
784
- * @returns {object[]}
1303
+ * @returns {{ v: 3, namespace: string|null, links: object[], revocations: object[] }}
785
1304
  */
786
1305
  toJSON() {
787
- return this.#links.map((l) => l.toJSON());
1306
+ return {
1307
+ v: 3,
1308
+ namespace: this.#namespace,
1309
+ links: this.#links.map((l) => l.toJSON()),
1310
+ revocations: this.listRevocations().map((r) => r.toJSON()),
1311
+ };
788
1312
  }
789
1313
 
790
1314
  /**
791
- * Deserialize from an array of link data.
1315
+ * Deserialize a keyring.
792
1316
  *
793
- * @param {object[]} data
1317
+ * Accepts the current object form and the pre-0.10 bare array of links.
1318
+ * Signatures are not re-checked here (no keys are available); they are
1319
+ * checked by {@link MeshKeyring#verifyCryptoChain}. Recorded revocations
1320
+ * are restored as-is: a revocation can only remove authority, so trusting
1321
+ * the local copy fails closed.
1322
+ *
1323
+ * @param {object|object[]} data
1324
+ * @param {object} [opts] - Constructor options (`storage`, `namespace`,
1325
+ * `acceptLegacyV2`). `namespace` defaults to the serialised one and
1326
+ * must agree with it when both are given.
794
1327
  * @returns {MeshKeyring}
795
1328
  */
796
- static fromJSON(data) {
797
- const kr = new MeshKeyring();
798
- for (const d of data) {
1329
+ static fromJSON(data, opts = {}) {
1330
+ const legacy = Array.isArray(data);
1331
+ const links = legacy ? data : (data?.links ?? []);
1332
+ const revocations = legacy ? [] : (data?.revocations ?? []);
1333
+ const storedNs = legacy ? null : (data?.namespace ?? null);
1334
+ if (!legacy && 'namespace' in opts && (opts.namespace ?? null) !== storedNs) {
1335
+ throw new Error('Namespace mismatch between options and serialised keyring');
1336
+ }
1337
+ const kr = new MeshKeyring({ ...opts, namespace: opts.namespace ?? storedNs });
1338
+ for (const d of links) {
799
1339
  /*
800
1340
  * Dispatch on the serialised shape. Reviving everything through
801
- * `KeyLink.fromJSON` returned a plain KeyLink for signed links too, and
802
- * `verifyCryptoChain` only checks a signature `if (link instanceof
803
- * SignedKeyLink)` -- so every restored keyring reported `valid: true`
804
- * having called `getPublicKey` zero times.
805
- *
806
- * The signatures were never lost; they survive serialisation intact.
807
- * Only the CLASS was, and the class is what the check keys on. So a
808
- * keyring that had been persisted, sent to a peer, or reloaded from
809
- * disk verified without any cryptography at all.
1341
+ * `KeyLink.fromJSON` returned a plain KeyLink for signed links too, so
1342
+ * a restored keyring verified without any cryptography (#33).
810
1343
  */
811
1344
  kr.#links.push(
812
1345
  d && (d.parentSignature || d.childSignature || d.signed)
@@ -814,6 +1347,15 @@ export class MeshKeyring {
814
1347
  : KeyLink.fromJSON(d)
815
1348
  );
816
1349
  }
1350
+ for (const r of revocations) {
1351
+ let u;
1352
+ try { u = SignedKeyUnlink.fromJSON(r); } catch (e) {
1353
+ kr.#dropped.push({ data: r, reason: `malformed: ${e.message}` });
1354
+ continue;
1355
+ }
1356
+ if (u.defect) kr.#dropped.push({ data: r, reason: u.defect });
1357
+ else if (!u.isExpired()) kr.#revocations.push(u);
1358
+ }
817
1359
  return kr;
818
1360
  }
819
1361
  }