@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/README.md +44 -1
- package/package.json +1 -1
- package/src/canonical.mjs +62 -0
- package/src/capabilities.mjs +158 -2
- package/src/keyring.mjs +667 -125
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,49 @@ 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
|
+
- 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.
|
|
82
|
+
- `executeSuccession(primary, { links, getPublicKey })` with a `transfer`
|
|
83
|
+
policy needs successor-signed replacement links (`{ localOnly: true }` keeps
|
|
84
|
+
the old unsigned behaviour).
|
|
85
|
+
- Before a capability chain crosses peers, sign it (`CapabilityToken.issue`,
|
|
86
|
+
`token.attenuateSigned`) and check it on arrival with
|
|
87
|
+
`chain.verifySignatures(getPublicKey, { rootIssuer })`.
|
|
88
|
+
|
|
89
|
+
**Migrating links signed before 0.10 (v2 payload).** They no longer verify by
|
|
90
|
+
default. To migrate, load them into a keyring with `{ acceptLegacyV2: true }`
|
|
91
|
+
(verification only, never for signing), find them with
|
|
92
|
+
`link.signatureVersion(parentPub, childPub) === 2`, and re-sign each with
|
|
93
|
+
`link.resign(parentIdentity, childIdentity, { namespace })`. v1
|
|
94
|
+
(`a|b|c|d`) signatures are no longer accepted at all; re-create those links.
|
|
95
|
+
|
|
53
96
|
## Padding group-key envelopes
|
|
54
97
|
|
|
55
98
|
`GroupKeyManager.encrypt()` leaks the exact plaintext length to anything that
|
package/package.json
CHANGED
|
@@ -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
|
+
}
|
package/src/capabilities.mjs
CHANGED
|
@@ -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
|
-
*
|
|
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(
|
|
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];
|