@svrnsec/pulse 0.3.1 → 0.4.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/bin/svrnsec-pulse.js +7 -0
- package/index.d.ts +130 -0
- package/package.json +51 -24
- package/src/analysis/audio.js +213 -0
- package/src/analysis/coherence.js +502 -0
- package/src/analysis/heuristic.js +428 -0
- package/src/analysis/jitter.js +446 -0
- package/src/analysis/llm.js +472 -0
- package/src/analysis/provider.js +248 -0
- package/src/analysis/trustScore.js +331 -0
- package/src/cli/args.js +36 -0
- package/src/cli/commands/scan.js +192 -0
- package/src/cli/runner.js +157 -0
- package/src/collector/adaptive.js +200 -0
- package/src/collector/bio.js +287 -0
- package/src/collector/canvas.js +239 -0
- package/src/collector/dram.js +203 -0
- package/src/collector/enf.js +311 -0
- package/src/collector/entropy.js +195 -0
- package/src/collector/gpu.js +245 -0
- package/src/collector/sabTimer.js +191 -0
- package/src/fingerprint.js +475 -0
- package/src/index.js +342 -0
- package/src/integrations/react-native.js +459 -0
- package/src/proof/challenge.js +249 -0
- package/src/terminal.js +263 -0
- package/src/update-notifier.js +264 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* svrnsec-pulse scan
|
|
3
|
+
*
|
|
4
|
+
* Runs the full probe locally (Node.js JS engine, no browser required),
|
|
5
|
+
* computes the TrustScore, and renders a pretty result card.
|
|
6
|
+
*
|
|
7
|
+
* Options:
|
|
8
|
+
* --json output raw JSON instead of the visual card
|
|
9
|
+
* --iterations override probe iteration count (default 200)
|
|
10
|
+
* --no-banner suppress the banner
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { generateNonce } from '../../proof/validator.js';
|
|
14
|
+
import { computeTrustScore, formatTrustScore } from '../../analysis/trustScore.js';
|
|
15
|
+
import { collectDramTimings } from '../../collector/dram.js';
|
|
16
|
+
import { collectEnfTimings } from '../../collector/enf.js';
|
|
17
|
+
import { renderProbeResult } from '../../terminal.js';
|
|
18
|
+
import { CURRENT_VERSION } from '../../update-notifier.js';
|
|
19
|
+
|
|
20
|
+
// ANSI helpers (inlined — no dep on terminal.js palette export)
|
|
21
|
+
const isTTY = () => process.stderr.isTTY && !process.env.NO_COLOR;
|
|
22
|
+
const A = { reset:'\x1b[0m', bold:'\x1b[1m', dim:'\x1b[2m', gray:'\x1b[90m',
|
|
23
|
+
bwhite:'\x1b[97m', bmagenta:'\x1b[95m', bcyan:'\x1b[96m', bgreen:'\x1b[92m',
|
|
24
|
+
byellow:'\x1b[93m', bred:'\x1b[91m' };
|
|
25
|
+
const c = (code, s) => isTTY() ? `${code}${s}${A.reset}` : s;
|
|
26
|
+
const dim = (s) => c(A.dim, s);
|
|
27
|
+
const mag = (s) => c(A.bmagenta, s);
|
|
28
|
+
const wh = (s) => c(A.bwhite, s);
|
|
29
|
+
const cy = (s) => c(A.bcyan, s);
|
|
30
|
+
const gr = (s) => c(A.bgreen, s);
|
|
31
|
+
const ye = (s) => c(A.byellow, s);
|
|
32
|
+
const re = (s) => c(A.bred, s);
|
|
33
|
+
const gy = (s) => c(A.gray, s);
|
|
34
|
+
const bd = (s) => c(A.bold, s);
|
|
35
|
+
|
|
36
|
+
function bar(pct, w = 24) {
|
|
37
|
+
const f = Math.round(Math.min(1, pct) * w);
|
|
38
|
+
const fill = isTTY() ? `\x1b[92m${'█'.repeat(f)}\x1b[0m` : '█'.repeat(f);
|
|
39
|
+
const void_ = gy('░'.repeat(w - f));
|
|
40
|
+
return fill + void_;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function spinner(ms = 80) {
|
|
44
|
+
if (!isTTY()) return { stop: () => {} };
|
|
45
|
+
const frames = ['⠋','⠙','⠹','⠸','⠼','⠴','⠦','⠧','⠇','⠏'];
|
|
46
|
+
let i = 0;
|
|
47
|
+
const iv = setInterval(() => {
|
|
48
|
+
process.stderr.write(`\r ${gy(frames[i++ % frames.length])} `);
|
|
49
|
+
}, ms);
|
|
50
|
+
return { stop: (msg = '') => { clearInterval(iv); process.stderr.write(`\r ${msg}\n`); } };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function runScan(args) {
|
|
54
|
+
const jsonMode = args.has('json') || args.has('j');
|
|
55
|
+
const iterations = parseInt(args.get('iterations', '200'), 10);
|
|
56
|
+
const noBanner = args.has('no-banner');
|
|
57
|
+
|
|
58
|
+
if (!noBanner && isTTY()) {
|
|
59
|
+
process.stderr.write(
|
|
60
|
+
'\n' +
|
|
61
|
+
gy(' ┌─────────────────────────────────────────────┐') + '\n' +
|
|
62
|
+
gy(' │') + ` ${mag('SVRN')}${wh(':PULSE')} ${gy('scan')} ` +
|
|
63
|
+
gy('Physical Turing Test │') + '\n' +
|
|
64
|
+
gy(' │') + ` ${gy(`v${CURRENT_VERSION}`)} ` +
|
|
65
|
+
cy('https://github.com/ayronny14-alt/Svrn-Pulse-Security') + ` ` +
|
|
66
|
+
gy('│') + '\n' +
|
|
67
|
+
gy(' └─────────────────────────────────────────────┘') + '\n\n'
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const t0 = Date.now();
|
|
72
|
+
const nonce = generateNonce();
|
|
73
|
+
|
|
74
|
+
// ── Entropy probe ─────────────────────────────────────────────────────────
|
|
75
|
+
if (isTTY() && !jsonMode) {
|
|
76
|
+
process.stderr.write(gy(' Probing entropy') + ' ');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const { collectEntropy } = await import('../../collector/entropy.js');
|
|
80
|
+
const spin = spinner();
|
|
81
|
+
|
|
82
|
+
let entropy;
|
|
83
|
+
try {
|
|
84
|
+
entropy = await collectEntropy({
|
|
85
|
+
iterations,
|
|
86
|
+
phased: true,
|
|
87
|
+
adaptive: true,
|
|
88
|
+
onBatch: (meta) => {
|
|
89
|
+
if (isTTY() && !jsonMode) {
|
|
90
|
+
spin.stop(
|
|
91
|
+
`${bar(meta.pct / 100, 20)} ${gy(meta.pct + '%')} ` +
|
|
92
|
+
`vm:${(meta.vmConf * 100).toFixed(0)}% hw:${(meta.hwConf * 100).toFixed(0)}%`
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
spin.stop(gr('✓ entropy collected'));
|
|
98
|
+
} catch (err) {
|
|
99
|
+
spin.stop(re('✗ entropy probe failed: ' + err.message));
|
|
100
|
+
process.exit(1);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ── Extended signals ──────────────────────────────────────────────────────
|
|
104
|
+
if (isTTY() && !jsonMode) process.stderr.write('\n');
|
|
105
|
+
|
|
106
|
+
const [enf, dram] = await Promise.allSettled([
|
|
107
|
+
collectEnfTimings(),
|
|
108
|
+
Promise.resolve(collectDramTimings()),
|
|
109
|
+
]).then(results => results.map(r => r.status === 'fulfilled' ? r.value : null));
|
|
110
|
+
|
|
111
|
+
// ── Analysis ──────────────────────────────────────────────────────────────
|
|
112
|
+
const { classifyJitter } = await import('../../analysis/jitter.js');
|
|
113
|
+
const { buildProof, buildCommitment } = await import('../../proof/fingerprint.js');
|
|
114
|
+
|
|
115
|
+
// Minimal bio stub for non-browser context
|
|
116
|
+
const bioStub = {
|
|
117
|
+
mouse: { sampleCount:0,ieiMean:0,ieiCV:0,velocityP50:0,velocityP95:0,angularJerkMean:0,pressureVariance:0 },
|
|
118
|
+
keyboard: { sampleCount:0,dwellMean:0,dwellCV:0,ikiMean:0,ikiCV:0 },
|
|
119
|
+
interferenceCoefficient: 0,
|
|
120
|
+
hasActivity: false,
|
|
121
|
+
durationMs: 0,
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const canvasStub = {
|
|
125
|
+
webglRenderer:null,webglVendor:null,webglVersion:null,
|
|
126
|
+
webglPixelHash:null,canvas2dHash:null,extensionCount:0,
|
|
127
|
+
isSoftwareRenderer:false,available:false,
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const audioStub = {
|
|
131
|
+
available:false,workletAvailable:false,callbackJitterCV:0,
|
|
132
|
+
noiseFloorMean:0,noiseFloorStd:0,sampleRate:0,callbackCount:0,
|
|
133
|
+
jitterMeanMs:0,jitterP95Ms:0,
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const jitter = classifyJitter(entropy.timings, { autocorrelations: entropy.autocorrelations });
|
|
137
|
+
const payload = buildProof({ entropy, jitter, bio: bioStub, canvas: canvasStub, audio: audioStub, enf, dram, nonce });
|
|
138
|
+
const { hash } = buildCommitment(payload);
|
|
139
|
+
|
|
140
|
+
const ts = computeTrustScore(payload, { enf, dram });
|
|
141
|
+
const elapsed = Date.now() - t0;
|
|
142
|
+
|
|
143
|
+
// ── Output ────────────────────────────────────────────────────────────────
|
|
144
|
+
if (jsonMode) {
|
|
145
|
+
process.stdout.write(JSON.stringify({ payload, hash, trustScore: ts, elapsed }, null, 2) + '\n');
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Pretty result card
|
|
150
|
+
renderProbeResult({ payload, hash, enf, dram, elapsedMs: elapsed });
|
|
151
|
+
|
|
152
|
+
// TrustScore panel
|
|
153
|
+
const gradeColor = ts.score >= 75 ? A.bgreen : ts.score >= 45 ? A.byellow : A.bred;
|
|
154
|
+
const W = 54;
|
|
155
|
+
const vb = gy('│');
|
|
156
|
+
|
|
157
|
+
process.stderr.write(gy('╭' + '─'.repeat(W + 2) + '╮') + '\n');
|
|
158
|
+
process.stderr.write(`${vb} ${bd('TRUST SCORE')}${' '.repeat(W - 9)} ${vb}\n`);
|
|
159
|
+
process.stderr.write(gy('├' + '─'.repeat(W + 2) + '┤') + '\n');
|
|
160
|
+
process.stderr.write(`${vb} ${' '.repeat(Math.floor((W - 8) / 2))}${c(gradeColor + A.bold, `${ts.score} / 100`)}${' '.repeat(Math.ceil((W - 8) / 2))} ${vb}\n`);
|
|
161
|
+
process.stderr.write(`${vb} ${' '.repeat(Math.floor((W - ts.grade.length - ts.label.length - 3) / 2))}${c(gradeColor, ts.grade)} · ${c(gradeColor, ts.label)}${' '.repeat(Math.ceil((W - ts.grade.length - ts.label.length - 3) / 2))} ${vb}\n`);
|
|
162
|
+
process.stderr.write(`${vb} ${' '.repeat(W)} ${vb}\n`);
|
|
163
|
+
|
|
164
|
+
// Per-signal bars
|
|
165
|
+
const layers = [
|
|
166
|
+
['Physics', ts.signals.physics, ts.breakdown.physics?.pts, 40],
|
|
167
|
+
['ENF', ts.signals.enf, ts.breakdown.enf?.pts, 20],
|
|
168
|
+
['GPU', ts.signals.gpu, ts.breakdown.gpu?.pts, 15],
|
|
169
|
+
['DRAM', ts.signals.dram, ts.breakdown.dram?.pts, 15],
|
|
170
|
+
['Bio/LLM', ts.signals.bio, ts.breakdown.bio?.pts, 10],
|
|
171
|
+
];
|
|
172
|
+
|
|
173
|
+
for (const [name, pct, pts, max] of layers) {
|
|
174
|
+
const lbl = gy(name.padEnd(10));
|
|
175
|
+
const b = bar(pct ?? 0, 24);
|
|
176
|
+
const ptsS = `${pts ?? 0}/${max}`.padStart(6);
|
|
177
|
+
process.stderr.write(`${vb} ${lbl} ${b} ${gy(ptsS)} ${vb}\n`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (ts.penalties.length > 0) {
|
|
181
|
+
process.stderr.write(`${vb} ${' '.repeat(W)} ${vb}\n`);
|
|
182
|
+
for (const p of ts.penalties) {
|
|
183
|
+
const msg = ye('⚠ ') + gy(p.reason.slice(0, W - 4));
|
|
184
|
+
process.stderr.write(`${vb} ${msg}${' '.repeat(Math.max(0, W - 2 - msg.replace(/\x1b\[[0-9;]*m/g,''). length))} ${vb}\n`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
process.stderr.write(`${vb} ${' '.repeat(W)} ${vb}\n`);
|
|
189
|
+
process.stderr.write(`${vb} ${gy('BLAKE3 ' + hash.slice(0, 40) + '…')}${' '.repeat(W - 48)} ${vb}\n`);
|
|
190
|
+
process.stderr.write(`${vb} ${gy(`elapsed ${(elapsed/1000).toFixed(2)}s`)}${' '.repeat(W - 14)} ${vb}\n`);
|
|
191
|
+
process.stderr.write(gy('╰' + '─'.repeat(W + 2) + '╯') + '\n\n');
|
|
192
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @svrnsec/pulse CLI — main entry point
|
|
3
|
+
*
|
|
4
|
+
* Commands:
|
|
5
|
+
* scan run the full probe locally
|
|
6
|
+
* challenge generate a signed challenge nonce
|
|
7
|
+
* version show version and check for updates
|
|
8
|
+
* help show this help text
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { parseArgs } from './args.js';
|
|
12
|
+
import { printBanner, checkForUpdate, CURRENT_VERSION } from '../update-notifier.js';
|
|
13
|
+
|
|
14
|
+
const isTTY = () => process.stderr.isTTY && !process.env.NO_COLOR;
|
|
15
|
+
const A = { reset:'\x1b[0m', gray:'\x1b[90m', bcyan:'\x1b[96m',
|
|
16
|
+
bwhite:'\x1b[97m', bmagenta:'\x1b[95m', bgreen:'\x1b[92m', byellow:'\x1b[93m' };
|
|
17
|
+
const c = (code, s) => isTTY() ? `${code}${s}${A.reset}` : s;
|
|
18
|
+
const gy = (s) => c(A.gray, s);
|
|
19
|
+
const cy = (s) => c(A.bcyan, s);
|
|
20
|
+
const wh = (s) => c(A.bwhite, s);
|
|
21
|
+
const gr = (s) => c(A.bgreen, s);
|
|
22
|
+
const ye = (s) => c(A.byellow, s);
|
|
23
|
+
const mg = (s) => c(A.bmagenta, s);
|
|
24
|
+
|
|
25
|
+
function help() {
|
|
26
|
+
process.stderr.write(`
|
|
27
|
+
${mg('SVRN')}${wh(':PULSE')} ${gy(`v${CURRENT_VERSION}`)} ${gy('Physical Turing Test')}
|
|
28
|
+
|
|
29
|
+
${wh('Usage')}
|
|
30
|
+
${cy('npx svrnsec-pulse')} ${gy('<command>')} ${gy('[options]')}
|
|
31
|
+
|
|
32
|
+
${wh('Commands')}
|
|
33
|
+
${cy('scan')} Run the full probe locally and show a TrustScore
|
|
34
|
+
${cy('challenge')} Generate a signed HMAC challenge nonce
|
|
35
|
+
${cy('version')} Show version and check for updates
|
|
36
|
+
${cy('help')} Show this help text
|
|
37
|
+
|
|
38
|
+
${wh('Scan options')}
|
|
39
|
+
${gy('--json')} Output raw JSON (pipe-friendly)
|
|
40
|
+
${gy('--iterations')} Override probe iteration count ${gy('(default: 200)')}
|
|
41
|
+
${gy('--no-banner')} Suppress the banner
|
|
42
|
+
|
|
43
|
+
${wh('Challenge options')}
|
|
44
|
+
${gy('--secret')} Server secret for HMAC signing ${gy('(or set PULSE_SECRET env)')}
|
|
45
|
+
${gy('--ttl')} Challenge TTL in seconds ${gy('(default: 300)')}
|
|
46
|
+
${gy('--json')} Output raw JSON
|
|
47
|
+
|
|
48
|
+
${wh('Examples')}
|
|
49
|
+
${gy('$')} ${cy('npx svrnsec-pulse scan')}
|
|
50
|
+
${gy('$')} ${cy('npx svrnsec-pulse scan --json | jq .trustScore.score')}
|
|
51
|
+
${gy('$')} ${cy('npx svrnsec-pulse challenge --secret $PULSE_SECRET')}
|
|
52
|
+
${gy('$')} ${cy('PULSE_SECRET=mysecret npx svrnsec-pulse challenge --json')}
|
|
53
|
+
|
|
54
|
+
${wh('Environment')}
|
|
55
|
+
${gy('PULSE_SECRET')} Default server secret for challenge signing
|
|
56
|
+
${gy('NO_COLOR')} Disable ANSI colors
|
|
57
|
+
${gy('PULSE_NO_UPDATE')} Disable update notifications
|
|
58
|
+
|
|
59
|
+
${gy(' Docs: https://github.com/ayronny14-alt/Svrn-Pulse-Security#readme')}
|
|
60
|
+
`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function cmdChallenge(args) {
|
|
64
|
+
const secret = args.get('secret') ?? process.env.PULSE_SECRET;
|
|
65
|
+
if (!secret) {
|
|
66
|
+
process.stderr.write(
|
|
67
|
+
ye('⚠ ') + 'No secret provided.\n' +
|
|
68
|
+
gy(' Pass --secret <value> or set PULSE_SECRET env var.\n') +
|
|
69
|
+
gy(' Generate one: ') + cy('npx svrnsec-pulse challenge --generate-secret\n')
|
|
70
|
+
);
|
|
71
|
+
process.exit(1);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (args.has('generate-secret')) {
|
|
75
|
+
const { generateSecret } = await import('../proof/challenge.js');
|
|
76
|
+
const s = generateSecret();
|
|
77
|
+
if (args.has('json')) {
|
|
78
|
+
process.stdout.write(JSON.stringify({ secret: s }) + '\n');
|
|
79
|
+
} else {
|
|
80
|
+
process.stderr.write(gr('Generated secret (store in env):\n'));
|
|
81
|
+
process.stdout.write(s + '\n');
|
|
82
|
+
}
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const { createChallenge } = await import('../proof/challenge.js');
|
|
87
|
+
const ttlMs = (parseInt(args.get('ttl', '300'), 10) || 300) * 1000;
|
|
88
|
+
const challenge = createChallenge(secret, { ttlMs });
|
|
89
|
+
|
|
90
|
+
if (args.has('json')) {
|
|
91
|
+
process.stdout.write(JSON.stringify(challenge, null, 2) + '\n');
|
|
92
|
+
} else {
|
|
93
|
+
process.stderr.write('\n');
|
|
94
|
+
process.stderr.write(gy(' nonce ') + wh(challenge.nonce) + '\n');
|
|
95
|
+
process.stderr.write(gy(' issuedAt ') + gy(new Date(challenge.issuedAt).toISOString()) + '\n');
|
|
96
|
+
process.stderr.write(gy(' expiresAt ') + gy(new Date(challenge.expiresAt).toISOString()) + '\n');
|
|
97
|
+
process.stderr.write(gy(' sig ') + cy(challenge.sig) + '\n\n');
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function cmdVersion(args) {
|
|
102
|
+
if (args.has('json')) {
|
|
103
|
+
const { latest, updateAvailable } = await checkForUpdate({ silent: true });
|
|
104
|
+
process.stdout.write(JSON.stringify({ version: CURRENT_VERSION, latest, updateAvailable }) + '\n');
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
process.stderr.write(`\n${mg('SVRN')}${wh(':PULSE')} ${gy('v' + CURRENT_VERSION)}\n\n`);
|
|
109
|
+
const { latest, updateAvailable } = await checkForUpdate({ silent: true });
|
|
110
|
+
if (updateAvailable) {
|
|
111
|
+
process.stderr.write(ye(` Update available: ${latest}\n`));
|
|
112
|
+
process.stderr.write(gy(` Run: `) + cy('npm i @svrnsec/pulse@latest') + '\n');
|
|
113
|
+
} else if (latest) {
|
|
114
|
+
process.stderr.write(gr(' Up to date.\n'));
|
|
115
|
+
}
|
|
116
|
+
process.stderr.write('\n');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function run(argv = process.argv.slice(2)) {
|
|
120
|
+
const args = parseArgs(argv);
|
|
121
|
+
const cmd = args.command ?? 'help';
|
|
122
|
+
|
|
123
|
+
try {
|
|
124
|
+
switch (cmd) {
|
|
125
|
+
case 'scan': {
|
|
126
|
+
const { runScan } = await import('./commands/scan.js');
|
|
127
|
+
await runScan(args);
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
case 'challenge':
|
|
131
|
+
case 'ch':
|
|
132
|
+
await cmdChallenge(args);
|
|
133
|
+
break;
|
|
134
|
+
case 'version':
|
|
135
|
+
case '-v':
|
|
136
|
+
case '--version':
|
|
137
|
+
await cmdVersion(args);
|
|
138
|
+
break;
|
|
139
|
+
case 'help':
|
|
140
|
+
case '-h':
|
|
141
|
+
case '--help':
|
|
142
|
+
help();
|
|
143
|
+
break;
|
|
144
|
+
default:
|
|
145
|
+
process.stderr.write(ye(`Unknown command: ${cmd}\n`));
|
|
146
|
+
help();
|
|
147
|
+
process.exit(1);
|
|
148
|
+
}
|
|
149
|
+
} catch (err) {
|
|
150
|
+
process.stderr.write(
|
|
151
|
+
c(A.bmagenta + '\x1b[1m', 'SVRN:PULSE error') + '\n' +
|
|
152
|
+
gy(err.message) + '\n'
|
|
153
|
+
);
|
|
154
|
+
if (process.env.DEBUG) process.stderr.write(err.stack + '\n');
|
|
155
|
+
process.exit(1);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @sovereign/pulse — Adaptive Entropy Probe
|
|
3
|
+
*
|
|
4
|
+
* Runs the WASM probe in batches and stops early once the signal is decisive.
|
|
5
|
+
*
|
|
6
|
+
* Why this works:
|
|
7
|
+
* A KVM VM with QE=1.27 and lag-1 autocorr=0.67 is unambiguously a VM after
|
|
8
|
+
* just 50 iterations. Running 200 iterations confirms what was already obvious
|
|
9
|
+
* at 50 — it adds no new information but wastes 3 seconds of user time.
|
|
10
|
+
*
|
|
11
|
+
* Conversely, a physical device with healthy entropy needs more data to
|
|
12
|
+
* rule out edge cases, so it runs longer.
|
|
13
|
+
*
|
|
14
|
+
* Speed profile:
|
|
15
|
+
* Obvious VM (QE < 1.5, lag1 > 0.60) → stops at 50 iters → ~0.9s (75% faster)
|
|
16
|
+
* Clear HW (QE > 3.5, lag1 < 0.10) → stops at ~100 iters → ~1.8s (50% faster)
|
|
17
|
+
* Ambiguous (borderline metrics) → runs full 200 iters → ~3.5s (same)
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { detectQuantizationEntropy } from '../analysis/jitter.js';
|
|
21
|
+
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
// Quick classifier (cheap, runs after every batch)
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Fast signal-quality check. No Hurst, no thermal analysis — just the three
|
|
28
|
+
* metrics that converge quickest: QE, CV, and lag-1 autocorrelation.
|
|
29
|
+
*
|
|
30
|
+
* @param {number[]} timings
|
|
31
|
+
* @returns {{ vmConf: number, hwConf: number, qe: number, cv: number, lag1: number }}
|
|
32
|
+
*/
|
|
33
|
+
export function quickSignal(timings) {
|
|
34
|
+
const n = timings.length;
|
|
35
|
+
const mean = timings.reduce((s, v) => s + v, 0) / n;
|
|
36
|
+
const variance = timings.reduce((s, v) => s + (v - mean) ** 2, 0) / n;
|
|
37
|
+
const cv = mean > 0 ? Math.sqrt(variance) / mean : 0;
|
|
38
|
+
const qe = detectQuantizationEntropy(timings);
|
|
39
|
+
|
|
40
|
+
// Pearson autocorrelation at lag-1 (O(n), fits in a single pass)
|
|
41
|
+
let num = 0, da = 0, db = 0;
|
|
42
|
+
for (let i = 0; i < n - 1; i++) {
|
|
43
|
+
const a = timings[i] - mean;
|
|
44
|
+
const b = timings[i + 1] - mean;
|
|
45
|
+
num += a * b;
|
|
46
|
+
da += a * a;
|
|
47
|
+
db += b * b;
|
|
48
|
+
}
|
|
49
|
+
const lag1 = Math.sqrt(da * db) < 1e-14 ? 0 : num / Math.sqrt(da * db);
|
|
50
|
+
|
|
51
|
+
// VM confidence: each factor independently identifies the hypervisor footprint
|
|
52
|
+
const vmConf = Math.min(1,
|
|
53
|
+
(qe < 1.50 ? 0.40 : qe < 2.00 ? 0.20 : 0.0) +
|
|
54
|
+
(lag1 > 0.60 ? 0.35 : lag1 > 0.40 ? 0.18 : 0.0) +
|
|
55
|
+
(cv < 0.04 ? 0.25 : cv < 0.07 ? 0.10 : 0.0)
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
// HW confidence: must see all three positive signals together
|
|
59
|
+
const hwConf = Math.min(1,
|
|
60
|
+
(qe > 3.50 ? 0.38 : qe > 3.00 ? 0.22 : 0.0) +
|
|
61
|
+
(Math.abs(lag1) < 0.10 ? 0.32 : Math.abs(lag1) < 0.20 ? 0.15 : 0.0) +
|
|
62
|
+
(cv > 0.10 ? 0.30 : cv > 0.07 ? 0.14 : 0.0)
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
return { vmConf, hwConf, qe, cv, lag1 };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
// collectEntropyAdaptive
|
|
70
|
+
// ---------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* @param {object} opts
|
|
74
|
+
* @param {number} [opts.minIterations=50] - never stop before this
|
|
75
|
+
* @param {number} [opts.maxIterations=200] - hard cap
|
|
76
|
+
* @param {number} [opts.batchSize=25] - WASM call granularity
|
|
77
|
+
* @param {number} [opts.vmThreshold=0.85] - stop early if VM confidence ≥ this
|
|
78
|
+
* @param {number} [opts.hwThreshold=0.80] - stop early if HW confidence ≥ this
|
|
79
|
+
* @param {number} [opts.hwMinIterations=75] - physical needs more data to confirm
|
|
80
|
+
* @param {number} [opts.matrixSize=64]
|
|
81
|
+
* @param {Function} [opts.onBatch] - called after each batch with interim signal
|
|
82
|
+
* @param {string} [opts.wasmPath]
|
|
83
|
+
* @param {Function} wasmModule - pre-initialised WASM module
|
|
84
|
+
* @returns {Promise<AdaptiveEntropyResult>}
|
|
85
|
+
*/
|
|
86
|
+
export async function collectEntropyAdaptive(wasmModule, opts = {}) {
|
|
87
|
+
const {
|
|
88
|
+
minIterations = 50,
|
|
89
|
+
maxIterations = 200,
|
|
90
|
+
batchSize = 25,
|
|
91
|
+
vmThreshold = 0.85,
|
|
92
|
+
hwThreshold = 0.80,
|
|
93
|
+
hwMinIterations = 75,
|
|
94
|
+
matrixSize = 64,
|
|
95
|
+
onBatch,
|
|
96
|
+
} = opts;
|
|
97
|
+
|
|
98
|
+
const wasm = wasmModule;
|
|
99
|
+
const allTimings = [];
|
|
100
|
+
const batches = []; // per-batch timing snapshots
|
|
101
|
+
let stoppedAt = null; // { reason, iterations, vmConf, hwConf }
|
|
102
|
+
let checksum = 0;
|
|
103
|
+
|
|
104
|
+
const t_start = Date.now();
|
|
105
|
+
|
|
106
|
+
while (allTimings.length < maxIterations) {
|
|
107
|
+
const n = Math.min(batchSize, maxIterations - allTimings.length);
|
|
108
|
+
const result = wasm.run_entropy_probe(n, matrixSize);
|
|
109
|
+
const chunk = Array.from(result.timings);
|
|
110
|
+
|
|
111
|
+
allTimings.push(...chunk);
|
|
112
|
+
checksum += result.checksum;
|
|
113
|
+
|
|
114
|
+
const sig = quickSignal(allTimings);
|
|
115
|
+
batches.push({ iterations: allTimings.length, ...sig });
|
|
116
|
+
|
|
117
|
+
// Fire progress callback with live signal so callers can stream to UI
|
|
118
|
+
if (typeof onBatch === 'function') {
|
|
119
|
+
try {
|
|
120
|
+
onBatch({
|
|
121
|
+
iterations: allTimings.length,
|
|
122
|
+
maxIterations,
|
|
123
|
+
pct: Math.round(allTimings.length / maxIterations * 100),
|
|
124
|
+
vmConf: sig.vmConf,
|
|
125
|
+
hwConf: sig.hwConf,
|
|
126
|
+
qe: sig.qe,
|
|
127
|
+
cv: sig.cv,
|
|
128
|
+
lag1: sig.lag1,
|
|
129
|
+
// Thresholds: 0.70 — high enough that a legitimate device won't be
|
|
130
|
+
// shown a false early verdict from a noisy first batch.
|
|
131
|
+
// 'borderline' surfaces when one axis is moderate but not decisive.
|
|
132
|
+
earlyVerdict: sig.vmConf > 0.70 ? 'vm'
|
|
133
|
+
: sig.hwConf > 0.70 ? 'physical'
|
|
134
|
+
: (sig.vmConf > 0.45 || sig.hwConf > 0.45) ? 'borderline'
|
|
135
|
+
: 'uncertain',
|
|
136
|
+
});
|
|
137
|
+
} catch {}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ── Early-exit checks ──────────────────────────────────────────────────
|
|
141
|
+
if (allTimings.length < minIterations) continue;
|
|
142
|
+
|
|
143
|
+
if (sig.vmConf >= vmThreshold) {
|
|
144
|
+
stoppedAt = { reason: 'VM_SIGNAL_DECISIVE', vmConf: sig.vmConf, hwConf: sig.hwConf };
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (allTimings.length >= hwMinIterations && sig.hwConf >= hwThreshold) {
|
|
149
|
+
stoppedAt = { reason: 'PHYSICAL_SIGNAL_DECISIVE', vmConf: sig.vmConf, hwConf: sig.hwConf };
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const elapsed = Date.now() - t_start;
|
|
155
|
+
const iterationsRan = allTimings.length;
|
|
156
|
+
const iterationsSaved = maxIterations - iterationsRan;
|
|
157
|
+
const speedupFactor = maxIterations / iterationsRan;
|
|
158
|
+
|
|
159
|
+
// ── Resolution probe using cached WASM call ────────────────────────────
|
|
160
|
+
const resResult = wasm.run_entropy_probe(1, 4); // tiny probe for resolution
|
|
161
|
+
const resProbe = Array.from(resResult.resolution_probe ?? []);
|
|
162
|
+
|
|
163
|
+
const resDeltas = [];
|
|
164
|
+
for (let i = 1; i < resProbe.length; i++) {
|
|
165
|
+
const d = resProbe[i] - resProbe[i - 1];
|
|
166
|
+
if (d > 0) resDeltas.push(d);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
timings: allTimings,
|
|
171
|
+
iterations: iterationsRan,
|
|
172
|
+
maxIterations,
|
|
173
|
+
checksum: checksum.toString(),
|
|
174
|
+
resolutionProbe: resProbe,
|
|
175
|
+
timerGranularityMs: resDeltas.length
|
|
176
|
+
? resDeltas.reduce((a, b) => Math.min(a, b), Infinity)
|
|
177
|
+
: null,
|
|
178
|
+
earlyExit: stoppedAt ? {
|
|
179
|
+
...stoppedAt,
|
|
180
|
+
iterationsSaved,
|
|
181
|
+
timeSavedMs: Math.round(iterationsSaved * (elapsed / iterationsRan)),
|
|
182
|
+
speedupFactor: +speedupFactor.toFixed(2),
|
|
183
|
+
} : null,
|
|
184
|
+
batches,
|
|
185
|
+
elapsedMs: elapsed,
|
|
186
|
+
collectedAt: t_start,
|
|
187
|
+
matrixSize,
|
|
188
|
+
phased: false, // adaptive replaces phased for speed
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* @typedef {object} AdaptiveEntropyResult
|
|
194
|
+
* @property {number[]} timings
|
|
195
|
+
* @property {number} iterations - how many actually ran
|
|
196
|
+
* @property {number} maxIterations - cap that was set
|
|
197
|
+
* @property {object|null} earlyExit - null if ran to completion
|
|
198
|
+
* @property {object[]} batches - per-batch signal snapshots
|
|
199
|
+
* @property {number} elapsedMs
|
|
200
|
+
*/
|