@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,403 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-peer-timestamp.js — Distributed timestamp consensus.
4
+ *
5
+ * Peers propose timestamps, network agrees on canonical order via
6
+ * median computation and outlier rejection. Enables legal-grade
7
+ * event sequencing without centralized time authority.
8
+ *
9
+ * - TimestampAuthority: collects peer timestamps, computes median, signs proofs
10
+ * - TimestampProof: portable proof of consensus timestamp with witnesses
11
+ *
12
+ * Dependencies are injected (sessions, identity).
13
+ * No browser-only imports at module level.
14
+ *
15
+ * Run tests:
16
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-timestamp.test.mjs
17
+ */
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Constants
21
+ // ---------------------------------------------------------------------------
22
+
23
+ /**
24
+ * Default configuration values for distributed timestamp consensus.
25
+ *
26
+ * @type {Readonly<{ clockSkewMs: number, minWitnesses: number, confidenceThreshold: number }>}
27
+ */
28
+ export const TIMESTAMP_DEFAULTS = Object.freeze({
29
+ clockSkewMs: 30_000,
30
+ minWitnesses: 1,
31
+ confidenceThreshold: 0.5,
32
+ })
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // TimestampProof — portable proof of consensus timestamp
36
+ // ---------------------------------------------------------------------------
37
+
38
+ /**
39
+ * A signed proof that a set of peers agreed on a canonical timestamp
40
+ * for a given event hash.
41
+ */
42
+ export class TimestampProof {
43
+ /** @type {string} */
44
+ eventHash
45
+
46
+ /** @type {number} */
47
+ canonicalTimestamp
48
+
49
+ /** @type {Array<{ podId: string, localTimestamp: number, signature: string }>} */
50
+ witnesses
51
+
52
+ /** @type {string} */
53
+ issuedBy
54
+
55
+ /** @type {number} */
56
+ issuedAt
57
+
58
+ /** @type {number} */
59
+ confidence
60
+
61
+ /** @type {string} */
62
+ signature
63
+
64
+ /**
65
+ * @param {object} opts
66
+ * @param {string} opts.eventHash - Hex hash of the event being timestamped
67
+ * @param {number} opts.canonicalTimestamp - Agreed-upon timestamp (ms since epoch)
68
+ * @param {Array<{ podId: string, localTimestamp: number, signature: string }>} opts.witnesses
69
+ * @param {string} opts.issuedBy - Pod ID of the authority that assembled the proof
70
+ * @param {number} [opts.issuedAt] - When the proof was assembled
71
+ * @param {number} opts.confidence - Ratio of accepted witnesses to total peers (0-1)
72
+ * @param {string} [opts.signature] - Authority signature over eventHash + canonicalTimestamp
73
+ */
74
+ constructor({ eventHash, canonicalTimestamp, witnesses, issuedBy, issuedAt, confidence, signature }) {
75
+ this.eventHash = eventHash
76
+ this.canonicalTimestamp = canonicalTimestamp
77
+ this.witnesses = witnesses
78
+ this.issuedBy = issuedBy
79
+ this.issuedAt = issuedAt ?? Date.now()
80
+ this.confidence = confidence
81
+ this.signature = signature ?? null
82
+ }
83
+
84
+ /**
85
+ * Verify internal consistency of this proof.
86
+ *
87
+ * @param {Function} [verifyFn] - Optional async (signature, data, podId) => boolean
88
+ * @returns {{ valid: boolean, confidence: number }}
89
+ */
90
+ verify(verifyFn) {
91
+ // Basic structural checks
92
+ if (!this.eventHash || typeof this.eventHash !== 'string') {
93
+ return { valid: false, confidence: 0 }
94
+ }
95
+ if (typeof this.canonicalTimestamp !== 'number' || this.canonicalTimestamp <= 0) {
96
+ return { valid: false, confidence: 0 }
97
+ }
98
+ if (!Array.isArray(this.witnesses) || this.witnesses.length === 0) {
99
+ return { valid: false, confidence: 0 }
100
+ }
101
+
102
+ return { valid: true, confidence: this.confidence }
103
+ }
104
+
105
+ /**
106
+ * Serialize to a plain JSON object.
107
+ * @returns {object}
108
+ */
109
+ toJSON() {
110
+ return {
111
+ eventHash: this.eventHash,
112
+ canonicalTimestamp: this.canonicalTimestamp,
113
+ witnesses: this.witnesses,
114
+ issuedBy: this.issuedBy,
115
+ issuedAt: this.issuedAt,
116
+ confidence: this.confidence,
117
+ signature: this.signature,
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Restore a TimestampProof from a plain JSON object.
123
+ * @param {object} json
124
+ * @returns {TimestampProof}
125
+ */
126
+ static fromJSON(json) {
127
+ return new TimestampProof({
128
+ eventHash: json.eventHash,
129
+ canonicalTimestamp: json.canonicalTimestamp,
130
+ witnesses: json.witnesses,
131
+ issuedBy: json.issuedBy,
132
+ issuedAt: json.issuedAt,
133
+ confidence: json.confidence,
134
+ signature: json.signature,
135
+ })
136
+ }
137
+ }
138
+
139
+ // ---------------------------------------------------------------------------
140
+ // Helpers — base64 encoding for signatures
141
+ // ---------------------------------------------------------------------------
142
+
143
+ /**
144
+ * Encode a Uint8Array to base64 string.
145
+ * Works in both browser (btoa) and Node.js (Buffer).
146
+ *
147
+ * @param {Uint8Array} bytes
148
+ * @returns {string}
149
+ */
150
+ function toBase64(bytes) {
151
+ if (typeof Buffer !== 'undefined') {
152
+ return Buffer.from(bytes).toString('base64')
153
+ }
154
+ return btoa(String.fromCharCode(...bytes))
155
+ }
156
+
157
+ // ---------------------------------------------------------------------------
158
+ // TimestampAuthority — distributed consensus coordinator
159
+ // ---------------------------------------------------------------------------
160
+
161
+ /**
162
+ * Coordinates distributed timestamp consensus among mesh peers.
163
+ *
164
+ * Collects local and peer timestamps, computes median, rejects outliers,
165
+ * and produces signed TimestampProof objects.
166
+ */
167
+ export class TimestampAuthority {
168
+ #sessions
169
+ #identity
170
+ #clockSkewMs
171
+ #onLog
172
+
173
+ /**
174
+ * @param {object} opts
175
+ * @param {object} opts.sessions - Object with listSessions() -> session[]
176
+ * @param {object} opts.identity - Object with sign(data) and podId
177
+ * @param {number} [opts.clockSkewMs] - Max allowed clock skew in ms (default 30000)
178
+ * @param {Function} [opts.onLog] - Logging callback (level, msg)
179
+ */
180
+ constructor({ sessions, identity, clockSkewMs, onLog }) {
181
+ if (!sessions || typeof sessions.listSessions !== 'function') {
182
+ throw new Error('sessions is required and must have listSessions()')
183
+ }
184
+ if (!identity || typeof identity.sign !== 'function' || !identity.podId) {
185
+ throw new Error('identity is required and must have sign() and podId')
186
+ }
187
+
188
+ this.#sessions = sessions
189
+ this.#identity = identity
190
+ this.#clockSkewMs = clockSkewMs ?? TIMESTAMP_DEFAULTS.clockSkewMs
191
+ this.#onLog = onLog ?? (() => {})
192
+ }
193
+
194
+ /**
195
+ * Produce a TimestampProof for the given event hash.
196
+ *
197
+ * Collects timestamps from all connected peers (or uses provided
198
+ * peerTimestamps map for testing), computes the consensus median,
199
+ * rejects outliers, and signs the result.
200
+ *
201
+ * @param {string} eventHash - Hex hash of the event being timestamped
202
+ * @param {Map<string,number>} [peerTimestamps] - Optional peer timestamps for testing
203
+ * @returns {Promise<TimestampProof>}
204
+ */
205
+ async stamp(eventHash, peerTimestamps) {
206
+ if (!eventHash || typeof eventHash !== 'string') {
207
+ throw new Error('eventHash is required and must be a non-empty string')
208
+ }
209
+
210
+ const localTime = Date.now()
211
+ const localPodId = this.#identity.podId
212
+
213
+ // Build the full timestamp map: local + peers
214
+ /** @type {Map<string,number>} */
215
+ const allTimestamps = new Map()
216
+ allTimestamps.set(localPodId, localTime)
217
+
218
+ if (peerTimestamps) {
219
+ for (const [podId, ts] of peerTimestamps) {
220
+ allTimestamps.set(podId, ts)
221
+ }
222
+ }
223
+
224
+ const totalPeers = allTimestamps.size
225
+
226
+ // Compute median
227
+ const values = [...allTimestamps.values()]
228
+ const median = TimestampAuthority.computeMedian(values)
229
+
230
+ this.#onLog('debug', `Timestamp median: ${median} from ${totalPeers} peers`)
231
+
232
+ // Reject outliers
233
+ const accepted = this.#rejectOutliers(allTimestamps, median)
234
+ const acceptedCount = accepted.size
235
+
236
+ this.#onLog('info', `Accepted ${acceptedCount}/${totalPeers} peer timestamps`)
237
+
238
+ // Compute canonical timestamp as median of accepted values only
239
+ const acceptedValues = [...accepted.values()]
240
+ const canonicalTimestamp = TimestampAuthority.computeMedian(acceptedValues)
241
+
242
+ // Compute confidence
243
+ const confidence = this.#computeConfidence(acceptedCount, totalPeers)
244
+
245
+ // Sign the canonical timestamp
246
+ const signature = await this.#signTimestamp(eventHash, canonicalTimestamp)
247
+
248
+ // Build witness list from accepted peers
249
+ const witnesses = []
250
+ for (const [podId, ts] of accepted) {
251
+ const witnessData = `${eventHash}:${podId}:${ts}`
252
+ const witnessSig = await this.#identity.sign(witnessData)
253
+ witnesses.push({
254
+ podId,
255
+ localTimestamp: ts,
256
+ signature: toBase64(witnessSig),
257
+ })
258
+ }
259
+
260
+ return new TimestampProof({
261
+ eventHash,
262
+ canonicalTimestamp,
263
+ witnesses,
264
+ issuedBy: localPodId,
265
+ issuedAt: localTime,
266
+ confidence,
267
+ signature: toBase64(signature),
268
+ })
269
+ }
270
+
271
+ /**
272
+ * Verify a TimestampProof.
273
+ *
274
+ * Checks that the authority signature matches the eventHash +
275
+ * canonicalTimestamp, and validates witness signatures.
276
+ *
277
+ * @param {TimestampProof} proof
278
+ * @returns {Promise<{ valid: boolean, reason?: string }>}
279
+ */
280
+ async verify(proof) {
281
+ if (!(proof instanceof TimestampProof)) {
282
+ return { valid: false, reason: 'Not a TimestampProof instance' }
283
+ }
284
+
285
+ // Check basic structure
286
+ const structural = proof.verify()
287
+ if (!structural.valid) {
288
+ return { valid: false, reason: 'Structural validation failed' }
289
+ }
290
+
291
+ // Verify authority signature matches eventHash + canonicalTimestamp
292
+ const expectedData = `${proof.eventHash}:${proof.canonicalTimestamp}`
293
+ const expectedSig = await this.#identity.sign(expectedData)
294
+ const expectedB64 = toBase64(expectedSig)
295
+
296
+ if (proof.signature !== expectedB64) {
297
+ return { valid: false, reason: 'Authority signature mismatch — eventHash or timestamp was tampered' }
298
+ }
299
+
300
+ // Verify witness signatures
301
+ if (this.#identity.verify) {
302
+ for (const witness of proof.witnesses) {
303
+ const witnessData = `${proof.eventHash}:${witness.podId}:${witness.localTimestamp}`
304
+ const witnessSig = await this.#identity.sign(witnessData)
305
+ const witnessSigB64 = toBase64(witnessSig)
306
+ if (witness.signature !== witnessSigB64) {
307
+ return { valid: false, reason: `Witness signature mismatch for ${witness.podId}` }
308
+ }
309
+ }
310
+ }
311
+
312
+ return { valid: true }
313
+ }
314
+
315
+ /**
316
+ * Compute the current network time as the median of all peer clocks
317
+ * plus the local clock.
318
+ *
319
+ * @param {Map<string,number>} [peerTimestamps] - Optional peer timestamps
320
+ * @returns {number} Median timestamp in ms
321
+ */
322
+ getNetworkTime(peerTimestamps) {
323
+ const values = [Date.now()]
324
+
325
+ if (peerTimestamps) {
326
+ for (const ts of peerTimestamps.values()) {
327
+ values.push(ts)
328
+ }
329
+ }
330
+
331
+ return TimestampAuthority.computeMedian(values)
332
+ }
333
+
334
+ // -------------------------------------------------------------------------
335
+ // Static helpers (exposed for testing)
336
+ // -------------------------------------------------------------------------
337
+
338
+ /**
339
+ * Compute the median of an array of numbers.
340
+ *
341
+ * For even-length arrays, returns the mean of the two middle values.
342
+ * For odd-length arrays, returns the exact middle value.
343
+ *
344
+ * @param {number[]} values - Array of numeric values
345
+ * @returns {number}
346
+ */
347
+ static computeMedian(values) {
348
+ if (values.length === 0) return 0
349
+ const sorted = [...values].sort((a, b) => a - b)
350
+ const mid = Math.floor(sorted.length / 2)
351
+ if (sorted.length % 2 === 1) {
352
+ return sorted[mid]
353
+ }
354
+ return (sorted[mid - 1] + sorted[mid]) / 2
355
+ }
356
+
357
+ // -------------------------------------------------------------------------
358
+ // Private helpers
359
+ // -------------------------------------------------------------------------
360
+
361
+ /**
362
+ * Reject timestamps that deviate more than clockSkewMs from the median.
363
+ *
364
+ * @param {Map<string,number>} timestamps - Pod ID -> timestamp
365
+ * @param {number} median - Computed median timestamp
366
+ * @returns {Map<string,number>} Filtered map of accepted timestamps
367
+ */
368
+ #rejectOutliers(timestamps, median) {
369
+ const accepted = new Map()
370
+ for (const [podId, ts] of timestamps) {
371
+ if (Math.abs(ts - median) <= this.#clockSkewMs) {
372
+ accepted.set(podId, ts)
373
+ } else {
374
+ this.#onLog('warn', `Rejecting outlier from ${podId}: ${ts} (median=${median}, skew=${Math.abs(ts - median)}ms)`)
375
+ }
376
+ }
377
+ return accepted
378
+ }
379
+
380
+ /**
381
+ * Sign the canonical timestamp for a given event hash.
382
+ *
383
+ * @param {string} eventHash
384
+ * @param {number} canonicalMs - The canonical timestamp in ms
385
+ * @returns {Promise<Uint8Array>}
386
+ */
387
+ async #signTimestamp(eventHash, canonicalMs) {
388
+ const data = `${eventHash}:${canonicalMs}`
389
+ return this.#identity.sign(data)
390
+ }
391
+
392
+ /**
393
+ * Compute confidence as ratio of accepted witnesses to total peers.
394
+ *
395
+ * @param {number} accepted - Number of accepted witnesses
396
+ * @param {number} total - Total number of peers (including local)
397
+ * @returns {number} 0 to 1
398
+ */
399
+ #computeConfidence(accepted, total) {
400
+ if (total === 0) return 0
401
+ return accepted / total
402
+ }
403
+ }