@johnhenry/browsermesh-discovery 0.1.0 → 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 CHANGED
@@ -41,7 +41,21 @@ 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, not encryption
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:
45
59
 
46
60
  `StealthAgent.hide(stateString)` / `reconstitute()` split a state string into
47
61
  `threshold` plaintext data shards plus XOR parity shards and store them in the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-discovery",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "DHT, peer discovery, naming, swarm coordination, and stealth networking for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/stealth.mjs CHANGED
@@ -16,8 +16,13 @@
16
16
  * tampering;
17
17
  * - keys name the agent they belong to.
18
18
  *
19
- * If the state must be secret, encrypt it yourself before calling `hide()`
20
- * (and decrypt after `reconstitute()`); this module does not manage keys.
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.
21
26
  *
22
27
  * StateShard represents one fragment.
23
28
  * ShardDistributor scatters shards across DHT nodes.
@@ -35,6 +40,93 @@
35
40
  * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-dht.test.mjs
36
41
  */
37
42
 
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
+ }
129
+
38
130
  // ---------------------------------------------------------------------------
39
131
  // Checksum Helper
40
132
  // ---------------------------------------------------------------------------
@@ -435,17 +527,22 @@ export class StealthAgent {
435
527
  /** @type {object|null} */
436
528
  #manifest = null
437
529
 
530
+ /** @type {CryptoKey|null} */
531
+ #key = null
532
+
438
533
  /**
439
534
  * @param {object} opts
440
535
  * @param {string} opts.agentId - Agent identifier
441
536
  * @param {import('./clawser-mesh-dht.js').DhtNode} opts.dhtNode - DHT node
442
537
  * @param {number} [opts.threshold=3] - Minimum shards for recovery
443
538
  * @param {number} [opts.totalShards=5] - Total shards to create
539
+ * @param {CryptoKey} [opts.key] - AES-GCM key (see `deriveStealthKey`); enables `hideEncrypted()` / `reconstituteEncrypted()`
444
540
  */
445
- constructor({ agentId, dhtNode, threshold = 3, totalShards = 5 }) {
541
+ constructor({ agentId, dhtNode, threshold = 3, totalShards = 5, key = null }) {
446
542
  if (!agentId || typeof agentId !== 'string') {
447
543
  throw new Error('agentId is required and must be a non-empty string')
448
544
  }
545
+ this.#key = key
449
546
  this.#agentId = agentId
450
547
  this.#dhtNode = dhtNode
451
548
  this.#threshold = threshold
@@ -474,6 +571,30 @@ export class StealthAgent {
474
571
  return this.#manifest
475
572
  }
476
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
+
477
598
  /**
478
599
  * Reconstitute the agent's state from DHT shards.
479
600
  * @returns {string} Reconstructed state blob