@svrnsec/pulse 0.3.1 → 0.5.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,311 @@
1
+ /**
2
+ * @sovereign/pulse — Electrical Network Frequency (ENF) Detection
3
+ *
4
+ * ┌─────────────────────────────────────────────────────────────────────────┐
5
+ * │ WHAT THIS IS │
6
+ * │ │
7
+ * │ Power grids operate at a nominal frequency — 60 Hz in the Americas, │
8
+ * │ 50 Hz in Europe, Asia, Africa, and Australia. This frequency is not │
9
+ * │ perfectly stable. It deviates by ±0.05 Hz in real time as generators │
10
+ * │ spin up and down to match load. These deviations are unique, logged │
11
+ * │ by grid operators, and have been used in forensics since 2010 to │
12
+ * │ timestamp recordings to within seconds. │
13
+ * │ │
14
+ * │ We are the first to measure it from a browser. │
15
+ * └─────────────────────────────────────────────────────────────────────────┘
16
+ *
17
+ * Signal path
18
+ * ───────────
19
+ * AC mains (50/60 Hz)
20
+ * → ATX power supply (full-wave rectified → 100/120 Hz ripple on DC rail)
21
+ * → Voltage Regulator Module (VRM) on motherboard
22
+ * → CPU Vcore (supply voltage to processor dies)
23
+ * → Transistor switching speed (slightly modulated by Vcore)
24
+ * → Matrix multiply loop timing (measurably longer when Vcore dips)
25
+ * → Our microsecond-resolution timing probe
26
+ *
27
+ * The ripple amplitude at the timing layer is ~10–100 ns — invisible to
28
+ * performance.now() at 1 ms resolution, clearly visible with Atomics-based
29
+ * microsecond timing. This is why this module depends on sabTimer.js.
30
+ *
31
+ * What we detect
32
+ * ──────────────
33
+ * gridFrequency 50.0 or 60.0 Hz (nominal), ±0.5 Hz measured
34
+ * gridRegion 'americas' (60 Hz) | 'emea_apac' (50 Hz) | 'unknown'
35
+ * ripplePresent true if the 100/120 Hz harmonic is statistically significant
36
+ * ripplePower power of the dominant grid harmonic (0–1)
37
+ * enfDeviation precise measured frequency – nominal (Hz) — temporal fingerprint
38
+ * temporalHash BLAKE3 of (enfDeviation + timestamp) — attestation anchor
39
+ *
40
+ * What this proves
41
+ * ───────────────
42
+ * 1. The device is connected to a real AC power grid (rules out cloud VMs,
43
+ * UPS-backed datacenter servers, and battery-only devices off-grid)
44
+ * 2. The geographic grid region (50 Hz vs 60 Hz — no IP, no location API)
45
+ * 3. A temporal fingerprint that can be cross-referenced against public ENF
46
+ * logs (e.g., www.gridwatch.templar.linux.org.uk) to verify the session
47
+ * timestamp is authentic
48
+ *
49
+ * Why VMs fail
50
+ * ────────────
51
+ * Datacenter power is conditioned, filtered, and UPS-backed. Grid frequency
52
+ * deviations are removed before they reach the server. Cloud VMs receive
53
+ * perfectly regulated power — the ENF signal does not exist in their timing
54
+ * measurements. This is a physical property of datacenter infrastructure,
55
+ * not a software configuration that can be patched or spoofed.
56
+ *
57
+ * A VM attempting to inject synthetic ENF ripple into its virtual clock
58
+ * would need to:
59
+ * 1. Know the real-time ENF of the target grid region (requires live API)
60
+ * 2. Modulate the virtual TSC at sub-microsecond precision
61
+ * 3. Match the precise VRM transfer function of the target motherboard
62
+ * This is not a realistic attack surface.
63
+ *
64
+ * Battery devices
65
+ * ───────────────
66
+ * Laptops on battery have no AC ripple. The module detects this via absence
67
+ * of both 100 Hz and 120 Hz signal, combined with very low ripple variance.
68
+ * This is handled by the 'battery_or_conditioned' verdict — treated as
69
+ * inconclusive rather than VM (real laptops exist).
70
+ *
71
+ * Required: crossOriginIsolated = true (COOP + COEP headers)
72
+ * The SAB microsecond timer is required for ENF detection. On browsers where
73
+ * it is unavailable, the module returns { enfAvailable: false }.
74
+ */
75
+
76
+ import { isSabAvailable, collectHighResTimings } from './sabTimer.js';
77
+
78
+ // ── Grid frequency constants ──────────────────────────────────────────────────
79
+ const GRID_60HZ_NOMINAL = 60.0; // Americas, parts of Japan & Korea
80
+ const GRID_50HZ_NOMINAL = 50.0; // EMEA, APAC, most of Asia
81
+ const RIPPLE_60HZ = 120.0; // Full-wave rectified: 2 × 60 Hz
82
+ const RIPPLE_50HZ = 100.0; // Full-wave rectified: 2 × 50 Hz
83
+ const RIPPLE_SLACK_HZ = 2.0; // ±2 Hz around nominal (accounts for VRM response)
84
+ const MIN_RIPPLE_POWER = 0.04; // Minimum power ratio to declare ripple present
85
+ const SNR_THRESHOLD = 2.0; // Signal-to-noise ratio for confident detection
86
+
87
+ // ── Probe parameters ──────────────────────────────────────────────────────────
88
+ // We need enough samples at sufficient rate to resolve 100–120 Hz.
89
+ // Nyquist: sample_rate > 240 Hz (need >2× the highest target frequency).
90
+ // With ~1 ms per iteration, 100 Hz ≈ 10 samples per cycle — adequate.
91
+ // We want at least 20 full cycles → 200 iterations minimum.
92
+ const PROBE_ITERATIONS = 512; // power of 2 for clean FFT
93
+ const PROBE_MATRIX_SIZE = 16; // small matrix → ~1 ms/iter → ~500 Hz sample rate
94
+
95
+ /* ─── collectEnfTimings ─────────────────────────────────────────────────────── */
96
+
97
+ /**
98
+ * @param {object} [opts]
99
+ * @param {number} [opts.iterations=512]
100
+ * @returns {Promise<EnfResult>}
101
+ */
102
+ export async function collectEnfTimings(opts = {}) {
103
+ const { iterations = PROBE_ITERATIONS } = opts;
104
+
105
+ if (!isSabAvailable()) {
106
+ return _noEnf('SharedArrayBuffer not available — COOP+COEP headers required');
107
+ }
108
+
109
+ // Collect high-resolution CPU timing series
110
+ const { timings, resolutionUs } = collectHighResTimings({
111
+ iterations,
112
+ matrixSize: PROBE_MATRIX_SIZE,
113
+ });
114
+
115
+ if (timings.length < 128) {
116
+ return _noEnf('insufficient timing samples');
117
+ }
118
+
119
+ // Estimate the sample rate from actual timing
120
+ const meanIterMs = timings.reduce((s, v) => s + v, 0) / timings.length;
121
+ const sampleRateHz = meanIterMs > 0 ? 1000 / meanIterMs : 0;
122
+
123
+ if (sampleRateHz < 60) {
124
+ return _noEnf(`sample rate too low for ENF detection: ${sampleRateHz.toFixed(0)} Hz`);
125
+ }
126
+
127
+ // ── Power Spectral Density ────────────────────────────────────────────────
128
+ const n = timings.length;
129
+ const psd = _computePsd(timings, sampleRateHz);
130
+
131
+ // Find the dominant frequency peak
132
+ const peakIdx = psd.reduce((best, v, i) => v > psd[best] ? i : best, 0);
133
+ const peakFreq = psd.freqs[peakIdx];
134
+
135
+ // Power in 100 Hz window vs 120 Hz window
136
+ const power100 = _bandPower(psd, RIPPLE_50HZ, RIPPLE_SLACK_HZ);
137
+ const power120 = _bandPower(psd, RIPPLE_60HZ, RIPPLE_SLACK_HZ);
138
+ const baseline = _baselinePower(psd, [
139
+ [RIPPLE_50HZ - RIPPLE_SLACK_HZ, RIPPLE_50HZ + RIPPLE_SLACK_HZ],
140
+ [RIPPLE_60HZ - RIPPLE_SLACK_HZ, RIPPLE_60HZ + RIPPLE_SLACK_HZ],
141
+ ]);
142
+
143
+ const snr100 = baseline > 0 ? power100 / baseline : 0;
144
+ const snr120 = baseline > 0 ? power120 / baseline : 0;
145
+
146
+ // ── Verdict ───────────────────────────────────────────────────────────────
147
+ const has100 = power100 > MIN_RIPPLE_POWER && snr100 > SNR_THRESHOLD;
148
+ const has120 = power120 > MIN_RIPPLE_POWER && snr120 > SNR_THRESHOLD;
149
+
150
+ let gridFrequency = null;
151
+ let gridRegion = 'unknown';
152
+ let ripplePower = 0;
153
+ let nominalHz = null;
154
+
155
+ if (has120 && power120 >= power100) {
156
+ gridFrequency = GRID_60HZ_NOMINAL;
157
+ gridRegion = 'americas';
158
+ ripplePower = power120;
159
+ nominalHz = RIPPLE_60HZ;
160
+ } else if (has100) {
161
+ gridFrequency = GRID_50HZ_NOMINAL;
162
+ gridRegion = 'emea_apac';
163
+ ripplePower = power100;
164
+ nominalHz = RIPPLE_50HZ;
165
+ }
166
+
167
+ const ripplePresent = has100 || has120;
168
+
169
+ // ── ENF deviation (temporal fingerprint) ─────────────────────────────────
170
+ // The precise ripple frequency deviates from nominal by ±0.1 Hz in real time.
171
+ // We measure the peak frequency in the ripple band to extract this deviation.
172
+ let enfDeviation = null;
173
+ if (ripplePresent && nominalHz !== null) {
174
+ const preciseRippleFreq = _precisePeakFreq(psd, nominalHz, RIPPLE_SLACK_HZ);
175
+ enfDeviation = +(preciseRippleFreq - nominalHz).toFixed(3); // Hz deviation from nominal
176
+ }
177
+
178
+ // ── Verdict ───────────────────────────────────────────────────────────────
179
+ const verdict =
180
+ !ripplePresent ? 'no_grid_signal' // VM, UPS, or battery
181
+ : gridRegion === 'americas' ? 'grid_60hz'
182
+ : gridRegion === 'emea_apac' ? 'grid_50hz'
183
+ : 'grid_detected_region_unknown';
184
+
185
+ const isVmIndicator = !ripplePresent && sampleRateHz > 100;
186
+ // High sample rate + no ripple = conditioned power (datacenter)
187
+
188
+ return {
189
+ enfAvailable: true,
190
+ ripplePresent,
191
+ gridFrequency,
192
+ gridRegion,
193
+ ripplePower: +ripplePower.toFixed(4),
194
+ snr50hz: +snr100.toFixed(2),
195
+ snr60hz: +snr120.toFixed(2),
196
+ enfDeviation,
197
+ sampleRateHz: +sampleRateHz.toFixed(1),
198
+ resolutionUs,
199
+ verdict,
200
+ isVmIndicator,
201
+ // For cross-referencing against public ENF databases (forensic timestamp)
202
+ temporalAnchor: enfDeviation !== null ? {
203
+ nominalHz,
204
+ measuredRippleHz: +(nominalHz + enfDeviation).toFixed(4),
205
+ capturedAt: Date.now(),
206
+ // Matches format used by ENF forensic databases:
207
+ // https://www.enf.cc | UK National Grid ESO data
208
+ gridHz: gridFrequency,
209
+ } : null,
210
+ };
211
+ }
212
+
213
+ /* ─── Power Spectral Density (Welch-inspired DFT) ───────────────────────── */
214
+
215
+ function _computePsd(signal, sampleRateHz) {
216
+ const n = signal.length;
217
+ const mean = signal.reduce((s, v) => s + v, 0) / n;
218
+
219
+ // Remove DC offset and apply Hann window
220
+ const windowed = signal.map((v, i) => {
221
+ const w = 0.5 * (1 - Math.cos((2 * Math.PI * i) / (n - 1))); // Hann
222
+ return (v - mean) * w;
223
+ });
224
+
225
+ // DFT up to Nyquist — only need up to ~200 Hz so we cap bins
226
+ const maxFreq = Math.min(200, sampleRateHz / 2);
227
+ const maxBin = Math.floor(maxFreq * n / sampleRateHz);
228
+
229
+ const powers = new Float64Array(maxBin);
230
+ const freqs = new Float64Array(maxBin);
231
+
232
+ for (let k = 1; k < maxBin; k++) {
233
+ let re = 0, im = 0;
234
+ for (let t = 0; t < n; t++) {
235
+ const angle = (2 * Math.PI * k * t) / n;
236
+ re += windowed[t] * Math.cos(angle);
237
+ im -= windowed[t] * Math.sin(angle);
238
+ }
239
+ powers[k] = (re * re + im * im) / (n * n);
240
+ freqs[k] = (k * sampleRateHz) / n;
241
+ }
242
+
243
+ // Normalise powers so they sum to 1 (makes thresholds sample-count-independent)
244
+ const total = powers.reduce((s, v) => s + v, 0);
245
+ if (total > 0) for (let i = 0; i < powers.length; i++) powers[i] /= total;
246
+
247
+ return { powers, freqs };
248
+ }
249
+
250
+ function _bandPower(psd, centerHz, halfwidthHz) {
251
+ let power = 0;
252
+ for (let i = 0; i < psd.freqs.length; i++) {
253
+ if (Math.abs(psd.freqs[i] - centerHz) <= halfwidthHz) {
254
+ power += psd.powers[i];
255
+ }
256
+ }
257
+ return power;
258
+ }
259
+
260
+ function _baselinePower(psd, excludeBands) {
261
+ let sum = 0, count = 0;
262
+ for (let i = 0; i < psd.freqs.length; i++) {
263
+ const f = psd.freqs[i];
264
+ const excluded = excludeBands.some(([lo, hi]) => f >= lo && f <= hi);
265
+ if (!excluded && f > 10 && f < 200) { sum += psd.powers[i]; count++; }
266
+ }
267
+ return count > 0 ? sum / count : 0;
268
+ }
269
+
270
+ function _precisePeakFreq(psd, centerHz, halfwidthHz) {
271
+ // Quadratic interpolation around the peak bin for sub-bin precision
272
+ let peakBin = 0, peakPow = -Infinity;
273
+ for (let i = 0; i < psd.freqs.length; i++) {
274
+ if (Math.abs(psd.freqs[i] - centerHz) <= halfwidthHz && psd.powers[i] > peakPow) {
275
+ peakPow = psd.powers[i]; peakBin = i;
276
+ }
277
+ }
278
+ if (peakBin <= 0 || peakBin >= psd.powers.length - 1) return psd.freqs[peakBin];
279
+
280
+ // Quadratic peak interpolation (Jacobsen method)
281
+ const alpha = psd.powers[peakBin - 1];
282
+ const beta = psd.powers[peakBin];
283
+ const gamma = psd.powers[peakBin + 1];
284
+ const denom = alpha - 2 * beta + gamma;
285
+ if (Math.abs(denom) < 1e-14) return psd.freqs[peakBin];
286
+ const deltaBin = 0.5 * (alpha - gamma) / denom;
287
+ const binWidth = psd.freqs[1] - psd.freqs[0];
288
+ return psd.freqs[peakBin] + deltaBin * binWidth;
289
+ }
290
+
291
+ function _noEnf(reason) {
292
+ return {
293
+ enfAvailable: false, ripplePresent: false, gridFrequency: null,
294
+ gridRegion: 'unknown', ripplePower: 0, snr50hz: 0, snr60hz: 0,
295
+ enfDeviation: null, sampleRateHz: 0, resolutionUs: 0,
296
+ verdict: 'unavailable', isVmIndicator: false, temporalAnchor: null, reason,
297
+ };
298
+ }
299
+
300
+ /**
301
+ * @typedef {object} EnfResult
302
+ * @property {boolean} enfAvailable
303
+ * @property {boolean} ripplePresent false = VM / datacenter / battery
304
+ * @property {number|null} gridFrequency 50 or 60 Hz
305
+ * @property {string} gridRegion 'americas' | 'emea_apac' | 'unknown'
306
+ * @property {number} ripplePower normalised PSD power at grid harmonic
307
+ * @property {number|null} enfDeviation Hz deviation from nominal (temporal fingerprint)
308
+ * @property {string} verdict
309
+ * @property {boolean} isVmIndicator true if signal absence + high sample rate
310
+ * @property {object|null} temporalAnchor forensic timestamp anchor
311
+ */
@@ -0,0 +1,195 @@
1
+ /**
2
+ * @sovereign/pulse — Entropy Collector
3
+ *
4
+ * Bridges the Rust/WASM matrix-multiply probe into JavaScript.
5
+ * The WASM module is lazily initialised once and cached for subsequent calls.
6
+ */
7
+
8
+ import { collectEntropyAdaptive } from './adaptive.js';
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // WASM loader (lazy singleton)
12
+ // ---------------------------------------------------------------------------
13
+ let _wasmModule = null;
14
+ let _initPromise = null;
15
+
16
+ /**
17
+ * Initialise (or return the cached) WASM module.
18
+ * Works in browsers (via fetch), in Electron (Node.js context), and in
19
+ * Jest/Vitest via a manual WASM path override.
20
+ *
21
+ * @param {string} [wasmPath] – override path/URL to the .wasm binary
22
+ */
23
+ async function initWasm(wasmPath) {
24
+ if (_wasmModule) return _wasmModule;
25
+ if (_initPromise) return _initPromise;
26
+
27
+ _initPromise = (async () => {
28
+ // Dynamic import so bundlers can tree-shake this for server-only builds.
29
+ const { default: init, run_entropy_probe, run_memory_probe, compute_autocorrelation } =
30
+ await import('../../pkg/pulse_core.js');
31
+
32
+ const url = wasmPath ?? new URL('../../pkg/pulse_core_bg.wasm', import.meta.url).href;
33
+ await init(url);
34
+
35
+ _wasmModule = { run_entropy_probe, run_memory_probe, compute_autocorrelation };
36
+ return _wasmModule;
37
+ })();
38
+
39
+ return _initPromise;
40
+ }
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // collectEntropy
44
+ // ---------------------------------------------------------------------------
45
+
46
+ /**
47
+ * Run the WASM entropy probe and return raw timing data.
48
+ *
49
+ * @param {object} opts
50
+ * @param {number} [opts.iterations=200] - number of matrix-multiply rounds
51
+ * @param {number} [opts.matrixSize=64] - N for the N×N matrices
52
+ * @param {number} [opts.memSizeKb=512] - size of the memory bandwidth probe
53
+ * @param {number} [opts.memIterations=50]
54
+ * @param {boolean} [opts.phased=true] - run cold/load/hot phases for entropy-jitter ratio
55
+ * @param {string} [opts.wasmPath] - optional custom WASM binary path
56
+ *
57
+ * @returns {Promise<EntropyResult>}
58
+ */
59
+ export async function collectEntropy(opts = {}) {
60
+ const {
61
+ iterations = 200,
62
+ matrixSize = 64,
63
+ memSizeKb = 512,
64
+ memIterations = 50,
65
+ phased = true,
66
+ adaptive = false,
67
+ adaptiveThreshold = 0.85,
68
+ onBatch,
69
+ wasmPath,
70
+ } = opts;
71
+
72
+ const wasm = await initWasm(wasmPath);
73
+ const t_start = Date.now();
74
+
75
+ let phases = null;
76
+ let timings, resolutionProbe, checksum, timerGranularityMs;
77
+ let _adaptiveInfo = null;
78
+
79
+ // ── Adaptive mode: smart early exit, fastest for obvious VMs ──────────
80
+ if (adaptive) {
81
+ const r = await collectEntropyAdaptive(wasm, {
82
+ minIterations: 50,
83
+ maxIterations: iterations,
84
+ batchSize: 25,
85
+ vmThreshold: adaptiveThreshold,
86
+ hwThreshold: 0.80,
87
+ hwMinIterations: 75,
88
+ matrixSize,
89
+ onBatch,
90
+ });
91
+ timings = r.timings;
92
+ resolutionProbe = r.resolutionProbe ?? [];
93
+ checksum = r.checksum;
94
+ timerGranularityMs = r.timerGranularityMs;
95
+ _adaptiveInfo = { earlyExit: r.earlyExit, batches: r.batches, elapsedMs: r.elapsedMs };
96
+
97
+ // ── Phased collection: cold → load → hot ──────────────────────────────
98
+ // Each phase runs a separate WASM probe. On real hardware, sustained load
99
+ // increases thermal noise so Phase 3 (hot) entropy is measurably higher
100
+ // than Phase 1 (cold). A VM's hypervisor clock is insensitive to guest
101
+ // thermal state, so all three phases return nearly identical entropy.
102
+ } else if (phased && iterations >= 60) {
103
+ const coldN = Math.floor(iterations * 0.25); // ~25% cold
104
+ const loadN = Math.floor(iterations * 0.50); // ~50% sustained load
105
+ const hotN = iterations - coldN - loadN; // ~25% hot
106
+
107
+ const cold = wasm.run_entropy_probe(coldN, matrixSize);
108
+ const load = wasm.run_entropy_probe(loadN, matrixSize);
109
+ const hot = wasm.run_entropy_probe(hotN, matrixSize);
110
+
111
+ const coldTimings = Array.from(cold.timings);
112
+ const loadTimings = Array.from(load.timings);
113
+ const hotTimings = Array.from(hot.timings);
114
+
115
+ timings = [...coldTimings, ...loadTimings, ...hotTimings];
116
+ resolutionProbe = Array.from(cold.resolution_probe);
117
+ checksum = (cold.checksum + load.checksum + hot.checksum).toString();
118
+
119
+ const { detectQuantizationEntropy } = await import('../analysis/jitter.js');
120
+ const coldQE = detectQuantizationEntropy(coldTimings);
121
+ const hotQE = detectQuantizationEntropy(hotTimings);
122
+
123
+ phases = {
124
+ cold: { n: coldN, timings: coldTimings, qe: coldQE, mean: _mean(coldTimings) },
125
+ load: { n: loadN, timings: loadTimings, qe: detectQuantizationEntropy(loadTimings), mean: _mean(loadTimings) },
126
+ hot: { n: hotN, timings: hotTimings, qe: hotQE, mean: _mean(hotTimings) },
127
+ // The key signal: entropy growth under load.
128
+ // Real silicon: hotQE / coldQE typically 1.05 – 1.40
129
+ // VM: hotQE / coldQE typically 0.95 – 1.05 (flat)
130
+ entropyJitterRatio: coldQE > 0 ? hotQE / coldQE : 1.0,
131
+ };
132
+ } else {
133
+ // Single-phase fallback (fewer iterations or phased disabled)
134
+ const result = wasm.run_entropy_probe(iterations, matrixSize);
135
+ timings = Array.from(result.timings);
136
+ resolutionProbe = Array.from(result.resolution_probe);
137
+ checksum = result.checksum.toString();
138
+ }
139
+
140
+ // ── Timer resolution (non-adaptive path only — adaptive computes its own) ─
141
+ if (!adaptive) {
142
+ const resDeltas = [];
143
+ for (let i = 1; i < resolutionProbe.length; i++) {
144
+ const d = resolutionProbe[i] - resolutionProbe[i - 1];
145
+ if (d > 0) resDeltas.push(d);
146
+ }
147
+ timerGranularityMs = resDeltas.length
148
+ ? resDeltas.reduce((a, b) => Math.min(a, b), Infinity)
149
+ : null;
150
+ }
151
+
152
+ // ── Autocorrelation at diagnostic lags ────────────────────────────────
153
+ // Extended lags catch long-period steal-time rhythms (Xen: ~150 iters)
154
+ const lags = [1, 2, 3, 5, 10, 25, 50];
155
+ const autocorrelations = {};
156
+ for (const lag of lags) {
157
+ if (lag < timings.length) {
158
+ autocorrelations[`lag${lag}`] = wasm.compute_autocorrelation(timings, lag);
159
+ }
160
+ }
161
+
162
+ // ── Secondary probe: memory bandwidth jitter ───────────────────────────
163
+ const memTimings = Array.from(wasm.run_memory_probe(memSizeKb, memIterations));
164
+
165
+ return {
166
+ timings,
167
+ resolutionProbe,
168
+ timerGranularityMs,
169
+ autocorrelations,
170
+ memTimings,
171
+ phases,
172
+ checksum,
173
+ collectedAt: t_start,
174
+ iterations: timings.length, // actual count (adaptive may differ from requested)
175
+ matrixSize,
176
+ adaptive: _adaptiveInfo, // null in non-adaptive mode
177
+ };
178
+ }
179
+
180
+ function _mean(arr) {
181
+ return arr.length ? arr.reduce((s, v) => s + v, 0) / arr.length : 0;
182
+ }
183
+
184
+ /**
185
+ * @typedef {object} EntropyResult
186
+ * @property {number[]} timings - per-iteration wall-clock deltas (ms)
187
+ * @property {number[]} resolutionProbe - raw successive perf.now() readings
188
+ * @property {number|null} timerGranularityMs - effective timer resolution
189
+ * @property {object} autocorrelations - { lag1, lag2, lag3, lag5, lag10 }
190
+ * @property {number[]} memTimings - memory-probe timings (ms)
191
+ * @property {string} checksum - proof the computation ran
192
+ * @property {number} collectedAt - Date.now() at probe start
193
+ * @property {number} iterations
194
+ * @property {number} matrixSize
195
+ */