@johnhenry/browsermesh-core 0.10.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.
Files changed (3) hide show
  1. package/README.md +15 -0
  2. package/package.json +1 -1
  3. package/src/keyring.mjs +132 -20
package/README.md CHANGED
@@ -64,6 +64,21 @@ import { MeshIdentityManager, MeshKeyring, TrustGraph } from '@johnhenry/browser
64
64
  - Revoke an edge with `SignedKeyUnlink.create(parentIdentity, childId)` and
65
65
  `keyring.applyUnlink(unlink, parentPub)`. Unlinks serialise, can be relayed
66
66
  to peers, and cut off every descendant of the child. `unlink()` is local only.
67
+ - A `SignedKeyUnlink` REQUIRES a signed `expires` (ms epoch, like
68
+ `SignedKeyLink`): `SignedKeyUnlink.create(p, childId, { expires })` throws
69
+ without one, or use `SignedKeyUnlink.forLink(parentIdentity, link)`, which
70
+ copies the link's expiry and namespace (pass `{ expires }` for a link that
71
+ never expires). It signs `"browsermesh/keyunlink/v2\n"` + canonical JSON.
72
+ **v1 unlinks (no `expires`) are no longer accepted**: `verify` is false,
73
+ `applyUnlink` throws, and `MeshKeyring.fromJSON` drops them (listed with a
74
+ reason in `keyring.droppedRevocations`). Once an unlink expires the keyring
75
+ stops counting it: `listRevocations({ now })`, `toJSON()` and `fromJSON()`
76
+ drop it, `pruneRevocations(now)` drops them explicitly and returns the
77
+ count, and `applyUnlink` records nothing for an already-expired one. Rule:
78
+ an unlink should expire no earlier than the link it revokes (what `forLink`
79
+ does). If it expires sooner, the revocation lapses and a stale copy of the
80
+ link is accepted again, but only while the link itself is unexpired;
81
+ `verifyCryptoChain` always refuses an expired link.
67
82
  - `executeSuccession(primary, { links, getPublicKey })` with a `transfer`
68
83
  policy needs successor-signed replacement links (`{ localOnly: true }` keeps
69
84
  the old unsigned behaviour).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-core",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Identity, crypto, peer management, and trust primitives for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/keyring.mjs CHANGED
@@ -35,7 +35,7 @@ export const VALID_RELATIONS = Object.freeze([
35
35
  export const KEYLINK_DOMAIN = 'browsermesh/keylink/v3\n';
36
36
 
37
37
  /** Domain prefix of the bytes a {@link SignedKeyUnlink} signs. */
38
- export const KEYUNLINK_DOMAIN = 'browsermesh/keyunlink/v1\n';
38
+ export const KEYUNLINK_DOMAIN = 'browsermesh/keyunlink/v2\n';
39
39
 
40
40
  // ---------------------------------------------------------------------------
41
41
  // KeyLink
@@ -348,8 +348,11 @@ export class SignedKeyLink extends KeyLink {
348
348
  /**
349
349
  * A signed, transferable revocation of the `parent -> child` edge.
350
350
  *
351
- * The parent signs `"browsermesh/keyunlink/v1\n" ‖ canonical(body)` over
352
- * `parent`, `child`, `namespace`, `created` and `reason`. It revokes every
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
353
356
  * link on that edge (in that namespace) created at or before `created`, so
354
357
  * a re-link signed later by both parties is not affected, but replaying the
355
358
  * old link is. Because authority flows down the chain, every descendant of
@@ -366,10 +369,17 @@ export class SignedKeyUnlink {
366
369
  * @param {string|null} [opts.namespace]
367
370
  * @param {number} [opts.created]
368
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.
369
375
  * @param {Uint8Array|null} [opts.signature]
370
376
  */
371
- constructor({ parent, child, namespace, created, reason, signature }) {
377
+ constructor({ parent, child, namespace, created, reason, expires, signature }) {
372
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;
373
383
  this.parent = parent;
374
384
  this.child = child;
375
385
  this.namespace = namespace ?? null;
@@ -378,7 +388,13 @@ export class SignedKeyUnlink {
378
388
  this.signature = signature || null;
379
389
  }
380
390
 
381
- /** @returns {Uint8Array} */
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
+ */
382
398
  get signedPayload() {
383
399
  return domainPayload(KEYUNLINK_DOMAIN, {
384
400
  parent: this.parent,
@@ -386,39 +402,85 @@ export class SignedKeyUnlink {
386
402
  namespace: this.namespace,
387
403
  created: this.created,
388
404
  reason: this.reason,
405
+ expires: this.expires,
389
406
  });
390
407
  }
391
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
+
392
418
  /**
393
419
  * Create an unlink signed by the parent.
394
420
  *
395
421
  * @param {import('./identity.mjs').PodIdentity} parentIdentity
396
422
  * @param {string} childId
397
- * @param {{ namespace?: string, reason?: string, created?: number }} [opts]
423
+ * @param {{ namespace?: string, reason?: string, created?: number, expires?: number }} [opts]
398
424
  * @returns {Promise<SignedKeyUnlink>}
399
425
  */
400
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
+ }
401
430
  const unlink = new SignedKeyUnlink({
402
431
  parent: parentIdentity.podId,
403
432
  child: childId,
404
433
  namespace: opts.namespace,
405
434
  created: opts.created ?? Date.now(),
406
435
  reason: opts.reason,
436
+ expires: opts.expires,
407
437
  });
408
438
  unlink.signature = await parentIdentity.sign(unlink.signedPayload);
409
439
  return unlink;
410
440
  }
411
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
+
412
466
  /**
413
467
  * Verify the parent's signature.
414
468
  * @param {CryptoKey} parentPub
415
469
  * @returns {Promise<boolean>}
416
470
  */
417
471
  async verify(parentPub) {
418
- if (!this.signature) return false;
472
+ if (!this.signature || !Number.isFinite(this.expires)) return false;
419
473
  return crypto.subtle.verify('Ed25519', parentPub, this.signature, this.signedPayload);
420
474
  }
421
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
+
422
484
  /**
423
485
  * Whether this unlink revokes `link` (same edge and namespace, and the
424
486
  * link was created at or before the unlink).
@@ -441,6 +503,7 @@ export class SignedKeyUnlink {
441
503
  namespace: this.namespace,
442
504
  created: this.created,
443
505
  reason: this.reason,
506
+ expires: this.expires,
444
507
  signature: this.signature ? encodeBase64url(this.signature) : null,
445
508
  };
446
509
  }
@@ -576,6 +639,8 @@ export class MeshKeyring {
576
639
 
577
640
  /** @type {SignedKeyUnlink[]} */
578
641
  #revocations = [];
642
+ /** @type {{ data: object, reason: string }[]} */
643
+ #dropped = [];
579
644
 
580
645
  /** @type {*} */
581
646
  #storage;
@@ -679,13 +744,40 @@ export class MeshKeyring {
679
744
  // -- Revocation ---------------------------------------------------------
680
745
 
681
746
  /**
682
- * Whether a recorded {@link SignedKeyUnlink} revokes `link`.
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).
683
752
  *
684
753
  * @param {KeyLink} link
754
+ * @param {number} [now=Date.now()]
685
755
  * @returns {boolean}
686
756
  */
687
- isRevoked(link) {
688
- return this.#revocations.some((r) => r.revokes(link));
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;
689
781
  }
690
782
 
691
783
  /**
@@ -711,6 +803,7 @@ export class MeshKeyring {
711
803
  `Namespace mismatch: unlink is for ${JSON.stringify(unlink.namespace)}, keyring is ${JSON.stringify(this.#namespace)}`
712
804
  );
713
805
  }
806
+ if (unlink.defect) throw new Error(`Unlink refused: ${unlink.defect}`);
714
807
  let ok = false;
715
808
  try {
716
809
  ok = await unlink.verify(parentPub);
@@ -719,12 +812,22 @@ export class MeshKeyring {
719
812
  }
720
813
  if (!ok) throw new Error('Signature verification failed');
721
814
 
815
+ // Already expired: it no longer counts, so record and relay nothing.
816
+ if (unlink.isExpired()) return { removed: false, descendants: [] };
817
+
722
818
  const descendants = this.#descendantsOf(unlink.child);
723
819
 
724
- const dup = this.#revocations.some(
725
- (r) => r.parent === unlink.parent && r.child === unlink.child && r.created === unlink.created
726
- );
727
- if (!dup) this.#revocations.push(unlink);
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
+ }
728
831
 
729
832
  const before = this.#links.length;
730
833
  this.#links = this.#links.filter((l) => !unlink.revokes(l));
@@ -732,12 +835,15 @@ export class MeshKeyring {
732
835
  }
733
836
 
734
837
  /**
735
- * All recorded signed revocations (copies of the list, same objects).
736
- * Relay these to peers so they can {@link MeshKeyring#applyUnlink} them.
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.
737
841
  *
842
+ * @param {{ now?: number }} [opts]
738
843
  * @returns {SignedKeyUnlink[]}
739
844
  */
740
- listRevocations() {
845
+ listRevocations(opts = {}) {
846
+ this.pruneRevocations(opts.now ?? Date.now());
741
847
  return [...this.#revocations];
742
848
  }
743
849
 
@@ -940,7 +1046,7 @@ export class MeshKeyring {
940
1046
 
941
1047
  for (const link of relevantChain) {
942
1048
  if (link.isExpired(now)) return fail(link, 'expired');
943
- if (this.isRevoked(link)) return fail(link, 'revoked');
1049
+ if (this.isRevoked(link, now)) return fail(link, 'revoked');
944
1050
  if ((link.namespace ?? null) !== this.#namespace) return fail(link, 'namespace');
945
1051
 
946
1052
  if (!(link instanceof SignedKeyLink)) {
@@ -1201,7 +1307,7 @@ export class MeshKeyring {
1201
1307
  v: 3,
1202
1308
  namespace: this.#namespace,
1203
1309
  links: this.#links.map((l) => l.toJSON()),
1204
- revocations: this.#revocations.map((r) => r.toJSON()),
1310
+ revocations: this.listRevocations().map((r) => r.toJSON()),
1205
1311
  };
1206
1312
  }
1207
1313
 
@@ -1242,7 +1348,13 @@ export class MeshKeyring {
1242
1348
  );
1243
1349
  }
1244
1350
  for (const r of revocations) {
1245
- kr.#revocations.push(SignedKeyUnlink.fromJSON(r));
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);
1246
1358
  }
1247
1359
  return kr;
1248
1360
  }