@johnhenry/browsermesh-core 0.6.0 → 0.7.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
@@ -50,6 +50,24 @@ npm install @johnhenry/browsermesh-core @johnhenry/browsermesh-primitives
50
50
  import { MeshIdentityManager, MeshKeyring, TrustGraph } from '@johnhenry/browsermesh-core';
51
51
  ```
52
52
 
53
+ ## Padding group-key envelopes
54
+
55
+ `GroupKeyManager.encrypt()` leaks the exact plaintext length to anything that
56
+ sees the ciphertext (a relay, for instance). Pass `padding` to round the
57
+ plaintext up to a size bucket before sealing it:
58
+
59
+ ```js
60
+ const { ciphertext, iv, epoch } = await keys.encrypt(bytes, { padding: true });
61
+ const back = await keys.decrypt(ciphertext, iv, epoch, { padding: true });
62
+ ```
63
+
64
+ `padding: true` uses buckets of 256 / 1024 / 4096 / 16384 bytes (larger
65
+ payloads round up to a multiple of 16384); `{ buckets: [...] }` picks your own;
66
+ `new GroupKeyManager({ ..., padding })` sets the default. Ciphertexts are then
67
+ `bucket + 16` bytes. Sender and receiver must agree on the setting (the padded
68
+ plaintext is not self-describing). Off by default; no cover traffic or timing
69
+ protection is provided.
70
+
53
71
  ## License
54
72
 
55
73
  MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-core",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Identity, crypto, peer management, and trust primitives for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -13,6 +13,18 @@
13
13
  * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-group-keys.test.mjs
14
14
  */
15
15
 
16
+ // Namespace import, not `import { padTo, unpad }`: padding needs primitives >= 0.3.0,
17
+ // but this package's peer range still admits 0.2.x, and a missing named export
18
+ // would fail to link (breaking all of core) instead of only breaking `padding`.
19
+ import * as primitives from '@johnhenry/browsermesh-primitives'
20
+
21
+ function paddingFns() {
22
+ if (typeof primitives.padTo !== 'function' || typeof primitives.unpad !== 'function') {
23
+ throw new Error('padding requires @johnhenry/browsermesh-primitives >= 0.3.0')
24
+ }
25
+ return primitives
26
+ }
27
+
16
28
  // ---------------------------------------------------------------------------
17
29
  // Wire constants
18
30
  // ---------------------------------------------------------------------------
@@ -227,6 +239,17 @@ export class GroupState {
227
239
  // GroupKeyManager
228
240
  // ---------------------------------------------------------------------------
229
241
 
242
+ /**
243
+ * @param {boolean|{ buckets?: number[] }|null|undefined} padding
244
+ * @returns {false|{ buckets?: number[] }}
245
+ */
246
+ function normalizePadding(padding) {
247
+ if (!padding) return false
248
+ if (padding === true) return {}
249
+ if (typeof padding === 'object') return { buckets: padding.buckets }
250
+ throw new TypeError('padding must be a boolean or { buckets }')
251
+ }
252
+
230
253
  /**
231
254
  * Manages symmetric group keys with epoch-based rotation.
232
255
  * Each epoch has a unique AES-GCM-256 key shared by all group members.
@@ -263,20 +286,26 @@ export class GroupKeyManager {
263
286
  /** @type {function|null} */
264
287
  #onLog
265
288
 
289
+ /** @type {false|{ buckets?: number[] }} Default padding for encrypt()/decrypt() */
290
+ #padding
291
+
266
292
  /**
267
293
  * @param {object} opts
268
294
  * @param {string} opts.localPodId
269
295
  * @param {string} opts.groupId
270
296
  * @param {number} [opts.maxEpochHistory=10]
271
297
  * @param {function} [opts.onLog]
298
+ * @param {boolean|{ buckets?: number[] }} [opts.padding=false] - Default for
299
+ * the `padding` option of `encrypt()`/`decrypt()`. Off unless set.
272
300
  */
273
- constructor({ localPodId, groupId, maxEpochHistory = 10, onLog } = {}) {
301
+ constructor({ localPodId, groupId, maxEpochHistory = 10, onLog, padding = false } = {}) {
274
302
  if (!localPodId) throw new Error('localPodId is required')
275
303
  if (!groupId) throw new Error('groupId is required')
276
304
  this.#localPodId = localPodId
277
305
  this.#groupId = groupId
278
306
  this.#maxEpochHistory = maxEpochHistory
279
307
  this.#onLog = onLog || null
308
+ this.#padding = normalizePadding(padding)
280
309
  }
281
310
 
282
311
  get localPodId() { return this.#localPodId }
@@ -498,19 +527,32 @@ export class GroupKeyManager {
498
527
  /**
499
528
  * Encrypt data with the current epoch key.
500
529
  *
530
+ * With `padding` on, the plaintext is rounded up to a size bucket (see
531
+ * `padTo()` in `@johnhenry/browsermesh-primitives`) BEFORE sealing, so a
532
+ * relay that only sees ciphertext learns the bucket, not the exact length:
533
+ * the ciphertext is always `bucket + 16` bytes (the AES-GCM tag). Every
534
+ * receiver must decrypt with the same `padding` setting. Off by default.
535
+ *
501
536
  * @param {Uint8Array} plaintext
537
+ * @param {object} [opts]
538
+ * @param {boolean|{ buckets?: number[] }} [opts.padding] - Overrides the
539
+ * constructor default; `true` uses the default buckets
540
+ * (256/1024/4096/16384), `{ buckets }` custom ones.
502
541
  * @returns {Promise<{ ciphertext: Uint8Array, iv: Uint8Array, epoch: number }>}
503
542
  */
504
- async encrypt(plaintext) {
543
+ async encrypt(plaintext, { padding } = {}) {
505
544
  const state = this.getCurrentState()
506
545
  if (!state || !state.key) throw new Error('No active group key')
507
546
 
547
+ const pad = padding === undefined ? this.#padding : normalizePadding(padding)
548
+ const sealed = pad ? paddingFns().padTo(plaintext, pad) : plaintext
549
+
508
550
  const iv = crypto.getRandomValues(new Uint8Array(12))
509
551
  const ciphertext = new Uint8Array(
510
552
  await crypto.subtle.encrypt(
511
553
  { name: 'AES-GCM', iv },
512
554
  state.key,
513
- plaintext,
555
+ sealed,
514
556
  ),
515
557
  )
516
558
 
@@ -523,9 +565,13 @@ export class GroupKeyManager {
523
565
  * @param {Uint8Array} ciphertext
524
566
  * @param {Uint8Array} iv
525
567
  * @param {number} epoch
568
+ * @param {object} [opts]
569
+ * @param {boolean|{ buckets?: number[] }} [opts.padding] - Must match the
570
+ * sender's `encrypt()` setting: when on, the padding is stripped after
571
+ * decryption. Overrides the constructor default.
526
572
  * @returns {Promise<Uint8Array>}
527
573
  */
528
- async decrypt(ciphertext, iv, epoch) {
574
+ async decrypt(ciphertext, iv, epoch, { padding } = {}) {
529
575
  const state = this.#epochs.get(epoch)
530
576
  if (!state || !state.key) throw new Error(`No key for epoch ${epoch}`)
531
577
 
@@ -537,7 +583,8 @@ export class GroupKeyManager {
537
583
  ),
538
584
  )
539
585
 
540
- return plaintext
586
+ const pad = padding === undefined ? this.#padding : normalizePadding(padding)
587
+ return pad ? paddingFns().unpad(plaintext) : plaintext
541
588
  }
542
589
 
543
590
  /**
@@ -560,9 +560,14 @@ export class TimestampProofTool extends BrowserTool {
560
560
 
561
561
  // ── Stealth tools ─────────────────────────────────────────────────────
562
562
 
563
+ // The agent is a `StealthAgent` from @johnhenry/browsermesh-discovery:
564
+ // `hide(stateString)` / `reconstitute()`. It shards the state across the DHT
565
+ // as plaintext slices plus XOR parity. There is NO encryption, so these tools
566
+ // say so; encrypt the state first if it is sensitive.
567
+
563
568
  export class StealthSaveTool extends BrowserTool {
564
569
  get name() { return 'stealth_save' }
565
- get description() { return 'Save agent state as threshold-encrypted shards distributed across the DHT.' }
570
+ get description() { return 'Save agent state as XOR-parity shards distributed across the DHT. The shards are NOT encrypted: anyone who can read the DHT entries can read the state.' }
566
571
  get parameters() {
567
572
  return {
568
573
  type: 'object',
@@ -578,8 +583,11 @@ export class StealthSaveTool extends BrowserTool {
578
583
  const agent = peerToolsContext.getStealthAgent()
579
584
  if (!agent) return { success: false, output: '', error: 'Stealth agent not initialized.' }
580
585
  try {
581
- await agent.saveState(state)
582
- return { success: true, output: 'State saved as distributed shards.' }
586
+ const manifest = typeof agent.hide === 'function'
587
+ ? await agent.hide(JSON.stringify(state))
588
+ : await agent.saveState(state) // duck-typed agent from before the tool matched StealthAgent
589
+ const shards = manifest?.shardIds?.length
590
+ return { success: true, output: `State saved as ${shards ?? ''}${shards ? ' ' : ''}unencrypted distributed shards.` }
583
591
  } catch (err) {
584
592
  return { success: false, output: '', error: err.message }
585
593
  }
@@ -588,7 +596,7 @@ export class StealthSaveTool extends BrowserTool {
588
596
 
589
597
  export class StealthRestoreTool extends BrowserTool {
590
598
  get name() { return 'stealth_restore' }
591
- get description() { return 'Restore agent state from threshold-encrypted DHT shards.' }
599
+ get description() { return 'Restore agent state from XOR-parity shards in the DHT (shards are not encrypted).' }
592
600
  get parameters() { return { type: 'object', properties: {} } }
593
601
  get permission() { return 'approve' }
594
602
 
@@ -596,7 +604,14 @@ export class StealthRestoreTool extends BrowserTool {
596
604
  const agent = peerToolsContext.getStealthAgent()
597
605
  if (!agent) return { success: false, output: '', error: 'Stealth agent not initialized.' }
598
606
  try {
599
- const state = await agent.restoreState()
607
+ if (typeof agent.reconstitute === 'function') {
608
+ if (typeof agent.isViable === 'function' && !agent.isViable()) {
609
+ return { success: true, output: 'No state found.' }
610
+ }
611
+ const blob = await agent.reconstitute()
612
+ return { success: true, output: blob ? blob : 'No state found.' }
613
+ }
614
+ const state = await agent.restoreState() // duck-typed agent from before the tool matched StealthAgent
600
615
  return { success: true, output: state ? JSON.stringify(state) : 'No state found.' }
601
616
  } catch (err) {
602
617
  return { success: false, output: '', error: err.message }