@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.
package/src/audit.mjs ADDED
@@ -0,0 +1,622 @@
1
+ /**
2
+ * clawser-mesh-audit.js -- Cryptographic audit trail for BrowserMesh.
3
+ *
4
+ * Provides a tamper-evident, hash-chained log of operations with
5
+ * Ed25519 signatures, Merkle proof generation/verification, and
6
+ * fork detection.
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-audit.test.mjs
12
+ */
13
+
14
+ import { encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives';
15
+ import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
16
+
17
+ // Re-export for consumers
18
+ export { encodeBase64url, decodeBase64url };
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // Wire constants — imported from canonical registry
22
+ // ---------------------------------------------------------------------------
23
+
24
+ /** Wire type for a single audit entry. */
25
+ export const AUDIT_ENTRY = MESH_TYPE.AUDIT_ENTRY;
26
+
27
+ /** Wire type for querying an audit chain. */
28
+ export const AUDIT_CHAIN_QUERY = MESH_TYPE.AUDIT_CHAIN_QUERY;
29
+
30
+ /** Wire type for responding with audit chain data. */
31
+ export const AUDIT_CHAIN_RESPONSE = MESH_TYPE.AUDIT_CHAIN_RESPONSE;
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // Genesis
35
+ // ---------------------------------------------------------------------------
36
+
37
+ /** The initial previous-hash for the first entry in every chain (32 zero bytes). */
38
+ export const GENESIS_HASH = new Uint8Array(32);
39
+
40
+ // ---------------------------------------------------------------------------
41
+ // Helpers
42
+ // ---------------------------------------------------------------------------
43
+
44
+ /**
45
+ * Produce canonical JSON for an object: keys sorted recursively,
46
+ * Uint8Array values encoded as base64url strings.
47
+ *
48
+ * @param {object} obj
49
+ * @returns {string}
50
+ */
51
+ function canonicalJSON(obj) {
52
+ return JSON.stringify(obj, (_key, value) => {
53
+ if (value instanceof Uint8Array) {
54
+ return encodeBase64url(value);
55
+ }
56
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
57
+ const sorted = {};
58
+ for (const k of Object.keys(value).sort()) {
59
+ sorted[k] = value[k];
60
+ }
61
+ return sorted;
62
+ }
63
+ return value;
64
+ });
65
+ }
66
+
67
+ /**
68
+ * SHA-256 hash of a UTF-8 string.
69
+ *
70
+ * @param {string} str
71
+ * @returns {Promise<Uint8Array>}
72
+ */
73
+ async function sha256(str) {
74
+ const data = new TextEncoder().encode(str);
75
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', data));
76
+ }
77
+
78
+ /**
79
+ * SHA-256 hash of raw bytes.
80
+ *
81
+ * @param {Uint8Array} bytes
82
+ * @returns {Promise<Uint8Array>}
83
+ */
84
+ async function sha256Bytes(bytes) {
85
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
86
+ }
87
+
88
+ /**
89
+ * Concatenate two Uint8Arrays.
90
+ *
91
+ * @param {Uint8Array} a
92
+ * @param {Uint8Array} b
93
+ * @returns {Uint8Array}
94
+ */
95
+ function concat(a, b) {
96
+ const result = new Uint8Array(a.length + b.length);
97
+ result.set(a, 0);
98
+ result.set(b, a.length);
99
+ return result;
100
+ }
101
+
102
+ /**
103
+ * Compare two Uint8Arrays for equality.
104
+ *
105
+ * @param {Uint8Array} a
106
+ * @param {Uint8Array} b
107
+ * @returns {boolean}
108
+ */
109
+ function bytesEqual(a, b) {
110
+ if (a.length !== b.length) return false;
111
+ for (let i = 0; i < a.length; i++) {
112
+ if (a[i] !== b[i]) return false;
113
+ }
114
+ return true;
115
+ }
116
+
117
+ // ---------------------------------------------------------------------------
118
+ // AuditEntry
119
+ // ---------------------------------------------------------------------------
120
+
121
+ /**
122
+ * A single entry in a hash-chained audit log.
123
+ *
124
+ * @class
125
+ */
126
+ export class AuditEntry {
127
+ /**
128
+ * @param {object} opts
129
+ * @param {number} opts.sequence - Zero-based position in the chain
130
+ * @param {string} opts.authorPodId - Pod ID of the author
131
+ * @param {string} opts.operation - Operation name
132
+ * @param {*} opts.data - Arbitrary operation payload
133
+ * @param {Uint8Array} opts.previousHash - SHA-256 hash of the previous entry (or GENESIS_HASH)
134
+ * @param {number} opts.timestamp - Creation timestamp (ms)
135
+ * @param {Uint8Array|null} [opts.signature] - Ed25519 signature over all fields except signature
136
+ */
137
+ constructor({ sequence, authorPodId, operation, data, previousHash, timestamp, signature }) {
138
+ /** @type {number} */
139
+ this.sequence = sequence;
140
+ /** @type {string} */
141
+ this.authorPodId = authorPodId;
142
+ /** @type {string} */
143
+ this.operation = operation;
144
+ /** @type {*} */
145
+ this.data = data;
146
+ /** @type {Uint8Array} */
147
+ this.previousHash = previousHash;
148
+ /** @type {number} */
149
+ this.timestamp = timestamp;
150
+ /** @type {Uint8Array|null} */
151
+ this.signature = signature || null;
152
+ }
153
+
154
+ /**
155
+ * Get the canonical bytes that are signed (all fields except signature).
156
+ *
157
+ * @returns {string} Canonical JSON string
158
+ */
159
+ get signedPayload() {
160
+ return canonicalJSON({
161
+ sequence: this.sequence,
162
+ authorPodId: this.authorPodId,
163
+ operation: this.operation,
164
+ data: this.data,
165
+ previousHash: this.previousHash,
166
+ timestamp: this.timestamp,
167
+ });
168
+ }
169
+
170
+ /**
171
+ * Compute the SHA-256 hash of this entry's signed payload.
172
+ *
173
+ * @returns {Promise<Uint8Array>}
174
+ */
175
+ async hash() {
176
+ return sha256(this.signedPayload);
177
+ }
178
+
179
+ /**
180
+ * Serialize to a plain object (binary fields as base64url).
181
+ *
182
+ * @returns {object}
183
+ */
184
+ toJSON() {
185
+ return {
186
+ sequence: this.sequence,
187
+ authorPodId: this.authorPodId,
188
+ operation: this.operation,
189
+ data: this.data,
190
+ previousHash: encodeBase64url(this.previousHash),
191
+ timestamp: this.timestamp,
192
+ signature: this.signature ? encodeBase64url(this.signature) : null,
193
+ };
194
+ }
195
+
196
+ /**
197
+ * Deserialize from a plain object.
198
+ *
199
+ * @param {object} json
200
+ * @returns {AuditEntry}
201
+ */
202
+ static fromJSON(json) {
203
+ return new AuditEntry({
204
+ sequence: json.sequence,
205
+ authorPodId: json.authorPodId,
206
+ operation: json.operation,
207
+ data: json.data,
208
+ previousHash: decodeBase64url(json.previousHash),
209
+ timestamp: json.timestamp,
210
+ signature: json.signature ? decodeBase64url(json.signature) : null,
211
+ });
212
+ }
213
+ }
214
+
215
+ // ---------------------------------------------------------------------------
216
+ // AuditChain
217
+ // ---------------------------------------------------------------------------
218
+
219
+ /**
220
+ * A linear hash chain of AuditEntry objects.
221
+ *
222
+ * @class
223
+ */
224
+ export class AuditChain {
225
+ /** @type {string} */
226
+ #chainId;
227
+
228
+ /** @type {AuditEntry[]} */
229
+ #entries = [];
230
+
231
+ /**
232
+ * @param {string} chainId - Unique identifier for this chain
233
+ */
234
+ constructor(chainId) {
235
+ if (!chainId || typeof chainId !== 'string') {
236
+ throw new Error('chainId must be a non-empty string');
237
+ }
238
+ this.#chainId = chainId;
239
+ }
240
+
241
+ /** @returns {string} */
242
+ get chainId() {
243
+ return this.#chainId;
244
+ }
245
+
246
+ /** @returns {number} */
247
+ get length() {
248
+ return this.#entries.length;
249
+ }
250
+
251
+ /**
252
+ * Append a new signed entry to the chain.
253
+ *
254
+ * @param {string} authorPodId - Pod ID of the author
255
+ * @param {string} operation - Operation name
256
+ * @param {*} data - Arbitrary payload
257
+ * @param {function(Uint8Array): Promise<Uint8Array>} signFn - Signing function
258
+ * @returns {Promise<AuditEntry>}
259
+ */
260
+ async append(authorPodId, operation, data, signFn) {
261
+ const sequence = this.#entries.length;
262
+ const previousHash = sequence === 0
263
+ ? GENESIS_HASH
264
+ : await this.#entries[sequence - 1].hash();
265
+
266
+ const entry = new AuditEntry({
267
+ sequence,
268
+ authorPodId,
269
+ operation,
270
+ data,
271
+ previousHash,
272
+ timestamp: Date.now(),
273
+ });
274
+
275
+ const payload = new TextEncoder().encode(entry.signedPayload);
276
+ entry.signature = await signFn(payload);
277
+
278
+ this.#entries.push(entry);
279
+ return entry;
280
+ }
281
+
282
+ /**
283
+ * Verify the entire chain: hash linkage and signatures.
284
+ *
285
+ * @param {function(string): Promise<Uint8Array|CryptoKey>} getPublicKey
286
+ * Resolves a podId to its Ed25519 public key (raw bytes or CryptoKey)
287
+ * @returns {Promise<{ valid: boolean, error?: string, failedAt?: number }>}
288
+ */
289
+ async verify(getPublicKey) {
290
+ for (let i = 0; i < this.#entries.length; i++) {
291
+ const entry = this.#entries[i];
292
+
293
+ // Check sequence
294
+ if (entry.sequence !== i) {
295
+ return { valid: false, error: 'sequence mismatch', failedAt: i };
296
+ }
297
+
298
+ // Check hash linkage
299
+ const expectedPrev = i === 0
300
+ ? GENESIS_HASH
301
+ : await this.#entries[i - 1].hash();
302
+
303
+ if (!bytesEqual(entry.previousHash, expectedPrev)) {
304
+ return { valid: false, error: 'hash chain broken', failedAt: i };
305
+ }
306
+
307
+ // Verify signature
308
+ if (!entry.signature) {
309
+ return { valid: false, error: 'missing signature', failedAt: i };
310
+ }
311
+
312
+ const publicKey = await getPublicKey(entry.authorPodId);
313
+ const payload = new TextEncoder().encode(entry.signedPayload);
314
+
315
+ let valid;
316
+ if (publicKey instanceof Uint8Array) {
317
+ // Import raw bytes as CryptoKey
318
+ const key = await crypto.subtle.importKey(
319
+ 'raw', publicKey, { name: 'Ed25519' }, false, ['verify']
320
+ );
321
+ valid = await crypto.subtle.verify('Ed25519', key, entry.signature, payload);
322
+ } else {
323
+ // Already a CryptoKey
324
+ valid = await crypto.subtle.verify('Ed25519', publicKey, entry.signature, payload);
325
+ }
326
+
327
+ if (!valid) {
328
+ return { valid: false, error: 'invalid signature', failedAt: i };
329
+ }
330
+ }
331
+
332
+ return { valid: true };
333
+ }
334
+
335
+ /**
336
+ * Get an entry by sequence number.
337
+ *
338
+ * @param {number} sequence
339
+ * @returns {AuditEntry|null}
340
+ */
341
+ get(sequence) {
342
+ return this.#entries[sequence] || null;
343
+ }
344
+
345
+ /**
346
+ * Iterate over all entries.
347
+ *
348
+ * @returns {IterableIterator<AuditEntry>}
349
+ */
350
+ *entries() {
351
+ for (const entry of this.#entries) {
352
+ yield entry;
353
+ }
354
+ }
355
+
356
+ /**
357
+ * Return a slice of entries.
358
+ *
359
+ * @param {number} [start=0]
360
+ * @param {number} [end]
361
+ * @returns {AuditEntry[]}
362
+ */
363
+ slice(start = 0, end) {
364
+ return this.#entries.slice(start, end);
365
+ }
366
+
367
+ /**
368
+ * Serialize the chain.
369
+ *
370
+ * @returns {object}
371
+ */
372
+ toJSON() {
373
+ return {
374
+ chainId: this.#chainId,
375
+ entries: this.#entries.map((e) => e.toJSON()),
376
+ };
377
+ }
378
+
379
+ /**
380
+ * Deserialize from JSON.
381
+ *
382
+ * @param {object} json
383
+ * @returns {AuditChain}
384
+ */
385
+ static fromJSON(json) {
386
+ const chain = new AuditChain(json.chainId);
387
+ for (const entryData of json.entries) {
388
+ chain.#entries.push(AuditEntry.fromJSON(entryData));
389
+ }
390
+ return chain;
391
+ }
392
+ }
393
+
394
+ // ---------------------------------------------------------------------------
395
+ // AuditStore
396
+ // ---------------------------------------------------------------------------
397
+
398
+ /**
399
+ * Manages multiple named AuditChains.
400
+ *
401
+ * @class
402
+ */
403
+ export class AuditStore {
404
+ /** @type {Map<string, AuditChain>} */
405
+ #chains = new Map();
406
+
407
+ /**
408
+ * Create a new chain. Throws if it already exists.
409
+ *
410
+ * @param {string} chainId
411
+ * @returns {AuditChain}
412
+ */
413
+ createChain(chainId) {
414
+ if (this.#chains.has(chainId)) {
415
+ throw new Error(`Chain already exists: ${chainId}`);
416
+ }
417
+ const chain = new AuditChain(chainId);
418
+ this.#chains.set(chainId, chain);
419
+ return chain;
420
+ }
421
+
422
+ /**
423
+ * Get a chain by ID (or null).
424
+ *
425
+ * @param {string} chainId
426
+ * @returns {AuditChain|null}
427
+ */
428
+ getChain(chainId) {
429
+ return this.#chains.get(chainId) || null;
430
+ }
431
+
432
+ /**
433
+ * Check whether a chain exists.
434
+ *
435
+ * @param {string} chainId
436
+ * @returns {boolean}
437
+ */
438
+ hasChain(chainId) {
439
+ return this.#chains.has(chainId);
440
+ }
441
+
442
+ /**
443
+ * Delete a chain. Returns true if it was deleted.
444
+ *
445
+ * @param {string} chainId
446
+ * @returns {boolean}
447
+ */
448
+ deleteChain(chainId) {
449
+ return this.#chains.delete(chainId);
450
+ }
451
+
452
+ /**
453
+ * List all chain IDs.
454
+ *
455
+ * @returns {string[]}
456
+ */
457
+ listChains() {
458
+ return [...this.#chains.keys()];
459
+ }
460
+
461
+ /** @returns {number} */
462
+ get size() {
463
+ return this.#chains.size;
464
+ }
465
+ }
466
+
467
+ // ---------------------------------------------------------------------------
468
+ // Fork detection
469
+ // ---------------------------------------------------------------------------
470
+
471
+ /**
472
+ * Detect a fork among a set of entries that share the same chain.
473
+ *
474
+ * Entries are grouped by sequence number. If any sequence has two or
475
+ * more entries with different hashes, a fork exists. Returns the
476
+ * common ancestor (last non-forked entry) and the divergent branches.
477
+ *
478
+ * @param {AuditEntry[]} entries
479
+ * @returns {Promise<{ ancestor: number, branches: AuditEntry[][] }|null>}
480
+ */
481
+ export async function detectFork(entries) {
482
+ if (entries.length === 0) return null;
483
+
484
+ // Group by sequence
485
+ const bySeq = new Map();
486
+ for (const entry of entries) {
487
+ if (!bySeq.has(entry.sequence)) {
488
+ bySeq.set(entry.sequence, []);
489
+ }
490
+ bySeq.get(entry.sequence).push(entry);
491
+ }
492
+
493
+ // Find the first sequence with divergent entries
494
+ const seqs = [...bySeq.keys()].sort((a, b) => a - b);
495
+
496
+ for (const seq of seqs) {
497
+ const group = bySeq.get(seq);
498
+ if (group.length < 2) continue;
499
+
500
+ // Check if all entries at this sequence are identical
501
+ const hashes = await Promise.all(group.map((e) => e.hash()));
502
+ const hashStrings = hashes.map((h) => encodeBase64url(h));
503
+ const unique = new Set(hashStrings);
504
+
505
+ if (unique.size > 1) {
506
+ // Fork detected — group branches by hash
507
+ const branchMap = new Map();
508
+ for (let i = 0; i < group.length; i++) {
509
+ const hs = hashStrings[i];
510
+ if (!branchMap.has(hs)) branchMap.set(hs, []);
511
+ branchMap.get(hs).push(group[i]);
512
+ }
513
+
514
+ return {
515
+ ancestor: seq - 1,
516
+ branches: [...branchMap.values()],
517
+ };
518
+ }
519
+ }
520
+
521
+ return null;
522
+ }
523
+
524
+ // ---------------------------------------------------------------------------
525
+ // Merkle proof helpers
526
+ // ---------------------------------------------------------------------------
527
+
528
+ /**
529
+ * Build a Merkle root from a list of audit entries.
530
+ *
531
+ * Leaves are the SHA-256 hashes of each entry's signed payload.
532
+ * The tree is built bottom-up; odd layers duplicate the last node.
533
+ *
534
+ * @param {AuditEntry[]} entries
535
+ * @returns {Promise<Uint8Array>} The Merkle root hash
536
+ */
537
+ export async function buildMerkleRoot(entries) {
538
+ if (entries.length === 0) {
539
+ return new Uint8Array(32); // empty root
540
+ }
541
+
542
+ let layer = await Promise.all(entries.map((e) => e.hash()));
543
+
544
+ while (layer.length > 1) {
545
+ const next = [];
546
+ for (let i = 0; i < layer.length; i += 2) {
547
+ const left = layer[i];
548
+ const right = i + 1 < layer.length ? layer[i + 1] : layer[i]; // duplicate last
549
+ next.push(await sha256Bytes(concat(left, right)));
550
+ }
551
+ layer = next;
552
+ }
553
+
554
+ return layer[0];
555
+ }
556
+
557
+ /**
558
+ * Build a Merkle inclusion proof for the entry at `index`.
559
+ *
560
+ * @param {AuditEntry[]} entries
561
+ * @param {number} index - Index of the entry to prove
562
+ * @returns {Promise<{ root: Uint8Array, proof: Array<{ hash: Uint8Array, position: 'left'|'right' }>, index: number }>}
563
+ */
564
+ export async function buildMerkleProof(entries, index) {
565
+ if (index < 0 || index >= entries.length) {
566
+ throw new RangeError(`Index ${index} out of range [0, ${entries.length})`);
567
+ }
568
+
569
+ let layer = await Promise.all(entries.map((e) => e.hash()));
570
+ const proof = [];
571
+ let currentIndex = index;
572
+
573
+ while (layer.length > 1) {
574
+ const next = [];
575
+ for (let i = 0; i < layer.length; i += 2) {
576
+ const left = layer[i];
577
+ const right = i + 1 < layer.length ? layer[i + 1] : layer[i];
578
+
579
+ if (i === currentIndex || i + 1 === currentIndex) {
580
+ if (currentIndex % 2 === 0) {
581
+ // Current is the left child, sibling is right
582
+ const sibling = i + 1 < layer.length ? layer[i + 1] : layer[i];
583
+ proof.push({ hash: sibling, position: 'right' });
584
+ } else {
585
+ // Current is the right child, sibling is left
586
+ proof.push({ hash: layer[i], position: 'left' });
587
+ }
588
+ }
589
+
590
+ next.push(await sha256Bytes(concat(left, right)));
591
+ }
592
+ currentIndex = Math.floor(currentIndex / 2);
593
+ layer = next;
594
+ }
595
+
596
+ return { root: layer[0], proof, index };
597
+ }
598
+
599
+ /**
600
+ * Verify a Merkle inclusion proof.
601
+ *
602
+ * @param {Uint8Array} entryHash - SHA-256 hash of the entry
603
+ * @param {Array<{ hash: Uint8Array, position: 'left'|'right' }>} proof - Sibling hashes
604
+ * @param {number} index - Original index of the entry
605
+ * @param {Uint8Array} root - Expected Merkle root
606
+ * @returns {Promise<boolean>}
607
+ */
608
+ export async function verifyMerkleProof(entryHash, proof, index, root) {
609
+ let current = entryHash;
610
+ let idx = index;
611
+
612
+ for (const step of proof) {
613
+ if (step.position === 'right') {
614
+ current = await sha256Bytes(concat(current, step.hash));
615
+ } else {
616
+ current = await sha256Bytes(concat(step.hash, current));
617
+ }
618
+ idx = Math.floor(idx / 2);
619
+ }
620
+
621
+ return bytesEqual(current, root);
622
+ }