@johnhenry/browsermesh-apps 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,514 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-peer-encrypted-store.js -- Encrypt blobs before uploading to peers.
4
+ *
5
+ * Peers store opaque ciphertext — they cannot read content. Enables
6
+ * "borrow storage from friends" scenario.
7
+ *
8
+ * Uses AES-256-GCM via Node.js crypto (for testing) or Web Crypto API
9
+ * (in browser). The 16-byte GCM auth tag is appended to the ciphertext.
10
+ *
11
+ * No browser-only imports at module level.
12
+ *
13
+ * Run tests:
14
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-encrypted-store.test.mjs
15
+ */
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Crypto helpers — Node.js-first for testability
19
+ // ---------------------------------------------------------------------------
20
+
21
+ let _crypto = null
22
+
23
+ /**
24
+ * Lazily resolve the crypto module.
25
+ *
26
+ * @returns {Promise<object>}
27
+ */
28
+ async function getCrypto() {
29
+ if (_crypto) return _crypto
30
+ if (typeof globalThis.crypto !== 'undefined' && globalThis.crypto.getRandomValues) {
31
+ _crypto = globalThis.crypto
32
+ } else {
33
+ const mod = await import('node:crypto')
34
+ _crypto = mod.default || mod
35
+ }
36
+ return _crypto
37
+ }
38
+
39
+ /**
40
+ * Generate a random 256-bit AES key.
41
+ *
42
+ * @returns {Promise<Uint8Array>}
43
+ */
44
+ async function generateKey() {
45
+ const c = await getCrypto()
46
+ const key = new Uint8Array(32)
47
+ c.getRandomValues(key)
48
+ return key
49
+ }
50
+
51
+ /**
52
+ * Generate a random 96-bit IV for GCM.
53
+ *
54
+ * @returns {Promise<Uint8Array>}
55
+ */
56
+ async function generateIV() {
57
+ const c = await getCrypto()
58
+ const iv = new Uint8Array(12)
59
+ c.getRandomValues(iv)
60
+ return iv
61
+ }
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // AES-256-GCM encrypt / decrypt — Node.js native
65
+ // ---------------------------------------------------------------------------
66
+
67
+ /**
68
+ * Encrypt data with AES-256-GCM.
69
+ *
70
+ * Returns the ciphertext with the 16-byte auth tag appended.
71
+ *
72
+ * @param {Uint8Array} data - Plaintext bytes
73
+ * @param {Uint8Array} key - 32-byte AES key
74
+ * @param {Uint8Array} iv - 12-byte IV
75
+ * @returns {Promise<Uint8Array>} ciphertext || authTag
76
+ */
77
+ async function aesEncrypt(data, key, iv) {
78
+ // Try Node.js crypto first (always available in test env)
79
+ try {
80
+ const nodeCrypto = await import('node:crypto')
81
+ const cipher = nodeCrypto.createCipheriv('aes-256-gcm', key, iv)
82
+ const encrypted = cipher.update(data)
83
+ const final = cipher.final()
84
+ const authTag = cipher.getAuthTag()
85
+
86
+ const result = new Uint8Array(encrypted.length + final.length + authTag.length)
87
+ result.set(new Uint8Array(encrypted.buffer, encrypted.byteOffset, encrypted.length), 0)
88
+ if (final.length > 0) {
89
+ result.set(new Uint8Array(final.buffer, final.byteOffset, final.length), encrypted.length)
90
+ }
91
+ result.set(new Uint8Array(authTag.buffer, authTag.byteOffset, authTag.length), encrypted.length + final.length)
92
+ return result
93
+ } catch {
94
+ // Fallback to Web Crypto
95
+ const subtle = globalThis.crypto?.subtle
96
+ if (!subtle) throw new Error('No crypto implementation available')
97
+
98
+ const cryptoKey = await subtle.importKey('raw', key, { name: 'AES-GCM' }, false, ['encrypt'])
99
+ const encrypted = await subtle.encrypt({ name: 'AES-GCM', iv }, cryptoKey, data)
100
+ return new Uint8Array(encrypted)
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Decrypt AES-256-GCM ciphertext.
106
+ *
107
+ * Expects the 16-byte auth tag appended to the ciphertext.
108
+ *
109
+ * @param {Uint8Array} ciphertext - ciphertext || authTag
110
+ * @param {Uint8Array} key - 32-byte AES key
111
+ * @param {Uint8Array} iv - 12-byte IV
112
+ * @returns {Promise<Uint8Array>} plaintext
113
+ */
114
+ async function aesDecrypt(ciphertext, key, iv) {
115
+ // Try Node.js crypto first
116
+ try {
117
+ const nodeCrypto = await import('node:crypto')
118
+ const authTag = ciphertext.slice(ciphertext.length - 16)
119
+ const data = ciphertext.slice(0, ciphertext.length - 16)
120
+
121
+ const decipher = nodeCrypto.createDecipheriv('aes-256-gcm', key, iv)
122
+ decipher.setAuthTag(authTag)
123
+ const decrypted = decipher.update(data)
124
+ const final = decipher.final()
125
+
126
+ const result = new Uint8Array(decrypted.length + final.length)
127
+ result.set(new Uint8Array(decrypted.buffer, decrypted.byteOffset, decrypted.length), 0)
128
+ if (final.length > 0) {
129
+ result.set(new Uint8Array(final.buffer, final.byteOffset, final.length), decrypted.length)
130
+ }
131
+ return result
132
+ } catch (err) {
133
+ // If the error is from auth tag mismatch, re-throw it
134
+ if (err.message?.includes('Unsupported state') || err.code === 'ERR_OSSL_BAD_DECRYPT') {
135
+ throw new Error('Decryption failed: authentication tag mismatch')
136
+ }
137
+
138
+ // Fallback to Web Crypto
139
+ const subtle = globalThis.crypto?.subtle
140
+ if (!subtle) throw err
141
+
142
+ const cryptoKey = await subtle.importKey('raw', key, { name: 'AES-GCM' }, false, ['decrypt'])
143
+ const decrypted = await subtle.decrypt({ name: 'AES-GCM', iv }, cryptoKey, ciphertext)
144
+ return new Uint8Array(decrypted)
145
+ }
146
+ }
147
+
148
+ // ---------------------------------------------------------------------------
149
+ // SHA-256 CID computation
150
+ // ---------------------------------------------------------------------------
151
+
152
+ /**
153
+ * Compute a content ID (CID) as the hex-encoded SHA-256 of data.
154
+ *
155
+ * @param {Uint8Array} data
156
+ * @returns {Promise<string>} hex-encoded SHA-256
157
+ */
158
+ export async function computeCid(data) {
159
+ try {
160
+ const nodeCrypto = await import('node:crypto')
161
+ const hash = nodeCrypto.createHash('sha256').update(data).digest()
162
+ return Buffer.from(hash).toString('hex')
163
+ } catch {
164
+ const digest = await globalThis.crypto.subtle.digest('SHA-256', data)
165
+ return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('')
166
+ }
167
+ }
168
+
169
+ // ---------------------------------------------------------------------------
170
+ // Base64 helpers
171
+ // ---------------------------------------------------------------------------
172
+
173
+ /**
174
+ * Encode bytes to standard base64.
175
+ *
176
+ * @param {Uint8Array} bytes
177
+ * @returns {string}
178
+ */
179
+ function toBase64(bytes) {
180
+ if (typeof Buffer !== 'undefined') {
181
+ return Buffer.from(bytes).toString('base64')
182
+ }
183
+ return btoa(String.fromCharCode(...bytes))
184
+ }
185
+
186
+ /**
187
+ * Decode standard base64 to bytes.
188
+ *
189
+ * @param {string} str
190
+ * @returns {Uint8Array}
191
+ */
192
+ function fromBase64(str) {
193
+ if (typeof Buffer !== 'undefined') {
194
+ return new Uint8Array(Buffer.from(str, 'base64'))
195
+ }
196
+ const bin = atob(str)
197
+ const bytes = new Uint8Array(bin.length)
198
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
199
+ return bytes
200
+ }
201
+
202
+ // ---------------------------------------------------------------------------
203
+ // Exported helper functions
204
+ // ---------------------------------------------------------------------------
205
+
206
+ /**
207
+ * Encrypt a blob of data with a fresh random key and IV.
208
+ *
209
+ * @param {Uint8Array|string} data - Plaintext
210
+ * @returns {Promise<{ ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array }>}
211
+ */
212
+ export async function encryptBlob(data) {
213
+ const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data
214
+ const key = await generateKey()
215
+ const iv = await generateIV()
216
+ const ciphertext = await aesEncrypt(bytes, key, iv)
217
+ return { ciphertext, key, iv }
218
+ }
219
+
220
+ /**
221
+ * Decrypt a blob using the provided key and IV.
222
+ *
223
+ * @param {Uint8Array} ciphertext
224
+ * @param {Uint8Array} key - 32-byte AES key
225
+ * @param {Uint8Array} iv - 12-byte IV
226
+ * @returns {Promise<Uint8Array>} plaintext
227
+ */
228
+ export async function decryptBlob(ciphertext, key, iv) {
229
+ return aesDecrypt(ciphertext, key, iv)
230
+ }
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // ManifestEntry
234
+ // ---------------------------------------------------------------------------
235
+
236
+ /**
237
+ * A single entry in the encrypted blob manifest tracking what was stored where.
238
+ */
239
+ export class ManifestEntry {
240
+ /**
241
+ * @param {object} opts
242
+ * @param {string} opts.cid - Content ID (hex SHA-256 of ciphertext)
243
+ * @param {string} opts.peerId - Peer the blob is stored on
244
+ * @param {string} opts.key - AES key (base64-encoded)
245
+ * @param {string} opts.iv - IV (base64-encoded)
246
+ * @param {number} opts.size - Size of the original plaintext in bytes
247
+ * @param {object} [opts.metadata] - Optional user metadata
248
+ * @param {number} [opts.storedAt] - Timestamp when stored
249
+ */
250
+ constructor({ cid, peerId, key, iv, size, metadata, storedAt }) {
251
+ /** @type {string} */
252
+ this.cid = cid
253
+ /** @type {string} */
254
+ this.peerId = peerId
255
+ /** @type {string} */
256
+ this.key = key
257
+ /** @type {string} */
258
+ this.iv = iv
259
+ /** @type {number} */
260
+ this.size = size
261
+ /** @type {object} */
262
+ this.metadata = metadata || {}
263
+ /** @type {number} */
264
+ this.storedAt = storedAt || Date.now()
265
+ }
266
+
267
+ /**
268
+ * Serialize to JSON-safe object.
269
+ *
270
+ * @returns {object}
271
+ */
272
+ toJSON() {
273
+ return {
274
+ cid: this.cid,
275
+ peerId: this.peerId,
276
+ key: this.key,
277
+ iv: this.iv,
278
+ size: this.size,
279
+ metadata: this.metadata,
280
+ storedAt: this.storedAt,
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Deserialize from a plain object.
286
+ *
287
+ * @param {object} json
288
+ * @returns {ManifestEntry}
289
+ */
290
+ static fromJSON(json) {
291
+ return new ManifestEntry({
292
+ cid: json.cid,
293
+ peerId: json.peerId,
294
+ key: json.key,
295
+ iv: json.iv,
296
+ size: json.size,
297
+ metadata: json.metadata,
298
+ storedAt: json.storedAt,
299
+ })
300
+ }
301
+ }
302
+
303
+ // ---------------------------------------------------------------------------
304
+ // EncryptedBlobStore
305
+ // ---------------------------------------------------------------------------
306
+
307
+ /**
308
+ * Encrypt blobs before uploading to peers.
309
+ *
310
+ * Peers store opaque ciphertext — they cannot read content. The local
311
+ * manifest tracks CIDs, keys, and IVs needed to retrieve and decrypt.
312
+ */
313
+ export class EncryptedBlobStore {
314
+ /** @type {object} FileClient instance */
315
+ #fileClient
316
+
317
+ /** @type {Function} */
318
+ #onLog
319
+
320
+ /** @type {Map<string, ManifestEntry>} cid -> ManifestEntry */
321
+ #manifest = new Map()
322
+
323
+ /**
324
+ * @param {object} opts
325
+ * @param {object} opts.fileClient - PeerFiles FileClient instance
326
+ * @param {Function} [opts.onLog] - Logging callback (level, message)
327
+ */
328
+ constructor({ fileClient, onLog }) {
329
+ if (!fileClient) {
330
+ throw new Error('fileClient is required')
331
+ }
332
+ this.#fileClient = fileClient
333
+ this.#onLog = onLog || (() => {})
334
+ }
335
+
336
+ /**
337
+ * Encrypt and store a blob on a remote peer.
338
+ *
339
+ * @param {string} peerId - Target peer ID
340
+ * @param {Uint8Array|string} data - Plaintext data to encrypt and store
341
+ * @param {object} [opts] - Options
342
+ * @param {object} [opts.metadata] - Optional metadata to attach
343
+ * @returns {Promise<{ cid: string, key: string, iv: string, size: number }>}
344
+ */
345
+ async store(peerId, data, opts = {}) {
346
+ if (!peerId || typeof peerId !== 'string') {
347
+ throw new Error('peerId must be a non-empty string')
348
+ }
349
+
350
+ const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data
351
+ const size = bytes.length
352
+
353
+ this.#onLog(2, `Encrypting blob (${size} bytes) for peer ${peerId}`)
354
+
355
+ // Generate key + IV and encrypt
356
+ const key = await generateKey()
357
+ const iv = await generateIV()
358
+ const ciphertext = await aesEncrypt(bytes, key, iv)
359
+
360
+ // Compute CID from ciphertext
361
+ const cid = await computeCid(ciphertext)
362
+
363
+ // Upload ciphertext to peer
364
+ const path = `.encrypted-blobs/${cid}`
365
+ await this.#fileClient.writeFile(path, ciphertext)
366
+
367
+ this.#onLog(2, `Uploaded encrypted blob ${cid} to peer ${peerId}`)
368
+
369
+ // Encode key/iv as base64 for storage
370
+ const keyB64 = toBase64(key)
371
+ const ivB64 = toBase64(iv)
372
+
373
+ // Store in local manifest
374
+ const entry = new ManifestEntry({
375
+ cid,
376
+ peerId,
377
+ key: keyB64,
378
+ iv: ivB64,
379
+ size,
380
+ metadata: opts.metadata || {},
381
+ })
382
+ this.#manifest.set(cid, entry)
383
+
384
+ return { cid, key: keyB64, iv: ivB64, size }
385
+ }
386
+
387
+ /**
388
+ * Download and decrypt a blob from a remote peer.
389
+ *
390
+ * @param {string} peerId - Peer to download from
391
+ * @param {string} cid - Content ID of the blob
392
+ * @param {string} key - Base64-encoded AES key
393
+ * @param {string} iv - Base64-encoded IV
394
+ * @returns {Promise<Uint8Array>} decrypted plaintext
395
+ */
396
+ async retrieve(peerId, cid, key, iv) {
397
+ if (!peerId || typeof peerId !== 'string') {
398
+ throw new Error('peerId must be a non-empty string')
399
+ }
400
+ if (!cid || typeof cid !== 'string') {
401
+ throw new Error('cid must be a non-empty string')
402
+ }
403
+
404
+ this.#onLog(2, `Retrieving blob ${cid} from peer ${peerId}`)
405
+
406
+ // Download ciphertext from peer
407
+ const path = `.encrypted-blobs/${cid}`
408
+ const result = await this.#fileClient.readFile(path)
409
+ const ciphertext = result.data instanceof Uint8Array
410
+ ? result.data
411
+ : new TextEncoder().encode(result.data)
412
+
413
+ // Verify CID matches
414
+ const actualCid = await computeCid(ciphertext)
415
+ if (actualCid !== cid) {
416
+ throw new Error(`CID mismatch: expected ${cid}, got ${actualCid}`)
417
+ }
418
+
419
+ // Decrypt
420
+ const keyBytes = fromBase64(key)
421
+ const ivBytes = fromBase64(iv)
422
+ const plaintext = await aesDecrypt(ciphertext, keyBytes, ivBytes)
423
+
424
+ this.#onLog(2, `Decrypted blob ${cid} (${plaintext.length} bytes)`)
425
+ return plaintext
426
+ }
427
+
428
+ /**
429
+ * Delete an encrypted blob from a remote peer.
430
+ *
431
+ * @param {string} peerId - Peer to delete from
432
+ * @param {string} cid - Content ID to delete
433
+ * @returns {Promise<boolean>}
434
+ */
435
+ async delete(peerId, cid) {
436
+ if (!cid || typeof cid !== 'string') {
437
+ throw new Error('cid must be a non-empty string')
438
+ }
439
+
440
+ this.#onLog(2, `Deleting blob ${cid} from peer ${peerId}`)
441
+
442
+ const path = `.encrypted-blobs/${cid}`
443
+ await this.#fileClient.deleteFile(path)
444
+
445
+ // Remove from manifest
446
+ const deleted = this.#manifest.delete(cid)
447
+ return deleted
448
+ }
449
+
450
+ /**
451
+ * List all entries in the local manifest.
452
+ *
453
+ * @returns {ManifestEntry[]}
454
+ */
455
+ listManifest() {
456
+ return [...this.#manifest.values()]
457
+ }
458
+
459
+ /**
460
+ * Verify that a blob on a remote peer matches its CID, without decrypting.
461
+ *
462
+ * @param {string} peerId - Peer to verify on
463
+ * @param {string} cid - Expected content ID
464
+ * @returns {Promise<{ valid: boolean, size: number }>}
465
+ */
466
+ async verify(peerId, cid) {
467
+ if (!cid || typeof cid !== 'string') {
468
+ throw new Error('cid must be a non-empty string')
469
+ }
470
+
471
+ this.#onLog(2, `Verifying blob ${cid} on peer ${peerId}`)
472
+
473
+ const path = `.encrypted-blobs/${cid}`
474
+ const result = await this.#fileClient.readFile(path)
475
+ const ciphertext = result.data instanceof Uint8Array
476
+ ? result.data
477
+ : new TextEncoder().encode(result.data)
478
+
479
+ const actualCid = await computeCid(ciphertext)
480
+ const valid = actualCid === cid
481
+
482
+ this.#onLog(2, `Verification of ${cid}: ${valid ? 'passed' : 'FAILED'}`)
483
+ return { valid, size: ciphertext.length }
484
+ }
485
+
486
+ /**
487
+ * Serialize the store state (manifest) to JSON.
488
+ *
489
+ * @returns {object}
490
+ */
491
+ toJSON() {
492
+ return {
493
+ manifest: [...this.#manifest.entries()].map(([cid, entry]) => entry.toJSON()),
494
+ }
495
+ }
496
+
497
+ /**
498
+ * Restore an EncryptedBlobStore from serialized JSON.
499
+ *
500
+ * @param {object} json
501
+ * @param {object} deps - Dependencies to inject
502
+ * @param {object} deps.fileClient - FileClient instance
503
+ * @param {Function} [deps.onLog] - Logging callback
504
+ * @returns {EncryptedBlobStore}
505
+ */
506
+ static fromJSON(json, deps) {
507
+ const store = new EncryptedBlobStore(deps)
508
+ for (const entryJson of json.manifest || []) {
509
+ const entry = ManifestEntry.fromJSON(entryJson)
510
+ store.#manifest.set(entry.cid, entry)
511
+ }
512
+ return store
513
+ }
514
+ }