@johnhenry/browsermesh-core 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +42 -0
- package/package.json +32 -0
- package/src/acl.mjs +530 -0
- package/src/capabilities.mjs +852 -0
- package/src/compat.mjs +29 -0
- package/src/group-keys.mjs +610 -0
- package/src/handshake.mjs +760 -0
- package/src/hardening.mjs +1183 -0
- package/src/identity-base.mjs +491 -0
- package/src/identity-tools.mjs +383 -0
- package/src/identity-wallet.mjs +505 -0
- package/src/identity.mjs +1349 -0
- package/src/index.mjs +15 -0
- package/src/keyring.mjs +741 -0
- package/src/peer-tools.mjs +959 -0
- package/src/peer.mjs +391 -0
- package/src/silent-catch.mjs +55 -0
- package/src/trust.mjs +425 -0
package/src/compat.mjs
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* compat.mjs -- BrowserTool shim for standalone use.
|
|
3
|
+
*
|
|
4
|
+
* In clawser, BrowserTool is the base class for AI-agent-callable tools.
|
|
5
|
+
* Subclasses override name/description/parameters/permission as GETTERS
|
|
6
|
+
* (not constructor-assigned properties) — this shim mirrors that exactly
|
|
7
|
+
* (see web/clawser-tools.js). An earlier version of this shim tried to
|
|
8
|
+
* assign `this.name = ...` in the constructor, which threw
|
|
9
|
+
* "Cannot set property name of #<Tool> which has only a getter" for
|
|
10
|
+
* every real subclass, since none of them define a setter.
|
|
11
|
+
*/
|
|
12
|
+
export class BrowserTool {
|
|
13
|
+
/** @returns {object} ToolSpec-compatible object */
|
|
14
|
+
get spec() {
|
|
15
|
+
return {
|
|
16
|
+
name: this.name,
|
|
17
|
+
description: this.description,
|
|
18
|
+
parameters: this.parameters,
|
|
19
|
+
required_permission: this.permission,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
get name() { throw new Error('implement name'); }
|
|
24
|
+
get description() { throw new Error('implement description'); }
|
|
25
|
+
get parameters() { return { type: 'object', properties: {} }; }
|
|
26
|
+
get permission() { return 'internal'; }
|
|
27
|
+
|
|
28
|
+
async execute(_params) { throw new Error('Not implemented'); }
|
|
29
|
+
}
|
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* clawser-mesh-group-keys.js -- Symmetric group encryption for multi-party sessions.
|
|
3
|
+
*
|
|
4
|
+
* Epoch-based key rotation with AES-GCM-256. Forward secrecy on member removal
|
|
5
|
+
* by generating a new epoch key and distributing it only to remaining members.
|
|
6
|
+
*
|
|
7
|
+
* Wire handlers: 0x80-0x83 (GROUP_KEY_DISTRIBUTE, GROUP_KEY_ROTATE,
|
|
8
|
+
* GROUP_KEY_REQUEST, GROUP_KEY_ACK).
|
|
9
|
+
*
|
|
10
|
+
* No browser-only imports at module level.
|
|
11
|
+
*
|
|
12
|
+
* Run tests:
|
|
13
|
+
* node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-group-keys.test.mjs
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
// Wire constants
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
export const GROUP_KEY_DISTRIBUTE = 0x80
|
|
21
|
+
export const GROUP_KEY_ROTATE = 0x81
|
|
22
|
+
export const GROUP_KEY_REQUEST = 0x82
|
|
23
|
+
export const GROUP_KEY_ACK = 0x83
|
|
24
|
+
|
|
25
|
+
// ---------------------------------------------------------------------------
|
|
26
|
+
// Per-member envelope encryption (X25519 ECDH + AES-GCM key wrap)
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Whether this environment's WebCrypto supports X25519 ECDH, required for
|
|
31
|
+
* per-member envelope encryption. Older browsers only support P-256/P-384
|
|
32
|
+
* ECDH — group key distribution falls back to metadata-only (current
|
|
33
|
+
* behavior) when this is false.
|
|
34
|
+
* @returns {boolean}
|
|
35
|
+
*/
|
|
36
|
+
export function supportsX25519() {
|
|
37
|
+
return typeof crypto !== 'undefined' && !!crypto.subtle
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function bytesToB64(bytes) {
|
|
41
|
+
let bin = ''
|
|
42
|
+
for (const b of bytes) bin += String.fromCharCode(b)
|
|
43
|
+
return btoa(bin)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function b64ToBytes(b64) {
|
|
47
|
+
const bin = atob(b64)
|
|
48
|
+
const bytes = new Uint8Array(bin.length)
|
|
49
|
+
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
|
50
|
+
return bytes
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Generate a fresh X25519 keypair for group-key envelope encryption.
|
|
55
|
+
* This is a SEPARATE keypair from a pod's Ed25519 signing identity — X25519
|
|
56
|
+
* is for key agreement (ECDH), Ed25519 for signatures; they're different
|
|
57
|
+
* curves with different WebCrypto algorithm identifiers.
|
|
58
|
+
*
|
|
59
|
+
* @returns {Promise<CryptoKeyPair>}
|
|
60
|
+
*/
|
|
61
|
+
export async function generateEncryptionKeyPair() {
|
|
62
|
+
return crypto.subtle.generateKey({ name: 'X25519' }, true, ['deriveKey', 'deriveBits'])
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Wrap an AES-GCM epoch key for one recipient using ECDH + AES-GCM key
|
|
67
|
+
* wrap. Uses a fresh ephemeral X25519 keypair per envelope (ECIES-style) —
|
|
68
|
+
* the sender's long-term private key is never used directly, so a single
|
|
69
|
+
* envelope's compromise doesn't expose other envelopes.
|
|
70
|
+
*
|
|
71
|
+
* @param {CryptoKey} epochKey - The AES-GCM key to protect (must be extractable)
|
|
72
|
+
* @param {CryptoKey} recipientPublicKey - Recipient's X25519 public key
|
|
73
|
+
* @returns {Promise<{ephemeralPublicKey: string, wrappedKey: string, iv: string}>} base64-encoded
|
|
74
|
+
*/
|
|
75
|
+
export async function wrapKeyForMember(epochKey, recipientPublicKey) {
|
|
76
|
+
const ephemeral = await generateEncryptionKeyPair()
|
|
77
|
+
const sharedKek = await crypto.subtle.deriveKey(
|
|
78
|
+
{ name: 'X25519', public: recipientPublicKey },
|
|
79
|
+
ephemeral.privateKey,
|
|
80
|
+
{ name: 'AES-GCM', length: 256 },
|
|
81
|
+
false,
|
|
82
|
+
['wrapKey'],
|
|
83
|
+
)
|
|
84
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
85
|
+
const wrapped = await crypto.subtle.wrapKey('raw', epochKey, sharedKek, { name: 'AES-GCM', iv })
|
|
86
|
+
const ephemeralPublicRaw = new Uint8Array(await crypto.subtle.exportKey('raw', ephemeral.publicKey))
|
|
87
|
+
return {
|
|
88
|
+
ephemeralPublicKey: bytesToB64(ephemeralPublicRaw),
|
|
89
|
+
wrappedKey: bytesToB64(new Uint8Array(wrapped)),
|
|
90
|
+
iv: bytesToB64(iv),
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Unwrap an epoch key envelope using this member's X25519 private key.
|
|
96
|
+
*
|
|
97
|
+
* @param {{ephemeralPublicKey: string, wrappedKey: string, iv: string}} envelope - base64-encoded
|
|
98
|
+
* @param {CryptoKey} recipientPrivateKey - This member's X25519 private key
|
|
99
|
+
* @returns {Promise<CryptoKey>} The unwrapped AES-GCM epoch key
|
|
100
|
+
*/
|
|
101
|
+
export async function unwrapKeyForMember(envelope, recipientPrivateKey) {
|
|
102
|
+
const ephemeralPublicRaw = b64ToBytes(envelope.ephemeralPublicKey)
|
|
103
|
+
const ephemeralPublicKey = await crypto.subtle.importKey('raw', ephemeralPublicRaw, { name: 'X25519' }, true, [])
|
|
104
|
+
const sharedKek = await crypto.subtle.deriveKey(
|
|
105
|
+
{ name: 'X25519', public: ephemeralPublicKey },
|
|
106
|
+
recipientPrivateKey,
|
|
107
|
+
{ name: 'AES-GCM', length: 256 },
|
|
108
|
+
false,
|
|
109
|
+
['unwrapKey'],
|
|
110
|
+
)
|
|
111
|
+
const wrapped = b64ToBytes(envelope.wrappedKey)
|
|
112
|
+
const iv = b64ToBytes(envelope.iv)
|
|
113
|
+
return crypto.subtle.unwrapKey(
|
|
114
|
+
'raw', wrapped, sharedKek, { name: 'AES-GCM', iv },
|
|
115
|
+
{ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'],
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
// GroupState — tracks a single epoch
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Represents a single epoch's group key state.
|
|
125
|
+
*/
|
|
126
|
+
export class GroupState {
|
|
127
|
+
/** @type {number} */
|
|
128
|
+
#epoch
|
|
129
|
+
|
|
130
|
+
/** @type {CryptoKey|null} */
|
|
131
|
+
#key
|
|
132
|
+
|
|
133
|
+
/** @type {Set<string>} */
|
|
134
|
+
#members
|
|
135
|
+
|
|
136
|
+
/** @type {number} */
|
|
137
|
+
#createdAt
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* @param {object} opts
|
|
141
|
+
* @param {number} opts.epoch
|
|
142
|
+
* @param {CryptoKey|null} opts.key
|
|
143
|
+
* @param {string[]} opts.members
|
|
144
|
+
* @param {number} [opts.createdAt]
|
|
145
|
+
*/
|
|
146
|
+
constructor({ epoch, key, members, createdAt = Date.now() }) {
|
|
147
|
+
if (typeof epoch !== 'number' || epoch < 0) {
|
|
148
|
+
throw new Error('epoch must be a non-negative number')
|
|
149
|
+
}
|
|
150
|
+
this.#epoch = epoch
|
|
151
|
+
this.#key = key
|
|
152
|
+
this.#members = new Set(members)
|
|
153
|
+
this.#createdAt = createdAt
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
get epoch() { return this.#epoch }
|
|
157
|
+
get key() { return this.#key }
|
|
158
|
+
get members() { return [...this.#members] }
|
|
159
|
+
get memberCount() { return this.#members.size }
|
|
160
|
+
get createdAt() { return this.#createdAt }
|
|
161
|
+
|
|
162
|
+
hasMember(podId) { return this.#members.has(podId) }
|
|
163
|
+
|
|
164
|
+
toJSON() {
|
|
165
|
+
return {
|
|
166
|
+
epoch: this.#epoch,
|
|
167
|
+
members: [...this.#members],
|
|
168
|
+
createdAt: this.#createdAt,
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ---------------------------------------------------------------------------
|
|
174
|
+
// GroupKeyManager
|
|
175
|
+
// ---------------------------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Manages symmetric group keys with epoch-based rotation.
|
|
179
|
+
* Each epoch has a unique AES-GCM-256 key shared by all group members.
|
|
180
|
+
* On member removal, a new epoch is created for forward secrecy.
|
|
181
|
+
*/
|
|
182
|
+
export class GroupKeyManager {
|
|
183
|
+
/** @type {string} */
|
|
184
|
+
#localPodId
|
|
185
|
+
|
|
186
|
+
/** @type {string} */
|
|
187
|
+
#groupId
|
|
188
|
+
|
|
189
|
+
/** @type {Map<number, GroupState>} epoch -> GroupState */
|
|
190
|
+
#epochs = new Map()
|
|
191
|
+
|
|
192
|
+
/** @type {number} */
|
|
193
|
+
#currentEpoch = -1
|
|
194
|
+
|
|
195
|
+
/** @type {number} */
|
|
196
|
+
#maxEpochHistory
|
|
197
|
+
|
|
198
|
+
/** @type {function|null} */
|
|
199
|
+
#broadcastFn = null
|
|
200
|
+
|
|
201
|
+
/** @type {CryptoKeyPair|null} This pod's X25519 keypair for envelope encryption */
|
|
202
|
+
#encryptionKeyPair = null
|
|
203
|
+
|
|
204
|
+
/** @type {Map<string, CryptoKey>} podId -> X25519 public key */
|
|
205
|
+
#memberPublicKeys = new Map()
|
|
206
|
+
|
|
207
|
+
/** @type {boolean} Warn once when falling back to metadata-only distribution */
|
|
208
|
+
#warnedNoEnvelope = false
|
|
209
|
+
|
|
210
|
+
/** @type {function|null} */
|
|
211
|
+
#onLog
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* @param {object} opts
|
|
215
|
+
* @param {string} opts.localPodId
|
|
216
|
+
* @param {string} opts.groupId
|
|
217
|
+
* @param {number} [opts.maxEpochHistory=10]
|
|
218
|
+
* @param {function} [opts.onLog]
|
|
219
|
+
*/
|
|
220
|
+
constructor({ localPodId, groupId, maxEpochHistory = 10, onLog } = {}) {
|
|
221
|
+
if (!localPodId) throw new Error('localPodId is required')
|
|
222
|
+
if (!groupId) throw new Error('groupId is required')
|
|
223
|
+
this.#localPodId = localPodId
|
|
224
|
+
this.#groupId = groupId
|
|
225
|
+
this.#maxEpochHistory = maxEpochHistory
|
|
226
|
+
this.#onLog = onLog || null
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
get localPodId() { return this.#localPodId }
|
|
230
|
+
get groupId() { return this.#groupId }
|
|
231
|
+
get currentEpoch() { return this.#currentEpoch }
|
|
232
|
+
get epochCount() { return this.#epochs.size }
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Generate (or regenerate) this pod's X25519 keypair used to receive
|
|
236
|
+
* per-member group-key envelopes. Must be called before this pod can
|
|
237
|
+
* be sent an encrypted envelope by other members — advertise the
|
|
238
|
+
* returned public key via peer discovery/registry metadata.
|
|
239
|
+
*
|
|
240
|
+
* @returns {Promise<string|null>} base64 raw public key, or null when
|
|
241
|
+
* X25519 is unsupported in this environment.
|
|
242
|
+
*/
|
|
243
|
+
async initEncryption() {
|
|
244
|
+
if (!supportsX25519()) {
|
|
245
|
+
this.#encryptionKeyPair = null
|
|
246
|
+
return null
|
|
247
|
+
}
|
|
248
|
+
this.#encryptionKeyPair = await generateEncryptionKeyPair()
|
|
249
|
+
return this.getPublicKeyRaw()
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* This pod's own X25519 public key, base64-encoded, for advertising to
|
|
254
|
+
* other members so they can encrypt envelopes addressed to this pod.
|
|
255
|
+
* @returns {Promise<string|null>}
|
|
256
|
+
*/
|
|
257
|
+
async getPublicKeyRaw() {
|
|
258
|
+
if (!this.#encryptionKeyPair) return null
|
|
259
|
+
const raw = new Uint8Array(await crypto.subtle.exportKey('raw', this.#encryptionKeyPair.publicKey))
|
|
260
|
+
return bytesToB64(raw)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Register another member's X25519 public key so envelopes can be
|
|
265
|
+
* addressed to them in `broadcastDistribute`.
|
|
266
|
+
*
|
|
267
|
+
* @param {string} podId
|
|
268
|
+
* @param {string|Uint8Array} publicKeyRaw - base64 string or raw bytes
|
|
269
|
+
*/
|
|
270
|
+
async setMemberPublicKey(podId, publicKeyRaw) {
|
|
271
|
+
const raw = typeof publicKeyRaw === 'string' ? b64ToBytes(publicKeyRaw) : publicKeyRaw
|
|
272
|
+
const key = await crypto.subtle.importKey('raw', raw, { name: 'X25519' }, true, [])
|
|
273
|
+
this.#memberPublicKeys.set(podId, key)
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** @param {string} podId @returns {boolean} */
|
|
277
|
+
hasMemberPublicKey(podId) {
|
|
278
|
+
return this.#memberPublicKeys.has(podId)
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
#log(msg) {
|
|
282
|
+
if (this.#onLog) this.#onLog(msg)
|
|
283
|
+
else if (typeof console !== 'undefined') console.warn(`[GroupKeyManager] ${msg}`)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Get the current group state.
|
|
288
|
+
* @returns {GroupState|null}
|
|
289
|
+
*/
|
|
290
|
+
getCurrentState() {
|
|
291
|
+
return this.#epochs.get(this.#currentEpoch) || null
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Get a specific epoch's state.
|
|
296
|
+
* @param {number} epoch
|
|
297
|
+
* @returns {GroupState|null}
|
|
298
|
+
*/
|
|
299
|
+
getEpochState(epoch) {
|
|
300
|
+
return this.#epochs.get(epoch) || null
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Initialize a new group with the given members.
|
|
305
|
+
* Generates the first epoch key (epoch 0).
|
|
306
|
+
*
|
|
307
|
+
* @param {string[]} members - Pod IDs of initial members
|
|
308
|
+
* @returns {Promise<GroupState>}
|
|
309
|
+
*/
|
|
310
|
+
async initGroup(members) {
|
|
311
|
+
if (!Array.isArray(members) || members.length === 0) {
|
|
312
|
+
throw new Error('members must be a non-empty array')
|
|
313
|
+
}
|
|
314
|
+
// Ensure localPodId is included
|
|
315
|
+
const allMembers = new Set(members)
|
|
316
|
+
allMembers.add(this.#localPodId)
|
|
317
|
+
|
|
318
|
+
const key = await this.#generateKey()
|
|
319
|
+
const epoch = 0
|
|
320
|
+
const state = new GroupState({
|
|
321
|
+
epoch,
|
|
322
|
+
key,
|
|
323
|
+
members: [...allMembers],
|
|
324
|
+
})
|
|
325
|
+
|
|
326
|
+
this.#epochs.set(epoch, state)
|
|
327
|
+
this.#currentEpoch = epoch
|
|
328
|
+
return state
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Rotate the group key to a new epoch.
|
|
333
|
+
* Used when adding a member (existing key is fine, but new epoch
|
|
334
|
+
* ensures clean key lifecycle) or periodically for key freshness.
|
|
335
|
+
*
|
|
336
|
+
* @param {string[]} [newMembers] - Updated member list; defaults to current members
|
|
337
|
+
* @returns {Promise<GroupState>}
|
|
338
|
+
*/
|
|
339
|
+
async rotate(newMembers) {
|
|
340
|
+
const current = this.getCurrentState()
|
|
341
|
+
const members = newMembers || (current ? current.members : [this.#localPodId])
|
|
342
|
+
|
|
343
|
+
const nextEpoch = this.#currentEpoch + 1
|
|
344
|
+
const key = await this.#generateKey()
|
|
345
|
+
const state = new GroupState({
|
|
346
|
+
epoch: nextEpoch,
|
|
347
|
+
key,
|
|
348
|
+
members,
|
|
349
|
+
})
|
|
350
|
+
|
|
351
|
+
this.#epochs.set(nextEpoch, state)
|
|
352
|
+
this.#currentEpoch = nextEpoch
|
|
353
|
+
this.#pruneOldEpochs()
|
|
354
|
+
return state
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Remove a member and rotate the key for forward secrecy.
|
|
359
|
+
* The removed member will not receive the new epoch key.
|
|
360
|
+
*
|
|
361
|
+
* @param {string} podId - Pod ID to remove
|
|
362
|
+
* @returns {Promise<GroupState>}
|
|
363
|
+
*/
|
|
364
|
+
async removeMember(podId) {
|
|
365
|
+
const current = this.getCurrentState()
|
|
366
|
+
if (!current) throw new Error('No active group state')
|
|
367
|
+
if (!current.hasMember(podId)) throw new Error(`${podId} is not a member`)
|
|
368
|
+
|
|
369
|
+
const remaining = current.members.filter(m => m !== podId)
|
|
370
|
+
if (remaining.length === 0) throw new Error('Cannot remove the last member')
|
|
371
|
+
|
|
372
|
+
return this.rotate(remaining)
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Add a member and rotate the key.
|
|
377
|
+
*
|
|
378
|
+
* @param {string} podId - Pod ID to add
|
|
379
|
+
* @returns {Promise<GroupState>}
|
|
380
|
+
*/
|
|
381
|
+
async addMember(podId) {
|
|
382
|
+
const current = this.getCurrentState()
|
|
383
|
+
if (!current) throw new Error('No active group state')
|
|
384
|
+
if (current.hasMember(podId)) throw new Error(`${podId} is already a member`)
|
|
385
|
+
|
|
386
|
+
const updated = [...current.members, podId]
|
|
387
|
+
return this.rotate(updated)
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Encrypt data with the current epoch key.
|
|
392
|
+
*
|
|
393
|
+
* @param {Uint8Array} plaintext
|
|
394
|
+
* @returns {Promise<{ ciphertext: Uint8Array, iv: Uint8Array, epoch: number }>}
|
|
395
|
+
*/
|
|
396
|
+
async encrypt(plaintext) {
|
|
397
|
+
const state = this.getCurrentState()
|
|
398
|
+
if (!state || !state.key) throw new Error('No active group key')
|
|
399
|
+
|
|
400
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
401
|
+
const ciphertext = new Uint8Array(
|
|
402
|
+
await crypto.subtle.encrypt(
|
|
403
|
+
{ name: 'AES-GCM', iv },
|
|
404
|
+
state.key,
|
|
405
|
+
plaintext,
|
|
406
|
+
),
|
|
407
|
+
)
|
|
408
|
+
|
|
409
|
+
return { ciphertext, iv, epoch: state.epoch }
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Decrypt data using the specified epoch key.
|
|
414
|
+
*
|
|
415
|
+
* @param {Uint8Array} ciphertext
|
|
416
|
+
* @param {Uint8Array} iv
|
|
417
|
+
* @param {number} epoch
|
|
418
|
+
* @returns {Promise<Uint8Array>}
|
|
419
|
+
*/
|
|
420
|
+
async decrypt(ciphertext, iv, epoch) {
|
|
421
|
+
const state = this.#epochs.get(epoch)
|
|
422
|
+
if (!state || !state.key) throw new Error(`No key for epoch ${epoch}`)
|
|
423
|
+
|
|
424
|
+
const plaintext = new Uint8Array(
|
|
425
|
+
await crypto.subtle.decrypt(
|
|
426
|
+
{ name: 'AES-GCM', iv },
|
|
427
|
+
state.key,
|
|
428
|
+
ciphertext,
|
|
429
|
+
),
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
return plaintext
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Accept an epoch key distributed by another member.
|
|
437
|
+
*
|
|
438
|
+
* @param {number} epoch
|
|
439
|
+
* @param {CryptoKey} key
|
|
440
|
+
* @param {string[]} members
|
|
441
|
+
*/
|
|
442
|
+
acceptEpoch(epoch, key, members) {
|
|
443
|
+
if (this.#epochs.has(epoch)) return // already have it
|
|
444
|
+
|
|
445
|
+
const state = new GroupState({ epoch, key, members })
|
|
446
|
+
this.#epochs.set(epoch, state)
|
|
447
|
+
if (epoch > this.#currentEpoch) {
|
|
448
|
+
this.#currentEpoch = epoch
|
|
449
|
+
}
|
|
450
|
+
this.#pruneOldEpochs()
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Wire the GroupKeyManager to a mesh transport layer.
|
|
455
|
+
*
|
|
456
|
+
* @param {function} broadcastFn - `(wireType: number, payload: object) => void`
|
|
457
|
+
* @param {function} subscribeFn - `(wireType: number, handler: (payload, fromPodId) => void) => void`
|
|
458
|
+
*/
|
|
459
|
+
wireTransport(broadcastFn, subscribeFn) {
|
|
460
|
+
if (typeof broadcastFn !== 'function' || typeof subscribeFn !== 'function') {
|
|
461
|
+
throw new Error('broadcastFn and subscribeFn must be functions')
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
this.#broadcastFn = broadcastFn
|
|
465
|
+
|
|
466
|
+
// Inbound: key distribution from group owner/rotator
|
|
467
|
+
subscribeFn(GROUP_KEY_DISTRIBUTE, (payload, fromPodId) => {
|
|
468
|
+
const { epoch, members, groupId, envelopes } = payload
|
|
469
|
+
if (groupId !== this.#groupId) return
|
|
470
|
+
if (!members?.includes(this.#localPodId)) return
|
|
471
|
+
|
|
472
|
+
const envelope = envelopes?.[this.#localPodId]
|
|
473
|
+
if (!envelope) {
|
|
474
|
+
// Metadata-only broadcast (sender had no known public key for us,
|
|
475
|
+
// or X25519 unsupported somewhere in the group) — no key material
|
|
476
|
+
// to accept. The member must fall back to broadcastRequest() once
|
|
477
|
+
// its own public key has been advertised/registered.
|
|
478
|
+
return
|
|
479
|
+
}
|
|
480
|
+
if (!this.#encryptionKeyPair) {
|
|
481
|
+
this.#log(`received envelope for epoch ${epoch} but local encryption key is not initialized (call initEncryption() first)`)
|
|
482
|
+
return
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
unwrapKeyForMember(envelope, this.#encryptionKeyPair.privateKey)
|
|
486
|
+
.then(key => this.acceptEpoch(epoch, key, members))
|
|
487
|
+
.catch(err => this.#log(`failed to unwrap epoch ${epoch} envelope: ${err.message}`))
|
|
488
|
+
})
|
|
489
|
+
|
|
490
|
+
// Inbound: key rotation notification
|
|
491
|
+
subscribeFn(GROUP_KEY_ROTATE, (payload, fromPodId) => {
|
|
492
|
+
const { epoch, members, groupId } = payload
|
|
493
|
+
if (groupId !== this.#groupId) return
|
|
494
|
+
// Rotation accepted — key delivered via GROUP_KEY_DISTRIBUTE
|
|
495
|
+
})
|
|
496
|
+
|
|
497
|
+
// Inbound: key request (member asking for the current key)
|
|
498
|
+
subscribeFn(GROUP_KEY_REQUEST, (payload, fromPodId) => {
|
|
499
|
+
const { groupId } = payload
|
|
500
|
+
if (groupId !== this.#groupId) return
|
|
501
|
+
const current = this.getCurrentState()
|
|
502
|
+
if (current && current.hasMember(fromPodId)) {
|
|
503
|
+
// Respond with key distribution
|
|
504
|
+
this.broadcastDistribute().catch(err => this.#log(`broadcastDistribute failed: ${err.message}`))
|
|
505
|
+
}
|
|
506
|
+
})
|
|
507
|
+
|
|
508
|
+
// Inbound: acknowledgment of key receipt
|
|
509
|
+
subscribeFn(GROUP_KEY_ACK, (payload, fromPodId) => {
|
|
510
|
+
// Track which members have acknowledged the key
|
|
511
|
+
})
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Broadcast the current epoch key to all members. When this pod's
|
|
516
|
+
* encryption keypair is initialized and at least one other member's
|
|
517
|
+
* public key is known, wraps the epoch key per-member (X25519 ECDH +
|
|
518
|
+
* AES-GCM). Members with no known public key (or when X25519 is
|
|
519
|
+
* unsupported) simply receive metadata and must catch up via
|
|
520
|
+
* broadcastRequest() once their key is registered — a logged warning
|
|
521
|
+
* marks this fallback so it's visible, not silent.
|
|
522
|
+
*/
|
|
523
|
+
async broadcastDistribute() {
|
|
524
|
+
if (!this.#broadcastFn) return
|
|
525
|
+
const state = this.getCurrentState()
|
|
526
|
+
if (!state) return
|
|
527
|
+
|
|
528
|
+
const canEnvelope = supportsX25519() && !!this.#encryptionKeyPair
|
|
529
|
+
let envelopes
|
|
530
|
+
if (canEnvelope) {
|
|
531
|
+
const targets = state.members.filter(m => m !== this.#localPodId && this.#memberPublicKeys.has(m))
|
|
532
|
+
if (targets.length > 0) {
|
|
533
|
+
envelopes = {}
|
|
534
|
+
for (const podId of targets) {
|
|
535
|
+
envelopes[podId] = await wrapKeyForMember(state.key, this.#memberPublicKeys.get(podId))
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
if (!envelopes && !this.#warnedNoEnvelope) {
|
|
541
|
+
this.#warnedNoEnvelope = true
|
|
542
|
+
this.#log(canEnvelope
|
|
543
|
+
? 'no member public keys registered — distributing epoch metadata only (members must request the key once registered)'
|
|
544
|
+
: 'X25519 unsupported or local encryption key not initialized — distributing epoch metadata only')
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
this.#broadcastFn(GROUP_KEY_DISTRIBUTE, {
|
|
548
|
+
groupId: this.#groupId,
|
|
549
|
+
epoch: state.epoch,
|
|
550
|
+
members: state.members,
|
|
551
|
+
...(envelopes ? { envelopes } : {}),
|
|
552
|
+
})
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Broadcast a rotation notification.
|
|
557
|
+
*/
|
|
558
|
+
broadcastRotation() {
|
|
559
|
+
if (!this.#broadcastFn) return
|
|
560
|
+
const state = this.getCurrentState()
|
|
561
|
+
if (!state) return
|
|
562
|
+
|
|
563
|
+
this.#broadcastFn(GROUP_KEY_ROTATE, {
|
|
564
|
+
groupId: this.#groupId,
|
|
565
|
+
epoch: state.epoch,
|
|
566
|
+
members: state.members,
|
|
567
|
+
})
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* Broadcast a key request.
|
|
572
|
+
*/
|
|
573
|
+
broadcastRequest() {
|
|
574
|
+
if (!this.#broadcastFn) return
|
|
575
|
+
this.#broadcastFn(GROUP_KEY_REQUEST, { groupId: this.#groupId })
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* Broadcast a key acknowledgment.
|
|
580
|
+
*
|
|
581
|
+
* @param {number} epoch
|
|
582
|
+
*/
|
|
583
|
+
broadcastAck(epoch) {
|
|
584
|
+
if (!this.#broadcastFn) return
|
|
585
|
+
this.#broadcastFn(GROUP_KEY_ACK, {
|
|
586
|
+
groupId: this.#groupId,
|
|
587
|
+
epoch,
|
|
588
|
+
podId: this.#localPodId,
|
|
589
|
+
})
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// -- Internal helpers -----------------------------------------------------
|
|
593
|
+
|
|
594
|
+
async #generateKey() {
|
|
595
|
+
return crypto.subtle.generateKey(
|
|
596
|
+
{ name: 'AES-GCM', length: 256 },
|
|
597
|
+
true,
|
|
598
|
+
['encrypt', 'decrypt'],
|
|
599
|
+
)
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
#pruneOldEpochs() {
|
|
603
|
+
if (this.#epochs.size <= this.#maxEpochHistory) return
|
|
604
|
+
const sorted = [...this.#epochs.keys()].sort((a, b) => a - b)
|
|
605
|
+
const toRemove = sorted.slice(0, sorted.length - this.#maxEpochHistory)
|
|
606
|
+
for (const epoch of toRemove) {
|
|
607
|
+
this.#epochs.delete(epoch)
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|