@johnhenry/browsermesh-discovery 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.
@@ -0,0 +1,450 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-mesh-stealth.js -- Stealth agent with erasure-coded state sharding.
4
+ *
5
+ * Provides state sharding across the DHT for agent stealth operations.
6
+ * State is split into shards using XOR-based erasure coding, distributed
7
+ * across the DHT, and can be reconstituted from a threshold number of shards.
8
+ *
9
+ * StateShard represents an erasure-coded fragment.
10
+ * ShardDistributor scatters shards across DHT nodes.
11
+ * ShardCollector retrieves and reconstructs state from DHT.
12
+ * StealthAgent orchestrates the hide/reconstitute lifecycle.
13
+ *
14
+ * No browser-only imports at module level.
15
+ *
16
+ * Run tests:
17
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-dht.test.mjs
18
+ */
19
+
20
+ import { STEALTH_SHARD } from './dht.mjs'
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Checksum Helper
24
+ // ---------------------------------------------------------------------------
25
+
26
+ /**
27
+ * Simple checksum: sum of char codes mod 2^32.
28
+ * @param {string} data
29
+ * @returns {number}
30
+ */
31
+ function simpleChecksum(data) {
32
+ let sum = 0
33
+ for (let i = 0; i < data.length; i++) {
34
+ sum = (sum + data.charCodeAt(i)) >>> 0
35
+ }
36
+ return sum
37
+ }
38
+
39
+ // ---------------------------------------------------------------------------
40
+ // StateShard
41
+ // ---------------------------------------------------------------------------
42
+
43
+ /**
44
+ * Erasure-coded fragment of agent state.
45
+ */
46
+ export class StateShard {
47
+ /** @type {string} */
48
+ #shardId
49
+
50
+ /** @type {string} */
51
+ #agentId
52
+
53
+ /** @type {string} */
54
+ #data
55
+
56
+ /** @type {number} */
57
+ #threshold
58
+
59
+ /** @type {number} */
60
+ #total
61
+
62
+ /** @type {number} */
63
+ #checksum
64
+
65
+ /**
66
+ * @param {object} opts
67
+ * @param {string} opts.shardId - Unique shard identifier
68
+ * @param {string} opts.agentId - Agent this shard belongs to
69
+ * @param {string} opts.data - Shard data
70
+ * @param {number} opts.threshold - Minimum shards needed for recovery
71
+ * @param {number} opts.total - Total shards created
72
+ * @param {number} opts.checksum - Checksum of the data
73
+ */
74
+ constructor({ shardId, agentId, data, threshold, total, checksum }) {
75
+ this.#shardId = shardId
76
+ this.#agentId = agentId
77
+ this.#data = data
78
+ this.#threshold = threshold
79
+ this.#total = total
80
+ this.#checksum = checksum
81
+ }
82
+
83
+ /** @returns {string} */
84
+ get shardId() { return this.#shardId }
85
+
86
+ /** @returns {string} */
87
+ get agentId() { return this.#agentId }
88
+
89
+ /** @returns {string} */
90
+ get data() { return this.#data }
91
+
92
+ /** @returns {number} */
93
+ get threshold() { return this.#threshold }
94
+
95
+ /** @returns {number} */
96
+ get total() { return this.#total }
97
+
98
+ /** @returns {number} */
99
+ get checksum() { return this.#checksum }
100
+
101
+ /**
102
+ * Verify the shard by recomputing checksum from data.
103
+ * @returns {boolean}
104
+ */
105
+ verify() {
106
+ return simpleChecksum(this.#data) === this.#checksum
107
+ }
108
+
109
+ /**
110
+ * Serialize to a JSON-safe object.
111
+ * @returns {object}
112
+ */
113
+ toJSON() {
114
+ return {
115
+ shardId: this.#shardId,
116
+ agentId: this.#agentId,
117
+ data: this.#data,
118
+ threshold: this.#threshold,
119
+ total: this.#total,
120
+ checksum: this.#checksum,
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Re-hydrate from a plain object.
126
+ * @param {object} json
127
+ * @returns {StateShard}
128
+ */
129
+ static fromJSON(json) {
130
+ return new StateShard(json)
131
+ }
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // ShardDistributor
136
+ // ---------------------------------------------------------------------------
137
+
138
+ /**
139
+ * Distributes agent state as shards across the DHT.
140
+ */
141
+ export class ShardDistributor {
142
+ /** @type {import('./clawser-mesh-dht.js').DhtNode} */
143
+ #dhtNode
144
+
145
+ /** @type {number} */
146
+ #threshold
147
+
148
+ /** @type {number} */
149
+ #totalShards
150
+
151
+ /**
152
+ * @param {object} opts
153
+ * @param {import('./clawser-mesh-dht.js').DhtNode} opts.dhtNode - DHT node for storage
154
+ * @param {number} [opts.threshold=3] - Minimum shards for recovery
155
+ * @param {number} [opts.totalShards=5] - Total shards to create
156
+ */
157
+ constructor({ dhtNode, threshold = 3, totalShards = 5 }) {
158
+ this.#dhtNode = dhtNode
159
+ this.#threshold = threshold
160
+ this.#totalShards = totalShards
161
+ }
162
+
163
+ /**
164
+ * Distribute agent state as shards into the DHT.
165
+ * @param {string} agentId - Agent identifier
166
+ * @param {string} stateBlob - State data to shard
167
+ * @returns {StateShard[]} Array of created shards
168
+ */
169
+ distribute(agentId, stateBlob) {
170
+ const shards = this.#splitState(agentId, stateBlob, this.#threshold, this.#totalShards)
171
+
172
+ // Store each shard in DHT
173
+ const keys = this.#generateShardKeys(agentId, this.#totalShards)
174
+ for (let i = 0; i < shards.length; i++) {
175
+ this.#dhtNode.store(keys[i], shards[i].toJSON())
176
+ }
177
+
178
+ return shards
179
+ }
180
+
181
+ /**
182
+ * Split state into shards with XOR-based parity.
183
+ *
184
+ * Creates `threshold` data shards by splitting the blob into equal chunks,
185
+ * then creates `total - threshold` parity shards by XOR-ing chunks in rotating fashion.
186
+ *
187
+ * @param {string} agentId
188
+ * @param {string} blob
189
+ * @param {number} threshold
190
+ * @param {number} total
191
+ * @returns {StateShard[]}
192
+ * @private
193
+ */
194
+ #splitState(agentId, blob, threshold, total) {
195
+ const shards = []
196
+ const chunkSize = Math.ceil(blob.length / threshold)
197
+
198
+ // Create data shards
199
+ const chunks = []
200
+ for (let i = 0; i < threshold; i++) {
201
+ const start = i * chunkSize
202
+ const chunk = blob.slice(start, start + chunkSize)
203
+ // Pad chunk to chunkSize with null chars for consistent XOR
204
+ const padded = chunk.padEnd(chunkSize, '\0')
205
+ chunks.push(padded)
206
+
207
+ const shard = new StateShard({
208
+ shardId: `${agentId}:shard:${i}`,
209
+ agentId,
210
+ data: padded,
211
+ threshold,
212
+ total,
213
+ checksum: simpleChecksum(padded),
214
+ })
215
+ shards.push(shard)
216
+ }
217
+
218
+ // Create parity shards by XOR-ing data chunks in rotating fashion
219
+ const parityCount = total - threshold
220
+ for (let p = 0; p < parityCount; p++) {
221
+ let parityData = ''
222
+ for (let c = 0; c < chunkSize; c++) {
223
+ let xorVal = 0
224
+ for (let d = 0; d < threshold; d++) {
225
+ // Rotate: XOR with shifted indices
226
+ const idx = (d + p) % threshold
227
+ xorVal ^= chunks[idx].charCodeAt(c)
228
+ }
229
+ parityData += String.fromCharCode(xorVal)
230
+ }
231
+
232
+ const shard = new StateShard({
233
+ shardId: `${agentId}:shard:${threshold + p}`,
234
+ agentId,
235
+ data: parityData,
236
+ threshold,
237
+ total,
238
+ checksum: simpleChecksum(parityData),
239
+ })
240
+ shards.push(shard)
241
+ }
242
+
243
+ return shards
244
+ }
245
+
246
+ /**
247
+ * Generate deterministic DHT keys for shard storage.
248
+ * @param {string} agentId
249
+ * @param {number} total
250
+ * @returns {string[]}
251
+ * @private
252
+ */
253
+ #generateShardKeys(agentId, total) {
254
+ const keys = []
255
+ for (let i = 0; i < total; i++) {
256
+ keys.push(`stealth:${agentId}:shard:${i}`)
257
+ }
258
+ return keys
259
+ }
260
+ }
261
+
262
+ // ---------------------------------------------------------------------------
263
+ // ShardCollector
264
+ // ---------------------------------------------------------------------------
265
+
266
+ /**
267
+ * Collects and reconstructs agent state from DHT shards.
268
+ */
269
+ export class ShardCollector {
270
+ /** @type {import('./clawser-mesh-dht.js').DhtNode} */
271
+ #dhtNode
272
+
273
+ /** @type {number} */
274
+ #threshold
275
+
276
+ /**
277
+ * @param {object} opts
278
+ * @param {import('./clawser-mesh-dht.js').DhtNode} opts.dhtNode - DHT node for retrieval
279
+ * @param {number} [opts.threshold=3] - Minimum shards needed
280
+ */
281
+ constructor({ dhtNode, threshold = 3 }) {
282
+ this.#dhtNode = dhtNode
283
+ this.#threshold = threshold
284
+ }
285
+
286
+ /**
287
+ * Collect shards from the DHT for a given agent.
288
+ * @param {string} agentId
289
+ * @param {number} totalShards
290
+ * @returns {StateShard[]} Retrieved shards
291
+ */
292
+ collect(agentId, totalShards) {
293
+ const shards = []
294
+ for (let i = 0; i < totalShards; i++) {
295
+ const key = `stealth:${agentId}:shard:${i}`
296
+ const value = this.#dhtNode.get(key)
297
+ if (value) {
298
+ const shard = value instanceof StateShard ? value : StateShard.fromJSON(value)
299
+ if (shard.verify()) {
300
+ shards.push(shard)
301
+ }
302
+ }
303
+ }
304
+ return shards
305
+ }
306
+
307
+ /**
308
+ * Reconstruct original state from data shards (first `threshold` shards).
309
+ * @param {StateShard[]} shards - At least `threshold` valid shards
310
+ * @returns {string} Reconstructed state blob
311
+ */
312
+ reconstruct(shards) {
313
+ if (shards.length < this.#threshold) {
314
+ throw new Error(`Need at least ${this.#threshold} shards, got ${shards.length}`)
315
+ }
316
+
317
+ // Sort shards by their index to get data shards in order
318
+ const sorted = [...shards].sort((a, b) => {
319
+ const idxA = parseInt(a.shardId.split(':').pop(), 10)
320
+ const idxB = parseInt(b.shardId.split(':').pop(), 10)
321
+ return idxA - idxB
322
+ })
323
+
324
+ // Use only the data shards (first threshold shards by index)
325
+ const dataShards = sorted.filter(s => {
326
+ const idx = parseInt(s.shardId.split(':').pop(), 10)
327
+ return idx < this.#threshold
328
+ })
329
+
330
+ if (dataShards.length < this.#threshold) {
331
+ throw new Error(`Not enough data shards for reconstruction: need ${this.#threshold}, got ${dataShards.length}`)
332
+ }
333
+
334
+ // Concatenate data chunks and trim null padding
335
+ let result = ''
336
+ for (const shard of dataShards) {
337
+ result += shard.data
338
+ }
339
+
340
+ // Remove null padding
341
+ return result.replace(/\0+$/, '')
342
+ }
343
+
344
+ /**
345
+ * Probe how many valid shards are available for an agent.
346
+ * @param {string} agentId
347
+ * @param {number} totalShards
348
+ * @returns {number} Count of available valid shards
349
+ */
350
+ probe(agentId, totalShards) {
351
+ const shards = this.collect(agentId, totalShards)
352
+ return shards.length
353
+ }
354
+ }
355
+
356
+ // ---------------------------------------------------------------------------
357
+ // StealthAgent
358
+ // ---------------------------------------------------------------------------
359
+
360
+ /**
361
+ * Orchestrates the hide/reconstitute lifecycle for a stealth agent.
362
+ * State is sharded across the DHT and can be reconstructed from
363
+ * a threshold number of shards.
364
+ */
365
+ export class StealthAgent {
366
+ /** @type {string} */
367
+ #agentId
368
+
369
+ /** @type {import('./clawser-mesh-dht.js').DhtNode} */
370
+ #dhtNode
371
+
372
+ /** @type {number} */
373
+ #threshold
374
+
375
+ /** @type {number} */
376
+ #totalShards
377
+
378
+ /** @type {ShardDistributor} */
379
+ #distributor
380
+
381
+ /** @type {ShardCollector} */
382
+ #collector
383
+
384
+ /** @type {object|null} */
385
+ #manifest = null
386
+
387
+ /**
388
+ * @param {object} opts
389
+ * @param {string} opts.agentId - Agent identifier
390
+ * @param {import('./clawser-mesh-dht.js').DhtNode} opts.dhtNode - DHT node
391
+ * @param {number} [opts.threshold=3] - Minimum shards for recovery
392
+ * @param {number} [opts.totalShards=5] - Total shards to create
393
+ */
394
+ constructor({ agentId, dhtNode, threshold = 3, totalShards = 5 }) {
395
+ if (!agentId || typeof agentId !== 'string') {
396
+ throw new Error('agentId is required and must be a non-empty string')
397
+ }
398
+ this.#agentId = agentId
399
+ this.#dhtNode = dhtNode
400
+ this.#threshold = threshold
401
+ this.#totalShards = totalShards
402
+ this.#distributor = new ShardDistributor({ dhtNode, threshold, totalShards })
403
+ this.#collector = new ShardCollector({ dhtNode, threshold })
404
+ }
405
+
406
+ /**
407
+ * Hide the agent's state by distributing it as shards across the DHT.
408
+ * @param {string} stateBlob - State data to hide
409
+ * @returns {object} Manifest with shard keys and metadata
410
+ */
411
+ hide(stateBlob) {
412
+ const shards = this.#distributor.distribute(this.#agentId, stateBlob)
413
+
414
+ this.#manifest = {
415
+ agentId: this.#agentId,
416
+ threshold: this.#threshold,
417
+ totalShards: this.#totalShards,
418
+ shardIds: shards.map(s => s.shardId),
419
+ hiddenAt: Date.now(),
420
+ }
421
+
422
+ return this.#manifest
423
+ }
424
+
425
+ /**
426
+ * Reconstitute the agent's state from DHT shards.
427
+ * @returns {string} Reconstructed state blob
428
+ */
429
+ reconstitute() {
430
+ const shards = this.#collector.collect(this.#agentId, this.#totalShards)
431
+ return this.#collector.reconstruct(shards)
432
+ }
433
+
434
+ /**
435
+ * Check if enough shards are available for reconstitution.
436
+ * @returns {boolean}
437
+ */
438
+ isViable() {
439
+ const count = this.#collector.probe(this.#agentId, this.#totalShards)
440
+ return count >= this.#threshold
441
+ }
442
+
443
+ /**
444
+ * Get the stored shard manifest.
445
+ * @returns {object|null}
446
+ */
447
+ getManifest() {
448
+ return this.#manifest
449
+ }
450
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-mesh-sw-routing.js -- ServiceWorker mesh:// fetch routing.
4
+ *
5
+ * Intercepts mesh:// protocol requests and *.mesh.local hostnames
6
+ * in the Service Worker fetch handler, delegating to mesh RPC.
7
+ *
8
+ * No browser-only imports at module level.
9
+ *
10
+ * Run tests:
11
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-sw-routing.test.mjs
12
+ */
13
+
14
+ const MESH_PROTOCOL = 'mesh://'
15
+ const MESH_LOCAL_SUFFIX = '.mesh.local'
16
+
17
+ /**
18
+ * Parse a mesh URL into { podId, path } or null.
19
+ * Supports:
20
+ * - mesh://podId/path
21
+ * - https://podId.mesh.local/path
22
+ * - http://podId.mesh.local/path
23
+ *
24
+ * @param {string} urlStr
25
+ * @returns {{ podId: string, path: string } | null}
26
+ */
27
+ export function parseMeshRequest(urlStr) {
28
+ if (!urlStr || typeof urlStr !== 'string') return null
29
+
30
+ // --- mesh:// protocol ---
31
+ if (urlStr.startsWith(MESH_PROTOCOL)) {
32
+ const rest = urlStr.slice(MESH_PROTOCOL.length)
33
+ if (!rest) return null
34
+
35
+ const slashIdx = rest.indexOf('/')
36
+ let podId, path
37
+ if (slashIdx === -1) {
38
+ podId = rest
39
+ path = '/'
40
+ } else {
41
+ podId = rest.slice(0, slashIdx)
42
+ path = rest.slice(slashIdx) || '/'
43
+ }
44
+
45
+ if (!podId) return null
46
+ return { podId, path }
47
+ }
48
+
49
+ // --- https://podId.mesh.local/path or http://podId.mesh.local/path ---
50
+ // Extract hostname from the raw string to preserve case (URL() lowercases hostnames).
51
+ const httpMatch = urlStr.match(/^https?:\/\/([^/?#]+)(\/[^?#]*)?/)
52
+ if (!httpMatch) return null
53
+
54
+ const rawHost = httpMatch[1] // preserves original case
55
+ const lowerHost = rawHost.toLowerCase()
56
+ if (!lowerHost.endsWith(MESH_LOCAL_SUFFIX)) return null
57
+
58
+ const podId = rawHost.slice(0, -MESH_LOCAL_SUFFIX.length)
59
+ if (!podId) return null
60
+
61
+ const path = httpMatch[2] || '/'
62
+ return { podId, path }
63
+ }
64
+
65
+ /**
66
+ * Routes mesh:// and *.mesh.local fetch requests to a mesh RPC handler.
67
+ */
68
+ export class MeshFetchRouter {
69
+ #onRpc
70
+
71
+ /**
72
+ * @param {object} opts
73
+ * @param {function({ podId: string, method: string, path: string, headers: object, body: * }): Promise<{ status?: number, headers?: object, body: * }>} opts.onRpc
74
+ */
75
+ constructor({ onRpc }) {
76
+ if (typeof onRpc !== 'function') throw new Error('onRpc callback is required')
77
+ this.#onRpc = onRpc
78
+ }
79
+
80
+ /**
81
+ * Attempt to route a Request object. Returns Response if matched, null if not a mesh request.
82
+ * @param {Request} request
83
+ * @returns {Promise<Response|null>}
84
+ */
85
+ async route(request) {
86
+ const parsed = parseMeshRequest(request.url)
87
+ if (!parsed) return null
88
+
89
+ const { podId, path } = parsed
90
+ const method = request.method || 'GET'
91
+
92
+ // Read body for non-GET methods
93
+ let body = null
94
+ if (method !== 'GET' && method !== 'HEAD') {
95
+ try {
96
+ body = await request.text()
97
+ // Try parsing as JSON
98
+ try { body = JSON.parse(body) } catch { /* keep as string */ }
99
+ } catch { /* no body */ }
100
+ }
101
+
102
+ // Extract headers
103
+ const headers = {}
104
+ if (request.headers) {
105
+ // Support both Map-like and plain objects
106
+ if (typeof request.headers.forEach === 'function') {
107
+ request.headers.forEach((v, k) => { headers[k] = v })
108
+ } else if (typeof request.headers.entries === 'function') {
109
+ for (const [k, v] of request.headers.entries()) headers[k] = v
110
+ }
111
+ }
112
+
113
+ try {
114
+ const result = await this.#onRpc({ podId, method, path, headers, body })
115
+ const status = result.status ?? 200
116
+ const resHeaders = result.headers ?? { 'content-type': 'application/json' }
117
+ const resBody = typeof result.body === 'string' ? result.body : JSON.stringify(result.body)
118
+ return new Response(resBody, { status, headers: resHeaders })
119
+ } catch (err) {
120
+ return new Response(JSON.stringify({ error: err.message }), {
121
+ status: 502,
122
+ headers: { 'content-type': 'application/json' },
123
+ })
124
+ }
125
+ }
126
+ }