@johnhenry/browsermesh-core 0.5.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 +18 -0
- package/package.json +1 -1
- package/src/group-keys.mjs +52 -5
- package/src/peer-tools.mjs +120 -20
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
package/src/group-keys.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
586
|
+
const pad = padding === undefined ? this.#padding : normalizePadding(padding)
|
|
587
|
+
return pad ? paddingFns().unpad(plaintext) : plaintext
|
|
541
588
|
}
|
|
542
589
|
|
|
543
590
|
/**
|
package/src/peer-tools.mjs
CHANGED
|
@@ -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
|
|
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
|
-
|
|
582
|
-
|
|
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
|
|
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
|
-
|
|
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 }
|
|
@@ -727,57 +742,121 @@ export class MeshGatewayStatusTool extends BrowserTool {
|
|
|
727
742
|
}
|
|
728
743
|
}
|
|
729
744
|
|
|
745
|
+
// ── Byte/text helpers for the torrent and IPFS tools ──────────────────
|
|
746
|
+
|
|
747
|
+
const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/
|
|
748
|
+
|
|
749
|
+
/** @param {Uint8Array} bytes @returns {string} */
|
|
750
|
+
function bytesToBase64(bytes) {
|
|
751
|
+
let bin = ''
|
|
752
|
+
const STEP = 0x8000
|
|
753
|
+
for (let i = 0; i < bytes.length; i += STEP) {
|
|
754
|
+
bin += String.fromCharCode.apply(null, bytes.subarray(i, i + STEP))
|
|
755
|
+
}
|
|
756
|
+
return btoa(bin)
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* Strict base64 decode: whitespace is ignored, anything else outside the
|
|
761
|
+
* alphabet (or a bad length) throws instead of decoding to garbage.
|
|
762
|
+
* @param {string} str @returns {Uint8Array}
|
|
763
|
+
*/
|
|
764
|
+
function base64ToBytes(str) {
|
|
765
|
+
const clean = String(str).replace(/\s+/g, '')
|
|
766
|
+
if (!BASE64_RE.test(clean) || clean.length % 4 === 1) {
|
|
767
|
+
throw new Error('data is not valid base64 (use encoding "text" for plain text)')
|
|
768
|
+
}
|
|
769
|
+
const bin = atob(clean)
|
|
770
|
+
const bytes = new Uint8Array(bin.length)
|
|
771
|
+
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
|
772
|
+
return bytes
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* The tools' `data` string -> bytes, per its `encoding` ('text' = UTF-8, the
|
|
777
|
+
* default; 'base64').
|
|
778
|
+
* @param {string} data @param {string} [encoding]
|
|
779
|
+
* @returns {Uint8Array}
|
|
780
|
+
*/
|
|
781
|
+
function decodeToolData(data, encoding = 'text') {
|
|
782
|
+
if (typeof data !== 'string') throw new Error('data must be a string')
|
|
783
|
+
if (encoding === 'text') return new TextEncoder().encode(data)
|
|
784
|
+
if (encoding === 'base64') return base64ToBytes(data)
|
|
785
|
+
throw new Error(`unknown encoding "${encoding}" (use "text" or "base64")`)
|
|
786
|
+
}
|
|
787
|
+
|
|
730
788
|
// ── Torrent tools ─────────────────────────────────────────────────────
|
|
731
789
|
|
|
732
790
|
export class TorrentSeedTool extends BrowserTool {
|
|
733
791
|
get name() { return 'torrent_seed' }
|
|
734
|
-
get description() { return 'Seed a file or data via BitTorrent-style P2P distribution.' }
|
|
792
|
+
get description() { return 'Seed a file or data via BitTorrent-style P2P distribution. Returns the magnet URI to hand to peers.' }
|
|
735
793
|
get parameters() {
|
|
736
794
|
return {
|
|
737
795
|
type: 'object',
|
|
738
796
|
properties: {
|
|
739
797
|
name: { type: 'string', description: 'Content name/identifier' },
|
|
740
|
-
data: { type: 'string', description: '
|
|
798
|
+
data: { type: 'string', description: 'Content to seed: plain text, or base64 when encoding is "base64"' },
|
|
799
|
+
encoding: {
|
|
800
|
+
type: 'string',
|
|
801
|
+
enum: ['text', 'base64'],
|
|
802
|
+
description: 'How data is encoded: "text" (UTF-8, default) or "base64" (for binary content)',
|
|
803
|
+
},
|
|
741
804
|
},
|
|
742
805
|
required: ['name', 'data'],
|
|
743
806
|
}
|
|
744
807
|
}
|
|
745
808
|
get permission() { return 'approve' }
|
|
746
809
|
|
|
747
|
-
async execute({ name, data }) {
|
|
810
|
+
async execute({ name, data, encoding = 'text' }) {
|
|
748
811
|
const tm = peerToolsContext.getTorrentManager()
|
|
749
812
|
if (!tm) return { success: false, output: '', error: 'Torrent manager not initialized.' }
|
|
750
813
|
try {
|
|
751
|
-
const
|
|
752
|
-
|
|
814
|
+
const bytes = decodeToolData(data, encoding)
|
|
815
|
+
const result = await tm.seed(bytes, { name })
|
|
816
|
+
const size = result?.size ?? bytes.byteLength
|
|
817
|
+
const id = result?.magnetURI || result?.infoHash || name
|
|
818
|
+
return { success: true, output: `Seeding "${name}" (${size} bytes): ${id}` }
|
|
753
819
|
} catch (err) {
|
|
754
820
|
return { success: false, output: '', error: err.message }
|
|
755
821
|
}
|
|
756
822
|
}
|
|
757
823
|
}
|
|
758
824
|
|
|
759
|
-
// ──
|
|
825
|
+
// ── Content-addressed store tools ─────────────────────────────────────
|
|
826
|
+
//
|
|
827
|
+
// Despite the `ipfs_` names (kept for compatibility), the store behind these
|
|
828
|
+
// is mesh-local with SHA-256 hex CIDs, not the public IPFS network.
|
|
760
829
|
|
|
761
830
|
export class IpfsStoreTool extends BrowserTool {
|
|
762
831
|
get name() { return 'ipfs_store' }
|
|
763
|
-
get description() { return 'Store data in the
|
|
832
|
+
get description() { return 'Store data in the mesh-local content-addressed store; returns its CID (a SHA-256 hex digest, not an IPFS CID). Content is local to this node.' }
|
|
764
833
|
get parameters() {
|
|
765
834
|
return {
|
|
766
835
|
type: 'object',
|
|
767
836
|
properties: {
|
|
768
|
-
data: { type: 'string', description: 'Data to store' },
|
|
837
|
+
data: { type: 'string', description: 'Data to store: plain text, or base64 when encoding is "base64"' },
|
|
838
|
+
encoding: {
|
|
839
|
+
type: 'string',
|
|
840
|
+
enum: ['text', 'base64'],
|
|
841
|
+
description: 'How data is encoded: "text" (UTF-8, default) or "base64" (for binary content)',
|
|
842
|
+
},
|
|
769
843
|
},
|
|
770
844
|
required: ['data'],
|
|
771
845
|
}
|
|
772
846
|
}
|
|
773
847
|
get permission() { return 'write' }
|
|
774
848
|
|
|
775
|
-
async execute({ data }) {
|
|
849
|
+
async execute({ data, encoding = 'text' }) {
|
|
776
850
|
const store = peerToolsContext.getIpfsStore()
|
|
777
851
|
if (!store) return { success: false, output: '', error: 'IPFS store not initialized.' }
|
|
778
852
|
try {
|
|
779
|
-
const
|
|
780
|
-
|
|
853
|
+
const bytes = decodeToolData(data, encoding)
|
|
854
|
+
const added = await store.add(bytes)
|
|
855
|
+
// IPFSStore.add() resolves { cid, size }; tolerate a store that returns just the cid string.
|
|
856
|
+
const cid = typeof added === 'string' ? added : added?.cid
|
|
857
|
+
if (!cid) throw new Error('store did not return a CID')
|
|
858
|
+
const size = (typeof added === 'object' ? added?.size : undefined) ?? bytes.byteLength
|
|
859
|
+
return { success: true, output: `Stored with CID: ${cid} (${size} bytes)` }
|
|
781
860
|
} catch (err) {
|
|
782
861
|
return { success: false, output: '', error: err.message }
|
|
783
862
|
}
|
|
@@ -786,25 +865,46 @@ export class IpfsStoreTool extends BrowserTool {
|
|
|
786
865
|
|
|
787
866
|
export class IpfsRetrieveTool extends BrowserTool {
|
|
788
867
|
get name() { return 'ipfs_retrieve' }
|
|
789
|
-
get description() { return 'Retrieve data from the
|
|
868
|
+
get description() { return 'Retrieve data from the mesh-local content-addressed store by CID. Returns UTF-8 text when the content is text, otherwise base64.' }
|
|
790
869
|
get parameters() {
|
|
791
870
|
return {
|
|
792
871
|
type: 'object',
|
|
793
872
|
properties: {
|
|
794
873
|
cid: { type: 'string', description: 'Content identifier (CID)' },
|
|
874
|
+
encoding: {
|
|
875
|
+
type: 'string',
|
|
876
|
+
enum: ['text', 'base64'],
|
|
877
|
+
description: 'Output encoding. Omit to get text when the content is valid UTF-8 and base64 otherwise; "text" fails on binary content; "base64" always returns base64.',
|
|
878
|
+
},
|
|
795
879
|
},
|
|
796
880
|
required: ['cid'],
|
|
797
881
|
}
|
|
798
882
|
}
|
|
799
883
|
get permission() { return 'read' }
|
|
800
884
|
|
|
801
|
-
async execute({ cid }) {
|
|
885
|
+
async execute({ cid, encoding }) {
|
|
802
886
|
const store = peerToolsContext.getIpfsStore()
|
|
803
887
|
if (!store) return { success: false, output: '', error: 'IPFS store not initialized.' }
|
|
804
888
|
try {
|
|
889
|
+
if (encoding !== undefined && encoding !== 'text' && encoding !== 'base64') {
|
|
890
|
+
throw new Error(`unknown encoding "${encoding}" (use "text" or "base64")`)
|
|
891
|
+
}
|
|
805
892
|
const data = await store.get(cid)
|
|
806
|
-
if (
|
|
807
|
-
return { success: true, output:
|
|
893
|
+
if (data === null || data === undefined) return { success: true, output: `CID ${cid} not found.` }
|
|
894
|
+
if (typeof data === 'string') return { success: true, output: data, encoding: 'text' }
|
|
895
|
+
|
|
896
|
+
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data)
|
|
897
|
+
if (encoding === 'base64') return { success: true, output: bytesToBase64(bytes), encoding: 'base64' }
|
|
898
|
+
try {
|
|
899
|
+
return { success: true, output: new TextDecoder('utf-8', { fatal: true }).decode(bytes), encoding: 'text' }
|
|
900
|
+
} catch {
|
|
901
|
+
if (encoding === 'text') throw new Error('content is not valid UTF-8 text; retry with encoding "base64"')
|
|
902
|
+
return {
|
|
903
|
+
success: true,
|
|
904
|
+
output: `Binary content (${bytes.byteLength} bytes), base64: ${bytesToBase64(bytes)}`,
|
|
905
|
+
encoding: 'base64',
|
|
906
|
+
}
|
|
907
|
+
}
|
|
808
908
|
} catch (err) {
|
|
809
909
|
return { success: false, output: '', error: err.message }
|
|
810
910
|
}
|