@johnhenry/browsermesh-core 0.9.0 → 0.10.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/README.md CHANGED
@@ -26,7 +26,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
26
26
  |--------|-------------|
27
27
  | identity | `MeshIdentityManager`, `AutoIdentityManager`, `IdentitySelector`, `PodIdentity`, `derivePodId` |
28
28
  | identity-tools | `IdentityCreateTool`, `IdentityListTool`, `IdentitySwitchTool`, `registerIdentityTools` |
29
- | keyring | `MeshKeyring`, `KeyLink`, `SignedKeyLink`, `SuccessionPolicy` |
29
+ | keyring | `MeshKeyring`, `KeyLink`, `SignedKeyLink`, `SignedKeyUnlink`, `SuccessionPolicy` |
30
30
  | group-keys | `GroupKeyManager`, `GroupState` |
31
31
  | peer | `PeerState`, `MeshPeerManager` |
32
32
  | peer-tools | `MeshPeerToolsContext`, `registerMeshPeerTools` + 30 BrowserTool subclasses |
@@ -50,6 +50,34 @@ npm install @johnhenry/browsermesh-core @johnhenry/browsermesh-primitives
50
50
  import { MeshIdentityManager, MeshKeyring, TrustGraph } from '@johnhenry/browsermesh-core';
51
51
  ```
52
52
 
53
+ ## Verifying key links and capabilities from peers
54
+
55
+ - `MeshKeyring#verifyCryptoChain(from, to, getPublicKey)` requires every link
56
+ on the path to be a `SignedKeyLink` signed by both ends, unexpired, in the
57
+ keyring's `namespace` and not revoked. Unsigned `KeyLink`s (from `link()`)
58
+ are refused unless you pass `{ requireSigned: false }`.
59
+ - `SignedKeyLink`s sign `"browsermesh/keylink/v3\n"` + sorted-key canonical
60
+ JSON, including an optional `namespace`. Give the keyring and its links the
61
+ same namespace (`new MeshKeyring({ namespace })`,
62
+ `SignedKeyLink.create(p, c, rel, { namespace })`) so a link issued for one
63
+ keyring is refused by another.
64
+ - Revoke an edge with `SignedKeyUnlink.create(parentIdentity, childId)` and
65
+ `keyring.applyUnlink(unlink, parentPub)`. Unlinks serialise, can be relayed
66
+ to peers, and cut off every descendant of the child. `unlink()` is local only.
67
+ - `executeSuccession(primary, { links, getPublicKey })` with a `transfer`
68
+ policy needs successor-signed replacement links (`{ localOnly: true }` keeps
69
+ the old unsigned behaviour).
70
+ - Before a capability chain crosses peers, sign it (`CapabilityToken.issue`,
71
+ `token.attenuateSigned`) and check it on arrival with
72
+ `chain.verifySignatures(getPublicKey, { rootIssuer })`.
73
+
74
+ **Migrating links signed before 0.10 (v2 payload).** They no longer verify by
75
+ default. To migrate, load them into a keyring with `{ acceptLegacyV2: true }`
76
+ (verification only, never for signing), find them with
77
+ `link.signatureVersion(parentPub, childPub) === 2`, and re-sign each with
78
+ `link.resign(parentIdentity, childIdentity, { namespace })`. v1
79
+ (`a|b|c|d`) signatures are no longer accepted at all; re-create those links.
80
+
53
81
  ## Padding group-key envelopes
54
82
 
55
83
  `GroupKeyManager.encrypt()` leaks the exact plaintext length to anything that
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-core",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Identity, crypto, peer management, and trust primitives for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -0,0 +1,62 @@
1
+ /**
2
+ * canonical.mjs -- Deterministic, domain-separated signing payloads.
3
+ *
4
+ * Internal helper (not re-exported from index.mjs). Used by
5
+ * SignedKeyLink, SignedKeyUnlink and signed CapabilityTokens so that every
6
+ * signature this package produces:
7
+ *
8
+ * - is over a canonical encoding: JSON with object keys sorted (recursively),
9
+ * no whitespace, `undefined` object members omitted, and only finite
10
+ * numbers — so two implementations that agree on the value agree on the
11
+ * bytes, regardless of property insertion order;
12
+ * - carries a domain prefix (`<namespace>/<type>/v<n>\n`) so a signature
13
+ * minted for one message type can never be replayed as another, even when
14
+ * the two bodies happen to encode identically.
15
+ */
16
+
17
+ /**
18
+ * Canonical JSON encoding with sorted keys.
19
+ *
20
+ * @param {*} value
21
+ * @returns {string}
22
+ */
23
+ export function canonicalize(value) {
24
+ if (value === null) return 'null';
25
+ switch (typeof value) {
26
+ case 'boolean':
27
+ case 'string':
28
+ return JSON.stringify(value);
29
+ case 'number':
30
+ if (!Number.isFinite(value)) {
31
+ throw new TypeError(`Cannot canonicalize non-finite number: ${value}`);
32
+ }
33
+ return JSON.stringify(value);
34
+ case 'object': {
35
+ if (Array.isArray(value)) {
36
+ return `[${value.map((v) => {
37
+ if (v === undefined) throw new TypeError('Cannot canonicalize undefined array element');
38
+ return canonicalize(v);
39
+ }).join(',')}]`;
40
+ }
41
+ const proto = Object.getPrototypeOf(value);
42
+ if (proto !== Object.prototype && proto !== null) {
43
+ throw new TypeError('Can only canonicalize plain objects');
44
+ }
45
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
46
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize(value[k])}`).join(',')}}`;
47
+ }
48
+ default:
49
+ throw new TypeError(`Cannot canonicalize value of type ${typeof value}`);
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Bytes to sign: `prefix ‖ canonicalize(body)`, UTF-8 encoded.
55
+ *
56
+ * @param {string} prefix - Domain prefix, ending in `\n`
57
+ * @param {object} body
58
+ * @returns {Uint8Array}
59
+ */
60
+ export function domainPayload(prefix, body) {
61
+ return new TextEncoder().encode(prefix + canonicalize(body));
62
+ }
@@ -17,10 +17,16 @@
17
17
  * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-capabilities.test.mjs
18
18
  */
19
19
 
20
+ import { encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives';
21
+ import { domainPayload } from './canonical.mjs';
22
+
20
23
  // ---------------------------------------------------------------------------
21
24
  // Wire Constants
22
25
  // ---------------------------------------------------------------------------
23
26
 
27
+ /** Domain prefix of the bytes a signed {@link CapabilityToken} signs. */
28
+ export const CAPABILITY_DOMAIN = 'browsermesh/capability/v1\n';
29
+
24
30
  /** Wire type for capability grant message. */
25
31
  export const CAP_GRANT = 0xDC;
26
32
 
@@ -105,8 +111,17 @@ export function expiryNarrows(parentExpiry, childExpiry) {
105
111
  let _tokenSeq = 0;
106
112
 
107
113
  /**
108
- * An unforgeable capability token granting specific access rights.
114
+ * A capability token granting specific access rights.
109
115
  * Tokens can be attenuated (narrowed) but never amplified.
116
+ *
117
+ * A token built with `new CapabilityToken(...)` is unsigned: fine for a
118
+ * single process, but not something another peer should trust. Before a
119
+ * token or chain crosses peers, sign it: {@link CapabilityToken.issue} for a
120
+ * root, {@link CapabilityToken#attenuateSigned} for a delegation. The issuer
121
+ * signs `"browsermesh/capability/v1\n" ‖ canonical(body)` over every field
122
+ * except the local `revoked` flag — including `parentId` and `depth`, so a
123
+ * signed token is bound to its place in the chain. Verify a chain received
124
+ * from a peer with {@link CapabilityChain#verifySignatures}.
110
125
  */
111
126
  export class CapabilityToken {
112
127
  /**
@@ -123,6 +138,7 @@ export class CapabilityToken {
123
138
  * @param {boolean} [opts.revoked] Whether token has been revoked
124
139
  * @param {number} [opts.depth] Delegation depth (0 for root)
125
140
  * @param {number|null} [opts.maxDepth] Maximum delegation depth (null = unlimited)
141
+ * @param {Uint8Array|null} [opts.signature] Issuer's Ed25519 signature over {@link CapabilityToken#signedPayload}
126
142
  */
127
143
  constructor({
128
144
  id,
@@ -137,6 +153,7 @@ export class CapabilityToken {
137
153
  revoked = false,
138
154
  depth = 0,
139
155
  maxDepth = null,
156
+ signature = null,
140
157
  }) {
141
158
  if (!issuer || typeof issuer !== 'string') {
142
159
  throw new Error('issuer is required and must be a non-empty string');
@@ -163,6 +180,76 @@ export class CapabilityToken {
163
180
  this.revoked = revoked;
164
181
  this.depth = depth;
165
182
  this.maxDepth = maxDepth;
183
+ /** @type {Uint8Array|null} */
184
+ this.signature = signature || null;
185
+ }
186
+
187
+ /**
188
+ * Bytes the issuer signs: domain prefix plus sorted-key canonical JSON of
189
+ * every field except `revoked` (local state) and `signature`.
190
+ *
191
+ * @returns {Uint8Array}
192
+ */
193
+ get signedPayload() {
194
+ return domainPayload(CAPABILITY_DOMAIN, {
195
+ id: this.id,
196
+ issuer: this.issuer,
197
+ holder: this.holder,
198
+ resource: this.resource,
199
+ permissions: [...this.permissions],
200
+ constraints: { ...this.constraints },
201
+ parentId: this.parentId,
202
+ createdAt: this.createdAt,
203
+ expiresAt: this.expiresAt,
204
+ depth: this.depth,
205
+ maxDepth: this.maxDepth,
206
+ });
207
+ }
208
+
209
+ /** Whether the token carries a signature (not whether it verifies). */
210
+ get isSigned() {
211
+ return this.signature !== null;
212
+ }
213
+
214
+ /**
215
+ * Sign this token as its issuer. The identity must be the issuer.
216
+ *
217
+ * @param {{ podId: string, sign: (data: Uint8Array) => Promise<Uint8Array> }} issuerIdentity
218
+ * @returns {Promise<this>}
219
+ */
220
+ async sign(issuerIdentity) {
221
+ if (!issuerIdentity || issuerIdentity.podId !== this.issuer) {
222
+ throw new Error('Only the issuer can sign a capability token');
223
+ }
224
+ this.signature = await issuerIdentity.sign(this.signedPayload);
225
+ return this;
226
+ }
227
+
228
+ /**
229
+ * Verify the issuer's signature.
230
+ *
231
+ * @param {CryptoKey} issuerPub
232
+ * @returns {Promise<boolean>}
233
+ */
234
+ async verifySignature(issuerPub) {
235
+ if (!this.signature) return false;
236
+ try {
237
+ return await crypto.subtle.verify('Ed25519', issuerPub, this.signature, this.signedPayload);
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Issue a signed root token. `issuer` is the identity's pod ID.
245
+ *
246
+ * @param {{ podId: string, sign: Function }} issuerIdentity
247
+ * @param {object} opts - Constructor options other than `issuer`
248
+ * @returns {Promise<CapabilityToken>}
249
+ */
250
+ static async issue(issuerIdentity, opts) {
251
+ const token = new CapabilityToken({ ...opts, issuer: issuerIdentity.podId, signature: null });
252
+ return token.sign(issuerIdentity);
166
253
  }
167
254
 
168
255
  /** Check whether this token has expired. */
@@ -261,6 +348,21 @@ export class CapabilityToken {
261
348
  });
262
349
  }
263
350
 
351
+ /**
352
+ * {@link CapabilityToken#attenuate}, then sign the child as its issuer
353
+ * (this token's holder).
354
+ *
355
+ * @param {{ podId: string, sign: Function }} holderIdentity - This token's holder
356
+ * @param {object} opts - As for attenuate()
357
+ * @returns {Promise<CapabilityToken>}
358
+ */
359
+ async attenuateSigned(holderIdentity, opts) {
360
+ if (!holderIdentity || holderIdentity.podId !== this.holder) {
361
+ throw new Error('Only the holder can delegate a capability token');
362
+ }
363
+ return this.attenuate(opts).sign(holderIdentity);
364
+ }
365
+
264
366
  /** Revoke this token. */
265
367
  revoke() {
266
368
  this.revoked = true;
@@ -280,11 +382,15 @@ export class CapabilityToken {
280
382
  revoked: this.revoked,
281
383
  depth: this.depth,
282
384
  maxDepth: this.maxDepth,
385
+ ...(this.signature ? { signature: encodeBase64url(this.signature) } : {}),
283
386
  };
284
387
  }
285
388
 
286
389
  static fromJSON(data) {
287
- return new CapabilityToken(data);
390
+ return new CapabilityToken({
391
+ ...data,
392
+ signature: data.signature ? decodeBase64url(data.signature) : null,
393
+ });
288
394
  }
289
395
  }
290
396
 
@@ -415,6 +521,56 @@ export class CapabilityChain {
415
521
  return { valid: true };
416
522
  }
417
523
 
524
+ /**
525
+ * Structural {@link CapabilityChain#verify} plus signatures — use this for
526
+ * any chain that came from another peer. Additionally requires:
527
+ * - every token is signed by its `issuer` (key from `getPublicKey`);
528
+ * - each delegated token's `issuer` is the `holder` of its parent, so
529
+ * only the holder of a capability can delegate it;
530
+ * - optionally, the root's issuer is `opts.rootIssuer`.
531
+ *
532
+ * Because each signature covers `parentId` and `depth`, a signed token
533
+ * cannot be re-parented into another chain.
534
+ *
535
+ * @param {(podId: string) => CryptoKey|Promise<CryptoKey>} getPublicKey
536
+ * @param {object} [opts]
537
+ * @param {boolean} [opts.checkValidity=true]
538
+ * @param {string} [opts.rootIssuer] - Required issuer of the root token
539
+ * @returns {Promise<{ valid: boolean, error?: string, brokenAt?: number }>}
540
+ */
541
+ async verifySignatures(getPublicKey, opts = {}) {
542
+ const structural = this.verify(opts.checkValidity ?? true);
543
+ if (!structural.valid) return structural;
544
+
545
+ if (opts.rootIssuer !== undefined && this.#tokens[0].issuer !== opts.rootIssuer) {
546
+ return { valid: false, error: 'Root token issuer is not trusted', brokenAt: 0 };
547
+ }
548
+
549
+ for (let i = 0; i < this.#tokens.length; i++) {
550
+ const token = this.#tokens[i];
551
+ if (!token.signature) {
552
+ return { valid: false, error: `Token at index ${i} is unsigned`, brokenAt: i };
553
+ }
554
+ if (i > 0 && token.issuer !== this.#tokens[i - 1].holder) {
555
+ return {
556
+ valid: false,
557
+ error: `Token at index ${i} was issued by "${token.issuer}", not by its parent's holder`,
558
+ brokenAt: i,
559
+ };
560
+ }
561
+ let pub;
562
+ try {
563
+ pub = await getPublicKey(token.issuer);
564
+ } catch {
565
+ pub = null;
566
+ }
567
+ if (!pub || !(await token.verifySignature(pub))) {
568
+ return { valid: false, error: `Bad signature at index ${i}`, brokenAt: i };
569
+ }
570
+ }
571
+ return { valid: true };
572
+ }
573
+
418
574
  /** Get all tokens as array. */
419
575
  toArray() {
420
576
  return [...this.#tokens];
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/v1\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.
135
- *
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}.
156
+ * The canonical signed payload bytes (version 3).
141
157
  *
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,122 @@ 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/v1\n" ‖ canonical(body)` over
352
+ * `parent`, `child`, `namespace`, `created` and `reason`. It revokes every
353
+ * link on that edge (in that namespace) created at or before `created`, so
354
+ * a re-link signed later by both parties is not affected, but replaying the
355
+ * old link is. Because authority flows down the chain, every descendant of
356
+ * `child` loses whatever authority it derived through the revoked edge.
357
+ *
358
+ * Unlike {@link MeshKeyring#unlink} (local only), an unlink can be relayed
359
+ * to peers and applied with {@link MeshKeyring#applyUnlink}.
360
+ */
361
+ export class SignedKeyUnlink {
362
+ /**
363
+ * @param {object} opts
364
+ * @param {string} opts.parent
365
+ * @param {string} opts.child
366
+ * @param {string|null} [opts.namespace]
367
+ * @param {number} [opts.created]
368
+ * @param {string|null} [opts.reason]
369
+ * @param {Uint8Array|null} [opts.signature]
370
+ */
371
+ constructor({ parent, child, namespace, created, reason, signature }) {
372
+ if (!parent || !child) throw new Error('parent and child are required');
373
+ this.parent = parent;
374
+ this.child = child;
375
+ this.namespace = namespace ?? null;
376
+ this.created = created || Date.now();
377
+ this.reason = reason ?? null;
378
+ this.signature = signature || null;
379
+ }
380
+
381
+ /** @returns {Uint8Array} */
382
+ get signedPayload() {
383
+ return domainPayload(KEYUNLINK_DOMAIN, {
384
+ parent: this.parent,
385
+ child: this.child,
386
+ namespace: this.namespace,
387
+ created: this.created,
388
+ reason: this.reason,
389
+ });
390
+ }
391
+
392
+ /**
393
+ * Create an unlink signed by the parent.
394
+ *
395
+ * @param {import('./identity.mjs').PodIdentity} parentIdentity
396
+ * @param {string} childId
397
+ * @param {{ namespace?: string, reason?: string, created?: number }} [opts]
398
+ * @returns {Promise<SignedKeyUnlink>}
399
+ */
400
+ static async create(parentIdentity, childId, opts = {}) {
401
+ const unlink = new SignedKeyUnlink({
402
+ parent: parentIdentity.podId,
403
+ child: childId,
404
+ namespace: opts.namespace,
405
+ created: opts.created ?? Date.now(),
406
+ reason: opts.reason,
407
+ });
408
+ unlink.signature = await parentIdentity.sign(unlink.signedPayload);
409
+ return unlink;
410
+ }
411
+
412
+ /**
413
+ * Verify the parent's signature.
414
+ * @param {CryptoKey} parentPub
415
+ * @returns {Promise<boolean>}
416
+ */
417
+ async verify(parentPub) {
418
+ if (!this.signature) return false;
419
+ return crypto.subtle.verify('Ed25519', parentPub, this.signature, this.signedPayload);
420
+ }
421
+
422
+ /**
423
+ * Whether this unlink revokes `link` (same edge and namespace, and the
424
+ * link was created at or before the unlink).
425
+ *
426
+ * @param {KeyLink} link
427
+ * @returns {boolean}
428
+ */
429
+ revokes(link) {
430
+ return link.parent === this.parent &&
431
+ link.child === this.child &&
432
+ (link.namespace ?? null) === this.namespace &&
433
+ link.created <= this.created;
434
+ }
435
+
436
+ toJSON() {
437
+ return {
438
+ type: 'unlink',
439
+ parent: this.parent,
440
+ child: this.child,
441
+ namespace: this.namespace,
442
+ created: this.created,
443
+ reason: this.reason,
444
+ signature: this.signature ? encodeBase64url(this.signature) : null,
445
+ };
446
+ }
447
+
448
+ /**
449
+ * @param {object} data
450
+ * @returns {SignedKeyUnlink}
451
+ */
452
+ static fromJSON(data) {
453
+ return new SignedKeyUnlink({
454
+ ...data,
455
+ signature: data.signature ? decodeBase64url(data.signature) : null,
456
+ });
457
+ }
458
+ }
459
+
301
460
  // ---------------------------------------------------------------------------
302
461
  // SuccessionPolicy
303
462
  // ---------------------------------------------------------------------------
@@ -378,18 +537,55 @@ export class SuccessionPolicy {
378
537
  // MeshKeyring
379
538
  // ---------------------------------------------------------------------------
380
539
 
540
+ /**
541
+ * Whether `child` scope is no wider than `parent` scope (null = unrestricted).
542
+ * @param {string[]|null} parent
543
+ * @param {string[]|null} child
544
+ */
545
+ function scopeNarrows(parent, child) {
546
+ if (parent === null) return true;
547
+ if (child === null) return false;
548
+ return child.every((s) => parent.includes(s));
549
+ }
550
+
551
+ /**
552
+ * Whether `child` expiry is no later than `parent` expiry (null = never).
553
+ * @param {number|null} parent
554
+ * @param {number|null} child
555
+ */
556
+ function expiresNarrows(parent, child) {
557
+ if (parent === null) return true;
558
+ if (child === null) return false;
559
+ return child <= parent;
560
+ }
561
+
381
562
  /**
382
563
  * Manages a graph of KeyLink relationships between identities.
383
564
  *
565
+ * A keyring may be bound to a `namespace` (any string naming the context:
566
+ * an account, an app, a mesh). Signed links and unlinks carry the namespace
567
+ * inside their signature, and the keyring only accepts ones whose namespace
568
+ * equals its own (`null` matches only `null`), so a link issued for one
569
+ * keyring cannot be replayed into another.
570
+ *
384
571
  * @class
385
572
  */
386
573
  export class MeshKeyring {
387
574
  /** @type {KeyLink[]} */
388
575
  #links = [];
389
576
 
577
+ /** @type {SignedKeyUnlink[]} */
578
+ #revocations = [];
579
+
390
580
  /** @type {*} */
391
581
  #storage;
392
582
 
583
+ /** @type {string|null} */
584
+ #namespace;
585
+
586
+ /** @type {boolean} */
587
+ #acceptLegacyV2;
588
+
393
589
  /** @type {Map<string, SuccessionPolicy>} primaryId -> policy */
394
590
  #successions = new Map();
395
591
 
@@ -399,15 +595,31 @@ export class MeshKeyring {
399
595
  /**
400
596
  * @param {object} [opts]
401
597
  * @param {*} [opts.storage] - Optional persistence adapter
598
+ * @param {string|null} [opts.namespace=null] - Context this keyring accepts links for
599
+ * @param {boolean} [opts.acceptLegacyV2=false] - Migration aid: also verify
600
+ * signatures over the pre-0.10 v2 payload (namespace-less links only).
601
+ * Off by default; turn it on only while re-signing persisted links.
402
602
  */
403
603
  constructor(opts = {}) {
404
604
  this.#storage = opts.storage || null;
605
+ this.#namespace = opts.namespace ?? null;
606
+ this.#acceptLegacyV2 = opts.acceptLegacyV2 === true;
607
+ }
608
+
609
+ /** The namespace this keyring accepts signed links and unlinks for. */
610
+ get namespace() {
611
+ return this.#namespace;
405
612
  }
406
613
 
407
614
  // -- Link management ----------------------------------------------------
408
615
 
409
616
  /**
410
- * Create a link from parent to child with the given relation.
617
+ * Create an **unsigned, local-only** link from parent to child.
618
+ *
619
+ * Unsigned links are useful for local bookkeeping but carry no proof:
620
+ * {@link MeshKeyring#verifyCryptoChain} refuses them unless called with
621
+ * `requireSigned: false`. Use {@link SignedKeyLink.create} plus
622
+ * {@link MeshKeyring#addVerifiedLink} for anything another party relies on.
411
623
  *
412
624
  * @param {string} parentId - Parent identity pod ID
413
625
  * @param {string} childId - Child identity pod ID
@@ -439,13 +651,17 @@ export class MeshKeyring {
439
651
  relation,
440
652
  scope: opts.scope,
441
653
  expires: opts.expires,
654
+ namespace: this.#namespace,
442
655
  });
443
656
  this.#links.push(link);
444
657
  return link;
445
658
  }
446
659
 
447
660
  /**
448
- * Remove a link between parent and child.
661
+ * Remove a link between parent and child. **Local only**: nothing is
662
+ * signed and peers are not told. To revoke a link in a way peers can
663
+ * verify and relay, create a {@link SignedKeyUnlink} and
664
+ * {@link MeshKeyring#applyUnlink} it.
449
665
  *
450
666
  * @param {string} parentId
451
667
  * @param {string} childId
@@ -460,6 +676,89 @@ export class MeshKeyring {
460
676
  return true;
461
677
  }
462
678
 
679
+ // -- Revocation ---------------------------------------------------------
680
+
681
+ /**
682
+ * Whether a recorded {@link SignedKeyUnlink} revokes `link`.
683
+ *
684
+ * @param {KeyLink} link
685
+ * @returns {boolean}
686
+ */
687
+ isRevoked(link) {
688
+ return this.#revocations.some((r) => r.revokes(link));
689
+ }
690
+
691
+ /**
692
+ * Apply a signed revocation: verify the parent's signature, record it
693
+ * (so the revoked link cannot be re-added or verified later, even if it
694
+ * arrives after the unlink), and remove the edge.
695
+ *
696
+ * Cascades: every descendant of the child loses the authority it derived
697
+ * through the revoked edge — {@link MeshKeyring#verifyCryptoChain} from
698
+ * any of them to an ancestor above the edge fails. The descendants are
699
+ * returned so callers can react (re-enroll, notify).
700
+ *
701
+ * @param {SignedKeyUnlink} unlink
702
+ * @param {CryptoKey} parentPub - The unlink's parent's Ed25519 public key
703
+ * @returns {Promise<{ removed: boolean, descendants: string[] }>}
704
+ */
705
+ async applyUnlink(unlink, parentPub) {
706
+ if (!(unlink instanceof SignedKeyUnlink)) {
707
+ throw new Error('Expected a SignedKeyUnlink instance');
708
+ }
709
+ if (unlink.namespace !== this.#namespace) {
710
+ throw new Error(
711
+ `Namespace mismatch: unlink is for ${JSON.stringify(unlink.namespace)}, keyring is ${JSON.stringify(this.#namespace)}`
712
+ );
713
+ }
714
+ let ok = false;
715
+ try {
716
+ ok = await unlink.verify(parentPub);
717
+ } catch {
718
+ ok = false;
719
+ }
720
+ if (!ok) throw new Error('Signature verification failed');
721
+
722
+ const descendants = this.#descendantsOf(unlink.child);
723
+
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);
728
+
729
+ const before = this.#links.length;
730
+ this.#links = this.#links.filter((l) => !unlink.revokes(l));
731
+ return { removed: this.#links.length < before, descendants };
732
+ }
733
+
734
+ /**
735
+ * All recorded signed revocations (copies of the list, same objects).
736
+ * Relay these to peers so they can {@link MeshKeyring#applyUnlink} them.
737
+ *
738
+ * @returns {SignedKeyUnlink[]}
739
+ */
740
+ listRevocations() {
741
+ return [...this.#revocations];
742
+ }
743
+
744
+ /** @param {string} id @returns {string[]} */
745
+ #descendantsOf(id) {
746
+ const out = [];
747
+ const seen = new Set([id]);
748
+ const queue = [id];
749
+ while (queue.length) {
750
+ const cur = queue.shift();
751
+ for (const l of this.#links) {
752
+ if (l.parent === cur && !seen.has(l.child)) {
753
+ seen.add(l.child);
754
+ out.push(l.child);
755
+ queue.push(l.child);
756
+ }
757
+ }
758
+ }
759
+ return out;
760
+ }
761
+
463
762
  // -- Chain traversal ----------------------------------------------------
464
763
 
465
764
  /**
@@ -528,7 +827,8 @@ export class MeshKeyring {
528
827
  }
529
828
 
530
829
  /**
531
- * Verify a chain for expiration.
830
+ * Verify a chain for expiration (structure only, no signatures; see
831
+ * {@link MeshKeyring#verifyCryptoChain}).
532
832
  *
533
833
  * @param {KeyLink[]} chain
534
834
  * @param {number} [now=Date.now()]
@@ -549,7 +849,8 @@ export class MeshKeyring {
549
849
  // -- Signed link support ------------------------------------------------
550
850
 
551
851
  /**
552
- * Add a signed link after verifying its signatures.
852
+ * Add a signed link after verifying its signatures, its namespace and
853
+ * that no recorded unlink revokes it.
553
854
  *
554
855
  * @param {SignedKeyLink} signedLink
555
856
  * @param {CryptoKey} parentPub - Parent's Ed25519 public key
@@ -566,8 +867,18 @@ export class MeshKeyring {
566
867
  if (signedLink.parent === signedLink.child) {
567
868
  throw new Error('Cannot link identity to itself');
568
869
  }
870
+ if (signedLink.namespace !== this.#namespace) {
871
+ throw new Error(
872
+ `Namespace mismatch: link is for ${JSON.stringify(signedLink.namespace)}, keyring is ${JSON.stringify(this.#namespace)}`
873
+ );
874
+ }
875
+ if (this.isRevoked(signedLink)) {
876
+ throw new Error(`Link has been revoked: ${signedLink.parent} -> ${signedLink.child}`);
877
+ }
569
878
 
570
- const valid = await signedLink.verifyBoth(parentPub, childPub);
879
+ const valid = await signedLink.verifyBoth(parentPub, childPub, {
880
+ acceptLegacyV2: this.#acceptLegacyV2,
881
+ });
571
882
  if (!valid) {
572
883
  throw new Error('Signature verification failed');
573
884
  }
@@ -584,14 +895,30 @@ export class MeshKeyring {
584
895
  }
585
896
 
586
897
  /**
587
- * Verify an entire chain cryptographically (signatures + expiration).
898
+ * Verify an entire chain cryptographically: every link on the path from
899
+ * `fromId` up to `toId` must be signed by both ends, unexpired, in this
900
+ * keyring's namespace, and not revoked by a recorded {@link SignedKeyUnlink}.
901
+ *
902
+ * On failure, `brokenAt` is the child ID of the offending link (or
903
+ * `'no-path'`) and `reason` is one of `'no-path'`, `'expired'`,
904
+ * `'revoked'`, `'namespace'`, `'unsigned'` or `'bad-signature'`.
588
905
  *
589
906
  * @param {string} fromId - Starting identity (leaf)
590
907
  * @param {string} toId - Target identity (root/ancestor)
591
908
  * @param {Function} getPublicKey - async (podId) => CryptoKey
592
- * @returns {Promise<{valid: boolean, chain: KeyLink[], brokenAt?: string}>}
909
+ * @param {object} [opts]
910
+ * @param {boolean} [opts.requireSigned=true] - Refuse unsigned KeyLinks.
911
+ * `false` restores the pre-0.10 behaviour of skipping them; only for
912
+ * purely local graphs.
913
+ * @param {boolean} [opts.acceptLegacyV2] - Defaults to the keyring's setting
914
+ * @param {number} [opts.now=Date.now()]
915
+ * @returns {Promise<{valid: boolean, chain: KeyLink[], brokenAt?: string, reason?: string}>}
593
916
  */
594
- async verifyCryptoChain(fromId, toId, getPublicKey) {
917
+ async verifyCryptoChain(fromId, toId, getPublicKey, opts = {}) {
918
+ const requireSigned = opts.requireSigned ?? true;
919
+ const acceptLegacyV2 = opts.acceptLegacyV2 ?? this.#acceptLegacyV2;
920
+ const now = opts.now ?? Date.now();
921
+
595
922
  const chain = this.getChain(fromId);
596
923
  const relevantChain = [];
597
924
 
@@ -606,26 +933,28 @@ export class MeshKeyring {
606
933
  }
607
934
 
608
935
  if (!found) {
609
- return { valid: false, chain: relevantChain, brokenAt: 'no-path' };
936
+ return { valid: false, chain: relevantChain, brokenAt: 'no-path', reason: 'no-path' };
610
937
  }
611
938
 
612
- // Verify each link in the chain
939
+ const fail = (link, reason) => ({ valid: false, chain: relevantChain, brokenAt: link.child, reason });
940
+
613
941
  for (const link of relevantChain) {
614
- if (link.isExpired()) {
615
- return { valid: false, chain: relevantChain, brokenAt: link.child };
942
+ if (link.isExpired(now)) return fail(link, 'expired');
943
+ if (this.isRevoked(link)) return fail(link, 'revoked');
944
+ if ((link.namespace ?? null) !== this.#namespace) return fail(link, 'namespace');
945
+
946
+ if (!(link instanceof SignedKeyLink)) {
947
+ if (requireSigned) return fail(link, 'unsigned');
948
+ continue;
616
949
  }
617
950
 
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
- }
951
+ try {
952
+ const parentPub = await getPublicKey(link.parent);
953
+ const childPub = await getPublicKey(link.child);
954
+ const ok = await link.verifyBoth(parentPub, childPub, { acceptLegacyV2 });
955
+ if (!ok) return fail(link, 'bad-signature');
956
+ } catch {
957
+ return fail(link, 'bad-signature');
629
958
  }
630
959
  }
631
960
 
@@ -637,6 +966,9 @@ export class MeshKeyring {
637
966
  /**
638
967
  * Register a succession policy for a primary identity.
639
968
  *
969
+ * The policy and the activity log are **local state**: nothing about them
970
+ * is signed. They decide when this keyring acts, not what peers accept.
971
+ *
640
972
  * @param {string} primaryId - Identity that must remain active
641
973
  * @param {string} successorId - Identity that takes over
642
974
  * @param {number} thresholdMs - Inactivity threshold in milliseconds
@@ -693,17 +1025,30 @@ export class MeshKeyring {
693
1025
  /**
694
1026
  * Execute a succession policy for the given primary identity.
695
1027
  *
696
- * - **transfer**: re-links all children of primaryId to successorId,
697
- * removes old links.
698
- * - **revoke**: removes all child links of primaryId.
1028
+ * - **transfer**: moves every child of `primaryId` under `successorId`.
1029
+ * The keyring cannot sign on anyone's behalf, so the caller supplies
1030
+ * `opts.links`: one {@link SignedKeyLink} per child, signed by the
1031
+ * successor (as parent) and the child, with the same relation and a
1032
+ * scope/expiry no wider than the link it replaces, in this keyring's
1033
+ * namespace. They are all verified (via `opts.getPublicKey`) before
1034
+ * anything changes; if any is missing or invalid, the call rejects and
1035
+ * the keyring is untouched. Pass `{ localOnly: true }` instead to get
1036
+ * the pre-0.10 behaviour of re-linking with **unsigned** local links,
1037
+ * which `verifyCryptoChain` refuses by default.
1038
+ * - **revoke**: removes all child links of primaryId (locally; to tell
1039
+ * peers, distribute {@link SignedKeyUnlink}s signed by the primary).
699
1040
  * - **notify**: returns a notification signal without modifying links.
700
1041
  *
701
- * The policy is removed after execution.
1042
+ * The policy is removed after successful execution.
702
1043
  *
703
1044
  * @param {string} primaryId
704
- * @returns {{ action: string, primaryId: string, successorId: string, affected: number }}
1045
+ * @param {object} [opts]
1046
+ * @param {SignedKeyLink[]} [opts.links] - Successor-signed replacement links (transfer)
1047
+ * @param {Function} [opts.getPublicKey] - async (podId) => CryptoKey (transfer)
1048
+ * @param {boolean} [opts.localOnly=false] - transfer with unsigned local links
1049
+ * @returns {Promise<{ action: string, primaryId: string, successorId: string, affected: number }>}
705
1050
  */
706
- executeSuccession(primaryId) {
1051
+ async executeSuccession(primaryId, opts = {}) {
707
1052
  const policy = this.#successions.get(primaryId);
708
1053
  if (!policy) {
709
1054
  throw new Error(`No succession policy for: ${primaryId}`);
@@ -713,21 +1058,84 @@ export class MeshKeyring {
713
1058
  let affected = 0;
714
1059
 
715
1060
  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
1061
+ const successorId = policy.successorId;
1062
+ if (opts.localOnly === true) {
1063
+ for (const child of children) {
1064
+ this.unlink(primaryId, child.child);
1065
+ if (successorId !== child.child) {
1066
+ const existing = this.#links.find(
1067
+ (l) => l.parent === successorId && l.child === child.child
1068
+ );
1069
+ if (!existing) {
1070
+ this.link(successorId, child.child, child.relation, {
1071
+ scope: child.scope || undefined,
1072
+ expires: child.expires ?? undefined,
1073
+ });
1074
+ }
1075
+ }
1076
+ affected++;
1077
+ }
1078
+ } else {
1079
+ const supplied = opts.links || [];
1080
+ const plan = [];
1081
+ for (const child of children) {
1082
+ if (child.child === successorId) {
1083
+ plan.push({ child, replacement: null });
1084
+ continue;
1085
+ }
1086
+ const alreadyLinked = this.#links.some(
1087
+ (l) => l.parent === successorId && l.child === child.child
1088
+ );
1089
+ if (alreadyLinked) {
1090
+ plan.push({ child, replacement: null });
1091
+ continue;
1092
+ }
1093
+ const replacement = supplied.find(
1094
+ (l) => l && l.parent === successorId && l.child === child.child
722
1095
  );
723
- if (!existing) {
724
- this.link(policy.successorId, child.child, child.relation, {
725
- scope: child.scope || undefined,
726
- expires: child.expires || undefined,
727
- });
1096
+ if (!(replacement instanceof SignedKeyLink)) {
1097
+ throw new Error(
1098
+ `transfer needs a SignedKeyLink ${successorId} -> ${child.child} signed by both (or pass localOnly: true)`
1099
+ );
1100
+ }
1101
+ if (replacement.relation !== child.relation) {
1102
+ throw new Error(`Replacement link for ${child.child} changes relation`);
1103
+ }
1104
+ if (!scopeNarrows(child.scope, replacement.scope) ||
1105
+ !expiresNarrows(child.expires, replacement.expires)) {
1106
+ throw new Error(`Replacement link for ${child.child} is wider than the link it replaces`);
1107
+ }
1108
+ if (replacement.namespace !== this.#namespace) {
1109
+ throw new Error(`Replacement link for ${child.child} has the wrong namespace`);
1110
+ }
1111
+ if (this.isRevoked(replacement)) {
1112
+ throw new Error(`Replacement link for ${child.child} has been revoked`);
1113
+ }
1114
+ if (typeof opts.getPublicKey !== 'function') {
1115
+ throw new Error('transfer needs opts.getPublicKey to verify replacement links');
1116
+ }
1117
+ let ok = false;
1118
+ try {
1119
+ ok = await replacement.verifyBoth(
1120
+ await opts.getPublicKey(replacement.parent),
1121
+ await opts.getPublicKey(replacement.child),
1122
+ { acceptLegacyV2: this.#acceptLegacyV2 }
1123
+ );
1124
+ } catch {
1125
+ ok = false;
728
1126
  }
1127
+ if (!ok) {
1128
+ throw new Error(`Replacement link for ${child.child}: signature verification failed`);
1129
+ }
1130
+ plan.push({ child, replacement });
1131
+ }
1132
+
1133
+ // Every replacement verified: now mutate.
1134
+ for (const { child, replacement } of plan) {
1135
+ this.unlink(primaryId, child.child);
1136
+ if (replacement) this.#links.push(replacement);
1137
+ affected++;
729
1138
  }
730
- affected++;
731
1139
  }
732
1140
  } else if (policy.action === 'revoke') {
733
1141
  for (const child of children) {
@@ -779,34 +1187,53 @@ export class MeshKeyring {
779
1187
  // -- Serialization ------------------------------------------------------
780
1188
 
781
1189
  /**
782
- * Serialize all links.
1190
+ * Serialize the keyring.
1191
+ *
1192
+ * Shape (since 0.10): `{ v: 3, namespace, links, revocations }`. Before
1193
+ * 0.10 this was a bare array of links; {@link MeshKeyring.fromJSON} still
1194
+ * reads that. An older browsermesh-core given the new object fails to
1195
+ * load it (it is not iterable) rather than misreading revocations as links.
783
1196
  *
784
- * @returns {object[]}
1197
+ * @returns {{ v: 3, namespace: string|null, links: object[], revocations: object[] }}
785
1198
  */
786
1199
  toJSON() {
787
- return this.#links.map((l) => l.toJSON());
1200
+ return {
1201
+ v: 3,
1202
+ namespace: this.#namespace,
1203
+ links: this.#links.map((l) => l.toJSON()),
1204
+ revocations: this.#revocations.map((r) => r.toJSON()),
1205
+ };
788
1206
  }
789
1207
 
790
1208
  /**
791
- * Deserialize from an array of link data.
1209
+ * Deserialize a keyring.
1210
+ *
1211
+ * Accepts the current object form and the pre-0.10 bare array of links.
1212
+ * Signatures are not re-checked here (no keys are available); they are
1213
+ * checked by {@link MeshKeyring#verifyCryptoChain}. Recorded revocations
1214
+ * are restored as-is: a revocation can only remove authority, so trusting
1215
+ * the local copy fails closed.
792
1216
  *
793
- * @param {object[]} data
1217
+ * @param {object|object[]} data
1218
+ * @param {object} [opts] - Constructor options (`storage`, `namespace`,
1219
+ * `acceptLegacyV2`). `namespace` defaults to the serialised one and
1220
+ * must agree with it when both are given.
794
1221
  * @returns {MeshKeyring}
795
1222
  */
796
- static fromJSON(data) {
797
- const kr = new MeshKeyring();
798
- for (const d of data) {
1223
+ static fromJSON(data, opts = {}) {
1224
+ const legacy = Array.isArray(data);
1225
+ const links = legacy ? data : (data?.links ?? []);
1226
+ const revocations = legacy ? [] : (data?.revocations ?? []);
1227
+ const storedNs = legacy ? null : (data?.namespace ?? null);
1228
+ if (!legacy && 'namespace' in opts && (opts.namespace ?? null) !== storedNs) {
1229
+ throw new Error('Namespace mismatch between options and serialised keyring');
1230
+ }
1231
+ const kr = new MeshKeyring({ ...opts, namespace: opts.namespace ?? storedNs });
1232
+ for (const d of links) {
799
1233
  /*
800
1234
  * 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.
1235
+ * `KeyLink.fromJSON` returned a plain KeyLink for signed links too, so
1236
+ * a restored keyring verified without any cryptography (#33).
810
1237
  */
811
1238
  kr.#links.push(
812
1239
  d && (d.parentSignature || d.childSignature || d.signed)
@@ -814,6 +1241,9 @@ export class MeshKeyring {
814
1241
  : KeyLink.fromJSON(d)
815
1242
  );
816
1243
  }
1244
+ for (const r of revocations) {
1245
+ kr.#revocations.push(SignedKeyUnlink.fromJSON(r));
1246
+ }
817
1247
  return kr;
818
1248
  }
819
1249
  }