@johnhenry/browsermesh-discovery 0.0.6 → 0.2.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 +30 -0
- package/package.json +1 -1
- package/src/stealth.mjs +194 -21
package/README.md
CHANGED
|
@@ -41,6 +41,36 @@ npm install @johnhenry/browsermesh-discovery @johnhenry/browsermesh-primitives
|
|
|
41
41
|
import { DhtNode, DiscoveryManager, SwarmCoordinator } from '@johnhenry/browsermesh-discovery';
|
|
42
42
|
```
|
|
43
43
|
|
|
44
|
+
## `StealthAgent` is sharding; encryption is opt-in
|
|
45
|
+
|
|
46
|
+
For secrecy, derive a per-group key and use the async encrypted path:
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
const key = await deriveStealthKey(groupSecret, 'my-group'); // HKDF-SHA-256 -> AES-256-GCM
|
|
50
|
+
const agent = new StealthAgent({ agentId, dhtNode, key });
|
|
51
|
+
await agent.hideEncrypted(state); // shard holders see only ciphertext
|
|
52
|
+
const state = await agent.reconstituteEncrypted();
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
The payload is bound to the agent id and a wrong key or any tampering rejects.
|
|
56
|
+
Not done yet (tracked in #230): threshold sharing of the key, signed shards,
|
|
57
|
+
agent-anonymous DHT keys, a real checksum and multi-loss parity. The plain
|
|
58
|
+
`hide()` / `reconstitute()` below are unchanged and plaintext:
|
|
59
|
+
|
|
60
|
+
`StealthAgent.hide(stateString)` / `reconstitute()` split a state string into
|
|
61
|
+
`threshold` plaintext data shards plus XOR parity shards and store them in the
|
|
62
|
+
DHT under `stealth:<agentId>:shard:<i>`. It improves availability, not secrecy:
|
|
63
|
+
|
|
64
|
+
- the shards contain the state verbatim (data shards) or its XOR (parity);
|
|
65
|
+
anyone who can read the DHT entries can read the state;
|
|
66
|
+
- every parity shard is the same XOR of all data chunks, so the state survives
|
|
67
|
+
the loss of **one** data shard, not `total - threshold` of them;
|
|
68
|
+
- the checksum detects accidental corruption only, not tampering;
|
|
69
|
+
- the keys name the agent they hold state for.
|
|
70
|
+
|
|
71
|
+
If the state is sensitive, encrypt it before `hide()` and decrypt after
|
|
72
|
+
`reconstitute()`; this package does not manage keys.
|
|
73
|
+
|
|
44
74
|
## License
|
|
45
75
|
|
|
46
76
|
MIT
|
package/package.json
CHANGED
package/src/stealth.mjs
CHANGED
|
@@ -1,10 +1,33 @@
|
|
|
1
1
|
/**
|
|
2
2
|
// STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
|
|
3
|
-
* clawser-mesh-stealth.js --
|
|
3
|
+
* clawser-mesh-stealth.js -- Agent state sharding across the DHT.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* NOT ENCRYPTED, NOT ANONYMOUS. This module splits a state string into
|
|
6
|
+
* `threshold` plaintext data shards plus `total - threshold` XOR parity shards
|
|
7
|
+
* and stores them in the DHT under keys derived from the agent id
|
|
8
|
+
* (`stealth:<agentId>:shard:<i>`). It gives availability, not secrecy:
|
|
9
|
+
*
|
|
10
|
+
* - shard data is the state itself (data shards) or the XOR of it (parity);
|
|
11
|
+
* anyone who can read the DHT entries can read the state;
|
|
12
|
+
* - the parity shards are all identical (the XOR of every data chunk), so
|
|
13
|
+
* the scheme survives the loss of exactly ONE data shard, not `total -
|
|
14
|
+
* threshold`;
|
|
15
|
+
* - the shard checksum is a sum of char codes: it catches corruption, not
|
|
16
|
+
* tampering;
|
|
17
|
+
* - keys name the agent they belong to.
|
|
18
|
+
*
|
|
19
|
+
* For secrecy use the opt-in encrypted path: derive a per-group AES-256-GCM key
|
|
20
|
+
* with `deriveStealthKey(groupSecret, groupId)` and call
|
|
21
|
+
* `StealthAgent#hideEncrypted()` / `#reconstituteEncrypted()` (async). The
|
|
22
|
+
* state is sealed before sharding, bound to the agent id, so shard holders see
|
|
23
|
+
* only ciphertext. That is the first half of #230; threshold sharing of the
|
|
24
|
+
* key, signed shards and agent-anonymous DHT keys are NOT done (see the issue).
|
|
25
|
+
* The plain synchronous `hide()` / `reconstitute()` are unchanged and plaintext.
|
|
26
|
+
*
|
|
27
|
+
* StateShard represents one fragment.
|
|
28
|
+
* ShardDistributor scatters shards across DHT nodes.
|
|
29
|
+
* ShardCollector retrieves and reconstructs state from DHT.
|
|
30
|
+
* StealthAgent orchestrates the hide/reconstitute lifecycle.
|
|
8
31
|
*
|
|
9
32
|
* StateShard represents an erasure-coded fragment.
|
|
10
33
|
* ShardDistributor scatters shards across DHT nodes.
|
|
@@ -17,7 +40,92 @@
|
|
|
17
40
|
* node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-dht.test.mjs
|
|
18
41
|
*/
|
|
19
42
|
|
|
20
|
-
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
// Payload encryption (AES-256-GCM)
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
|
|
47
|
+
const ENC_PREFIX = 'v1.'
|
|
48
|
+
const IV_BYTES = 12
|
|
49
|
+
|
|
50
|
+
function toBase64Url(bytes) {
|
|
51
|
+
let bin = ''
|
|
52
|
+
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i])
|
|
53
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function fromBase64Url(str) {
|
|
57
|
+
const b64 = str.replace(/-/g, '+').replace(/_/g, '/')
|
|
58
|
+
const bin = atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4))
|
|
59
|
+
const out = new Uint8Array(bin.length)
|
|
60
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
|
|
61
|
+
return out
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Derive the AES-256-GCM key for one discovery group from a secret every group
|
|
66
|
+
* member holds (HKDF-SHA-256, `groupId` as salt). Members of the same group
|
|
67
|
+
* derive the same key; another group, or a different secret, cannot.
|
|
68
|
+
*
|
|
69
|
+
* @param {Uint8Array|string} groupSecret - At least 16 bytes of shared secret
|
|
70
|
+
* @param {string} groupId
|
|
71
|
+
* @returns {Promise<CryptoKey>}
|
|
72
|
+
*/
|
|
73
|
+
export async function deriveStealthKey(groupSecret, groupId) {
|
|
74
|
+
if (!groupId || typeof groupId !== 'string') throw new Error('groupId is required and must be a non-empty string')
|
|
75
|
+
const raw = typeof groupSecret === 'string' ? new TextEncoder().encode(groupSecret) : groupSecret
|
|
76
|
+
if (!(raw instanceof Uint8Array) || raw.length < 16) throw new Error('groupSecret must be at least 16 bytes')
|
|
77
|
+
const base = await crypto.subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey'])
|
|
78
|
+
return crypto.subtle.deriveKey(
|
|
79
|
+
{ name: 'HKDF', hash: 'SHA-256', salt: new TextEncoder().encode(`browsermesh-stealth:${groupId}`), info: new TextEncoder().encode('aes-256-gcm') },
|
|
80
|
+
base,
|
|
81
|
+
{ name: 'AES-GCM', length: 256 },
|
|
82
|
+
false,
|
|
83
|
+
['encrypt', 'decrypt'],
|
|
84
|
+
)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Seal a state string: `v1.` + base64url(iv || ciphertext+tag), a fresh random
|
|
89
|
+
* IV per call, `agentId` as additional authenticated data.
|
|
90
|
+
*
|
|
91
|
+
* @param {string} state
|
|
92
|
+
* @param {CryptoKey} key
|
|
93
|
+
* @param {string} agentId
|
|
94
|
+
* @returns {Promise<string>}
|
|
95
|
+
*/
|
|
96
|
+
export async function encryptStealthState(state, key, agentId) {
|
|
97
|
+
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES))
|
|
98
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt(
|
|
99
|
+
{ name: 'AES-GCM', iv, additionalData: new TextEncoder().encode(agentId) },
|
|
100
|
+
key,
|
|
101
|
+
new TextEncoder().encode(state),
|
|
102
|
+
))
|
|
103
|
+
const out = new Uint8Array(IV_BYTES + ct.length)
|
|
104
|
+
out.set(iv, 0)
|
|
105
|
+
out.set(ct, IV_BYTES)
|
|
106
|
+
return ENC_PREFIX + toBase64Url(out)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Open a payload produced by `encryptStealthState`. Rejects on a wrong key,
|
|
111
|
+
* wrong agent id, or any modification.
|
|
112
|
+
*
|
|
113
|
+
* @param {string} payload
|
|
114
|
+
* @param {CryptoKey} key
|
|
115
|
+
* @param {string} agentId
|
|
116
|
+
* @returns {Promise<string>}
|
|
117
|
+
*/
|
|
118
|
+
export async function decryptStealthState(payload, key, agentId) {
|
|
119
|
+
if (typeof payload !== 'string' || !payload.startsWith(ENC_PREFIX)) throw new Error('not an encrypted stealth payload')
|
|
120
|
+
const bytes = fromBase64Url(payload.slice(ENC_PREFIX.length))
|
|
121
|
+
if (bytes.length <= IV_BYTES) throw new Error('encrypted stealth payload is truncated')
|
|
122
|
+
const pt = await crypto.subtle.decrypt(
|
|
123
|
+
{ name: 'AES-GCM', iv: bytes.slice(0, IV_BYTES), additionalData: new TextEncoder().encode(agentId) },
|
|
124
|
+
key,
|
|
125
|
+
bytes.slice(IV_BYTES),
|
|
126
|
+
)
|
|
127
|
+
return new TextDecoder().decode(pt)
|
|
128
|
+
}
|
|
21
129
|
|
|
22
130
|
// ---------------------------------------------------------------------------
|
|
23
131
|
// Checksum Helper
|
|
@@ -41,7 +149,8 @@ function simpleChecksum(data) {
|
|
|
41
149
|
// ---------------------------------------------------------------------------
|
|
42
150
|
|
|
43
151
|
/**
|
|
44
|
-
*
|
|
152
|
+
* One fragment of sharded agent state: a plaintext slice of the state (data
|
|
153
|
+
* shard) or the XOR of all slices (parity shard). Not encrypted.
|
|
45
154
|
*/
|
|
46
155
|
export class StateShard {
|
|
47
156
|
/** @type {string} */
|
|
@@ -305,7 +414,13 @@ export class ShardCollector {
|
|
|
305
414
|
}
|
|
306
415
|
|
|
307
416
|
/**
|
|
308
|
-
* Reconstruct original state from
|
|
417
|
+
* Reconstruct the original state from at least `threshold` valid shards.
|
|
418
|
+
*
|
|
419
|
+
* All `threshold` data shards are used when present. If exactly one data
|
|
420
|
+
* shard is missing and a parity shard is available, the missing chunk is
|
|
421
|
+
* recovered as parity XOR the other chunks. Two or more missing data
|
|
422
|
+
* shards cannot be recovered (every parity shard carries the same XOR).
|
|
423
|
+
*
|
|
309
424
|
* @param {StateShard[]} shards - At least `threshold` valid shards
|
|
310
425
|
* @returns {string} Reconstructed state blob
|
|
311
426
|
*/
|
|
@@ -321,20 +436,42 @@ export class ShardCollector {
|
|
|
321
436
|
return idxA - idxB
|
|
322
437
|
})
|
|
323
438
|
|
|
324
|
-
//
|
|
325
|
-
const
|
|
439
|
+
// Data shards by index; parity shards (index >= threshold) separately
|
|
440
|
+
const byIndex = new Map()
|
|
441
|
+
let parity = null
|
|
442
|
+
for (const s of sorted) {
|
|
326
443
|
const idx = parseInt(s.shardId.split(':').pop(), 10)
|
|
327
|
-
|
|
328
|
-
|
|
444
|
+
if (idx < this.#threshold) byIndex.set(idx, s.data)
|
|
445
|
+
else if (!parity) parity = s.data
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const missing = []
|
|
449
|
+
for (let i = 0; i < this.#threshold; i++) {
|
|
450
|
+
if (!byIndex.has(i)) missing.push(i)
|
|
451
|
+
}
|
|
329
452
|
|
|
330
|
-
if (
|
|
331
|
-
throw new Error(
|
|
453
|
+
if (missing.length > 1 || (missing.length === 1 && parity === null)) {
|
|
454
|
+
throw new Error(
|
|
455
|
+
`Not enough data shards for reconstruction: need ${this.#threshold}, got ${this.#threshold - missing.length}` +
|
|
456
|
+
' (parity can recover at most one missing data shard)',
|
|
457
|
+
)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
if (missing.length === 1) {
|
|
461
|
+
// parity = XOR of every data chunk, so the missing chunk is parity XOR the rest
|
|
462
|
+
let recovered = ''
|
|
463
|
+
for (let c = 0; c < parity.length; c++) {
|
|
464
|
+
let xorVal = parity.charCodeAt(c)
|
|
465
|
+
for (const data of byIndex.values()) xorVal ^= data.charCodeAt(c)
|
|
466
|
+
recovered += String.fromCharCode(xorVal)
|
|
467
|
+
}
|
|
468
|
+
byIndex.set(missing[0], recovered)
|
|
332
469
|
}
|
|
333
470
|
|
|
334
|
-
// Concatenate data chunks
|
|
471
|
+
// Concatenate data chunks in order
|
|
335
472
|
let result = ''
|
|
336
|
-
for (
|
|
337
|
-
result +=
|
|
473
|
+
for (let i = 0; i < this.#threshold; i++) {
|
|
474
|
+
result += byIndex.get(i)
|
|
338
475
|
}
|
|
339
476
|
|
|
340
477
|
// Remove null padding
|
|
@@ -358,9 +495,15 @@ export class ShardCollector {
|
|
|
358
495
|
// ---------------------------------------------------------------------------
|
|
359
496
|
|
|
360
497
|
/**
|
|
361
|
-
* Orchestrates the hide/reconstitute lifecycle for
|
|
362
|
-
*
|
|
363
|
-
*
|
|
498
|
+
* Orchestrates the hide/reconstitute lifecycle for an agent's state.
|
|
499
|
+
*
|
|
500
|
+
* State is sharded across the DHT as plaintext data shards plus XOR parity
|
|
501
|
+
* (see the module header): it can be reconstructed from `threshold` shards
|
|
502
|
+
* (so one lost data shard is tolerated) but it is NOT encrypted and the shard
|
|
503
|
+
* keys name the agent. Encrypt the state before `hide()` if it is sensitive.
|
|
504
|
+
*
|
|
505
|
+
* Methods are `hide(stateBlob)`, `reconstitute()`, `isViable()` and
|
|
506
|
+
* `getManifest()`; they are synchronous.
|
|
364
507
|
*/
|
|
365
508
|
export class StealthAgent {
|
|
366
509
|
/** @type {string} */
|
|
@@ -384,17 +527,22 @@ export class StealthAgent {
|
|
|
384
527
|
/** @type {object|null} */
|
|
385
528
|
#manifest = null
|
|
386
529
|
|
|
530
|
+
/** @type {CryptoKey|null} */
|
|
531
|
+
#key = null
|
|
532
|
+
|
|
387
533
|
/**
|
|
388
534
|
* @param {object} opts
|
|
389
535
|
* @param {string} opts.agentId - Agent identifier
|
|
390
536
|
* @param {import('./clawser-mesh-dht.js').DhtNode} opts.dhtNode - DHT node
|
|
391
537
|
* @param {number} [opts.threshold=3] - Minimum shards for recovery
|
|
392
538
|
* @param {number} [opts.totalShards=5] - Total shards to create
|
|
539
|
+
* @param {CryptoKey} [opts.key] - AES-GCM key (see `deriveStealthKey`); enables `hideEncrypted()` / `reconstituteEncrypted()`
|
|
393
540
|
*/
|
|
394
|
-
constructor({ agentId, dhtNode, threshold = 3, totalShards = 5 }) {
|
|
541
|
+
constructor({ agentId, dhtNode, threshold = 3, totalShards = 5, key = null }) {
|
|
395
542
|
if (!agentId || typeof agentId !== 'string') {
|
|
396
543
|
throw new Error('agentId is required and must be a non-empty string')
|
|
397
544
|
}
|
|
545
|
+
this.#key = key
|
|
398
546
|
this.#agentId = agentId
|
|
399
547
|
this.#dhtNode = dhtNode
|
|
400
548
|
this.#threshold = threshold
|
|
@@ -404,7 +552,8 @@ export class StealthAgent {
|
|
|
404
552
|
}
|
|
405
553
|
|
|
406
554
|
/**
|
|
407
|
-
*
|
|
555
|
+
* Distribute the agent's state as shards across the DHT. This is sharding,
|
|
556
|
+
* not concealment: the shards are plaintext slices of `stateBlob`.
|
|
408
557
|
* @param {string} stateBlob - State data to hide
|
|
409
558
|
* @returns {object} Manifest with shard keys and metadata
|
|
410
559
|
*/
|
|
@@ -422,6 +571,30 @@ export class StealthAgent {
|
|
|
422
571
|
return this.#manifest
|
|
423
572
|
}
|
|
424
573
|
|
|
574
|
+
/**
|
|
575
|
+
* Like `hide()`, but seals the state with AES-GCM first, so the DHT holds
|
|
576
|
+
* only ciphertext. Requires the `key` option.
|
|
577
|
+
* @param {string} stateBlob
|
|
578
|
+
* @returns {Promise<object>} Manifest (`encrypted: true`)
|
|
579
|
+
*/
|
|
580
|
+
async hideEncrypted(stateBlob) {
|
|
581
|
+
if (!this.#key) throw new Error('hideEncrypted requires a key (see deriveStealthKey)')
|
|
582
|
+
const sealed = await encryptStealthState(stateBlob, this.#key, this.#agentId)
|
|
583
|
+
this.hide(sealed)
|
|
584
|
+
this.#manifest = { ...this.#manifest, encrypted: true }
|
|
585
|
+
return this.#manifest
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Reconstitute and decrypt state stored by `hideEncrypted()`. Rejects when
|
|
590
|
+
* the key is wrong or the shards were altered. Requires the `key` option.
|
|
591
|
+
* @returns {Promise<string>}
|
|
592
|
+
*/
|
|
593
|
+
async reconstituteEncrypted() {
|
|
594
|
+
if (!this.#key) throw new Error('reconstituteEncrypted requires a key (see deriveStealthKey)')
|
|
595
|
+
return decryptStealthState(this.reconstitute(), this.#key, this.#agentId)
|
|
596
|
+
}
|
|
597
|
+
|
|
425
598
|
/**
|
|
426
599
|
* Reconstitute the agent's state from DHT shards.
|
|
427
600
|
* @returns {string} Reconstructed state blob
|