@svrnsec/pulse 0.3.0 → 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/index.d.ts CHANGED
@@ -586,3 +586,261 @@ export interface SignatureComparison {
586
586
  profileMatch: boolean;
587
587
  providerMatch: boolean;
588
588
  }
589
+
590
+ // =============================================================================
591
+ // Extended Signal Layer Types
592
+ // =============================================================================
593
+
594
+ // ── ENF (Electrical Network Frequency) ───────────────────────────────────────
595
+
596
+ export interface EnfResult {
597
+ enfAvailable: boolean;
598
+ ripplePresent: boolean;
599
+ gridFrequency: 50 | 60 | null;
600
+ gridRegion: 'americas' | 'emea_apac' | 'unknown';
601
+ ripplePower: number;
602
+ snr50hz: number;
603
+ snr60hz: number;
604
+ enfDeviation: number | null;
605
+ sampleRateHz: number;
606
+ resolutionUs: number;
607
+ verdict: 'grid_60hz' | 'grid_50hz' | 'no_grid_signal' | 'grid_detected_region_unknown' | 'unavailable';
608
+ isVmIndicator: boolean;
609
+ temporalAnchor: {
610
+ nominalHz: number;
611
+ measuredRippleHz: number;
612
+ capturedAt: number;
613
+ gridHz: number;
614
+ } | null;
615
+ reason?: string;
616
+ }
617
+
618
+ export declare function collectEnfTimings(opts?: { iterations?: number }): Promise<EnfResult>;
619
+
620
+ // ── WebGPU Thermal Variance ───────────────────────────────────────────────────
621
+
622
+ export interface GpuEntropyResult {
623
+ gpuPresent: boolean;
624
+ isSoftware: boolean;
625
+ vendorString: string | null;
626
+ dispatchCV: number;
627
+ thermalGrowth: number;
628
+ verdict: 'real_gpu' | 'software_renderer' | 'no_webgpu' | 'ambiguous';
629
+ }
630
+
631
+ export declare function collectGpuEntropy(opts?: object): Promise<GpuEntropyResult>;
632
+
633
+ // ── DRAM Refresh Cycle ────────────────────────────────────────────────────────
634
+
635
+ export interface DramResult {
636
+ timings: number[];
637
+ refreshPeriodMs: number | null;
638
+ refreshPresent: boolean;
639
+ peakLag: number;
640
+ peakPower: number;
641
+ verdict: 'dram' | 'virtual' | 'ambiguous';
642
+ }
643
+
644
+ export declare function collectDramTimings(opts?: { iterations?: number; bufferMb?: number }): DramResult;
645
+
646
+ // ── LLM / AI Agent Behavioral Fingerprint ─────────────────────────────────────
647
+
648
+ export interface LlmResult {
649
+ aiConf: number;
650
+ thinkTimePattern: 'llm_latency_peak' | 'human_pareto' | 'unknown';
651
+ correctionRate: number;
652
+ rhythmicity: number;
653
+ pauseDistribution: 'uniform' | 'pareto' | 'unknown';
654
+ verdict: 'ai_agent' | 'human' | 'insufficient_data';
655
+ matchedModel: string | null;
656
+ }
657
+
658
+ export declare function detectLlmAgent(bioSnapshot: object): LlmResult;
659
+
660
+ // ── SAB Microsecond Timer ─────────────────────────────────────────────────────
661
+
662
+ export interface SabTimerResult {
663
+ isClamped: boolean;
664
+ clampAmountUs: number;
665
+ resolutionUs: number;
666
+ }
667
+
668
+ export declare function isSabAvailable(): boolean;
669
+ export declare function collectHighResTimings(opts?: { iterations?: number; matrixSize?: number }): {
670
+ timings: number[];
671
+ resolutionUs: number;
672
+ };
673
+
674
+ // =============================================================================
675
+ // Terminal / DX Utilities
676
+ // =============================================================================
677
+
678
+ export declare function renderProbeResult(opts: {
679
+ payload: ProofPayload;
680
+ hash: string;
681
+ result?: ValidationResult;
682
+ enf?: EnfResult | null;
683
+ gpu?: GpuEntropyResult | null;
684
+ dram?: DramResult | null;
685
+ llm?: LlmResult | null;
686
+ elapsedMs?: number;
687
+ }): void;
688
+
689
+ export declare function renderError(err: Error | string): void;
690
+ export declare function renderInlineUpdateHint(latest: string): void;
691
+
692
+ // =============================================================================
693
+ // Version / Update Notifier
694
+ // =============================================================================
695
+
696
+ export declare const CURRENT_VERSION: string;
697
+
698
+ export declare function checkForUpdate(opts?: {
699
+ silent?: boolean;
700
+ pkg?: string;
701
+ }): Promise<{ current: string; latest: string | null; updateAvailable: boolean }>;
702
+
703
+ export declare function notifyOnExit(opts?: { pkg?: string }): void;
704
+
705
+ // =============================================================================
706
+ // Extended PulseCommitment (includes extended signal layer results)
707
+ // =============================================================================
708
+
709
+ export interface ExtendedPulseCommitment extends PulseCommitment {
710
+ extended: {
711
+ enf: EnfResult | null;
712
+ gpu: GpuEntropyResult | null;
713
+ dram: DramResult | null;
714
+ llm: LlmResult | null;
715
+ };
716
+ }
717
+
718
+ // =============================================================================
719
+ // TrustScore
720
+ // =============================================================================
721
+
722
+ export interface TrustScoreBreakdown {
723
+ pts: number;
724
+ max: number;
725
+ [key: string]: unknown;
726
+ }
727
+
728
+ export interface TrustScorePenalty {
729
+ signal: string;
730
+ reason: string;
731
+ cap: number;
732
+ }
733
+
734
+ export interface TrustScoreBonus {
735
+ signal: string;
736
+ reason: string;
737
+ pts: number;
738
+ }
739
+
740
+ export interface TrustScore {
741
+ score: number;
742
+ grade: 'A' | 'B' | 'C' | 'D' | 'F';
743
+ label: 'Trusted' | 'Verified' | 'Marginal' | 'Suspicious' | 'Blocked';
744
+ color: string;
745
+ hardCap: number | null;
746
+ breakdown: {
747
+ physics: TrustScoreBreakdown;
748
+ enf: TrustScoreBreakdown;
749
+ gpu: TrustScoreBreakdown;
750
+ dram: TrustScoreBreakdown;
751
+ bio: TrustScoreBreakdown;
752
+ };
753
+ penalties: TrustScorePenalty[];
754
+ bonuses: TrustScoreBonus[];
755
+ signals: {
756
+ physics: number;
757
+ enf: number;
758
+ gpu: number;
759
+ dram: number;
760
+ bio: number;
761
+ };
762
+ }
763
+
764
+ export declare function computeTrustScore(
765
+ payload: ProofPayload,
766
+ extended?: { enf?: EnfResult; gpu?: GpuEntropyResult; dram?: DramResult; llm?: LlmResult }
767
+ ): TrustScore;
768
+
769
+ export declare function formatTrustScore(ts: TrustScore): string;
770
+
771
+ // =============================================================================
772
+ // HMAC-Signed Challenge
773
+ // =============================================================================
774
+
775
+ export interface SignedChallenge {
776
+ nonce: string;
777
+ issuedAt: number;
778
+ expiresAt: number;
779
+ sig: string;
780
+ }
781
+
782
+ export interface ChallengeVerifyResult {
783
+ valid: boolean;
784
+ reason?: string;
785
+ }
786
+
787
+ export declare function createChallenge(
788
+ secret: string,
789
+ opts?: { ttlMs?: number; nonce?: string }
790
+ ): SignedChallenge;
791
+
792
+ export declare function verifyChallenge(
793
+ challenge: SignedChallenge,
794
+ secret: string,
795
+ opts?: { checkNonce?: (nonce: string) => Promise<boolean> }
796
+ ): Promise<ChallengeVerifyResult>;
797
+
798
+ export declare function embedChallenge(challenge: SignedChallenge, payload: ProofPayload): ProofPayload;
799
+ export declare function extractChallenge(payload: ProofPayload): SignedChallenge;
800
+ export declare function generateSecret(): string;
801
+
802
+ // =============================================================================
803
+ // React Native Hook
804
+ // =============================================================================
805
+
806
+ export interface TremorResult {
807
+ tremorPresent: boolean;
808
+ tremorPower: number;
809
+ rmsNoise: number;
810
+ sampleRate: number;
811
+ gyroNoise: number;
812
+ isStatic: boolean;
813
+ }
814
+
815
+ export interface TouchAnalysis {
816
+ humanConf: number;
817
+ dwellMean: number;
818
+ dwellCV: number;
819
+ sampleCount: number;
820
+ }
821
+
822
+ export interface UsePulseNativeOptions {
823
+ challengeUrl?: string;
824
+ verifyUrl?: string;
825
+ apiKey?: string;
826
+ sensorMs?: number;
827
+ autoRun?: boolean;
828
+ onResult?: (trustScore: TrustScore, proof: object) => void;
829
+ onError?: (error: Error) => void;
830
+ }
831
+
832
+ export interface UsePulseNativeReturn {
833
+ run: () => Promise<void>;
834
+ reset: () => void;
835
+ isRunning: boolean;
836
+ stage: string | null;
837
+ pct: number;
838
+ trustScore: TrustScore | null;
839
+ tremor: TremorResult | null;
840
+ touches: TouchAnalysis | null;
841
+ proof: object | null;
842
+ error: Error | null;
843
+ panHandlers: object | null;
844
+ }
845
+
846
+ export declare function usePulseNative(opts?: UsePulseNativeOptions): UsePulseNativeReturn;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@svrnsec/pulse",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Physical Turing Test — Hardware-Biological Symmetry Protocol distinguishing real consumer devices from sanitised datacenter VMs.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -14,6 +14,9 @@
14
14
  "url": "https://github.com/ayronny14-alt/Svrn-Pulse-Security/issues"
15
15
  },
16
16
  "types": "index.d.ts",
17
+ "bin": {
18
+ "svrnsec-pulse": "./bin/svrnsec-pulse.js"
19
+ },
17
20
  "publishConfig": {
18
21
  "access": "public",
19
22
  "registry": "https://registry.npmjs.org/"
@@ -21,28 +24,39 @@
21
24
  "exports": {
22
25
  ".": {
23
26
  "browser": "./dist/pulse.esm.js",
24
- "import": "./dist/pulse.esm.js",
27
+ "import": "./dist/pulse.esm.js",
25
28
  "require": "./dist/pulse.cjs.js"
26
29
  },
27
30
  "./validator": {
28
- "node": "./src/proof/validator.js",
31
+ "node": "./src/proof/validator.js",
29
32
  "import": "./src/proof/validator.js"
30
33
  },
34
+ "./challenge": {
35
+ "node": "./src/proof/challenge.js",
36
+ "import": "./src/proof/challenge.js"
37
+ },
38
+ "./trust": {
39
+ "import": "./src/analysis/trustScore.js",
40
+ "node": "./src/analysis/trustScore.js"
41
+ },
31
42
  "./registry": {
32
43
  "import": "./src/registry/serializer.js",
33
- "node": "./src/registry/serializer.js"
44
+ "node": "./src/registry/serializer.js"
34
45
  },
35
46
  "./middleware/express": {
36
47
  "import": "./src/middleware/express.js",
37
- "node": "./src/middleware/express.js"
48
+ "node": "./src/middleware/express.js"
38
49
  },
39
50
  "./middleware/next": {
40
51
  "import": "./src/middleware/next.js",
41
- "node": "./src/middleware/next.js"
52
+ "node": "./src/middleware/next.js"
42
53
  },
43
54
  "./react": {
44
55
  "import": "./src/integrations/react.js"
45
56
  },
57
+ "./react-native": {
58
+ "import": "./src/integrations/react-native.js"
59
+ },
46
60
  "./gpu": {
47
61
  "import": "./src/collector/gpu.js"
48
62
  },
@@ -59,38 +73,45 @@
59
73
  "import": "./src/collector/enf.js"
60
74
  }
61
75
  },
62
- "main": "dist/pulse.cjs.js",
76
+ "main": "dist/pulse.cjs.js",
63
77
  "module": "dist/pulse.esm.js",
64
78
  "files": [
65
79
  "dist/",
66
80
  "pkg/",
81
+ "bin/",
82
+ "src/",
67
83
  "index.d.ts",
68
- "src/proof/validator.js",
69
- "src/proof/fingerprint.js",
70
- "src/middleware/express.js",
71
- "src/middleware/next.js",
72
- "src/registry/serializer.js",
73
- "src/integrations/react.js",
74
84
  "SECURITY.md"
75
85
  ],
76
86
  "scripts": {
77
87
  "build:wasm": "bash build.sh",
78
- "build:js": "rollup -c rollup.config.js",
79
- "build": "npm run build:wasm && npm run build:js",
80
- "dev": "rollup -c rollup.config.js --watch",
81
- "test": "node --experimental-vm-modules ./node_modules/jest-cli/bin/jest.js",
82
- "demo": "node demo/node-demo.js"
88
+ "build:js": "rollup -c rollup.config.js",
89
+ "build": "npm run build:wasm && npm run build:js",
90
+ "dev": "rollup -c rollup.config.js --watch",
91
+ "test": "node --experimental-vm-modules ./node_modules/jest-cli/bin/jest.js",
92
+ "demo": "node demo/node-demo.js",
93
+ "scan": "node bin/svrnsec-pulse.js scan"
83
94
  },
84
95
  "dependencies": {
85
96
  "@noble/hashes": "^1.4.0"
86
97
  },
87
98
  "devDependencies": {
88
- "@rollup/plugin-commonjs": "^25.0.0",
99
+ "@rollup/plugin-commonjs": "^25.0.0",
89
100
  "@rollup/plugin-node-resolve": "^15.0.0",
90
- "@rollup/plugin-wasm": "^6.2.2",
91
- "@types/jest": "^29.0.0",
92
- "jest": "^29.0.0",
93
- "rollup": "^4.0.0"
101
+ "@rollup/plugin-wasm": "^6.2.2",
102
+ "@types/jest": "^29.0.0",
103
+ "jest": "^29.0.0",
104
+ "rollup": "^4.0.0"
105
+ },
106
+ "peerDependencies": {
107
+ "react": ">=17.0.0",
108
+ "react-native": ">=0.70.0",
109
+ "expo-sensors": ">=13.0.0"
110
+ },
111
+ "peerDependenciesMeta": {
112
+ "react": { "optional": true },
113
+ "react-native": { "optional": true },
114
+ "expo-sensors": { "optional": true }
94
115
  },
95
116
  "keywords": [
96
117
  "physical-turing-test",
@@ -105,7 +126,13 @@
105
126
  "dram-detection",
106
127
  "llm-detection",
107
128
  "ai-agent-detection",
108
- "behavioral-biometrics"
129
+ "behavioral-biometrics",
130
+ "trust-score",
131
+ "hmac-challenge",
132
+ "react-native",
133
+ "mobile-security",
134
+ "enf-detection",
135
+ "cli"
109
136
  ],
110
137
  "engines": {
111
138
  "node": ">=18.0.0"
@@ -0,0 +1,213 @@
1
+ /**
2
+ * @sovereign/pulse — AudioContext Oscillator Jitter
3
+ *
4
+ * Measures the scheduling jitter of the browser's audio pipeline.
5
+ * Real audio hardware callbacks are driven by a hardware interrupt (IRQ)
6
+ * from the sound card; the timing reflects the actual interrupt latency
7
+ * of the physical device. VM audio drivers (if present at all) are
8
+ * emulated and show either unrealistically low jitter or burst-mode
9
+ * scheduling artefacts that are statistically distinguishable.
10
+ */
11
+
12
+ /**
13
+ * @param {object} [opts]
14
+ * @param {number} [opts.durationMs=2000] - how long to collect audio callbacks
15
+ * @param {number} [opts.bufferSize=256] - ScriptProcessorNode buffer size
16
+ * @returns {Promise<AudioJitter>}
17
+ */
18
+ export async function collectAudioJitter(opts = {}) {
19
+ const { durationMs = 2000, bufferSize = 256 } = opts;
20
+
21
+ const base = {
22
+ available: false,
23
+ workletAvailable: false,
24
+ callbackJitterCV: 0,
25
+ noiseFloorMean: 0,
26
+ sampleRate: 0,
27
+ callbackCount: 0,
28
+ jitterTimings: [],
29
+ };
30
+
31
+ if (typeof AudioContext === 'undefined' && typeof webkitAudioContext === 'undefined') {
32
+ return base; // Node.js / server environment
33
+ }
34
+
35
+ let ctx;
36
+ try {
37
+ ctx = new (window.AudioContext || window.webkitAudioContext)();
38
+ } catch (_) {
39
+ return base;
40
+ }
41
+
42
+ // Some browsers require a user gesture before AudioContext can run.
43
+ if (ctx.state === 'suspended') {
44
+ try {
45
+ await ctx.resume();
46
+ } catch (_) {
47
+ await ctx.close().catch(() => {});
48
+ return base;
49
+ }
50
+ }
51
+
52
+ const sampleRate = ctx.sampleRate;
53
+ const expectedInterval = (bufferSize / sampleRate) * 1000; // ms per callback
54
+
55
+ const jitterTimings = []; // absolute AudioContext.currentTime at each callback
56
+ const callbackDeltas = [];
57
+
58
+ const result = await new Promise((resolve) => {
59
+ // ── AudioWorklet (preferred — runs on dedicated real-time thread) ──────
60
+ const useWorklet = typeof AudioWorkletNode !== 'undefined';
61
+ base.workletAvailable = useWorklet;
62
+
63
+ if (useWorklet) {
64
+ // Inline worklet: send currentTime back via MessagePort every buffer
65
+ const workletCode = `
66
+ class PulseProbe extends AudioWorkletProcessor {
67
+ process(inputs, outputs) {
68
+ this.port.postMessage({ t: currentTime });
69
+ // Pass-through silence
70
+ for (const out of outputs)
71
+ for (const ch of out) ch.fill(0);
72
+ return true;
73
+ }
74
+ }
75
+ registerProcessor('pulse-probe', PulseProbe);
76
+ `;
77
+ const blob = new Blob([workletCode], { type: 'application/javascript' });
78
+ const blobUrl = URL.createObjectURL(blob);
79
+
80
+ ctx.audioWorklet.addModule(blobUrl).then(() => {
81
+ const node = new AudioWorkletNode(ctx, 'pulse-probe');
82
+ node.port.onmessage = (e) => {
83
+ jitterTimings.push(e.data.t * 1000); // convert to ms
84
+ };
85
+ node.connect(ctx.destination);
86
+
87
+ setTimeout(async () => {
88
+ node.disconnect();
89
+ URL.revokeObjectURL(blobUrl);
90
+ resolve(node);
91
+ }, durationMs);
92
+ }).catch(() => {
93
+ URL.revokeObjectURL(blobUrl);
94
+ _fallbackScriptProcessor(ctx, bufferSize, durationMs, jitterTimings, resolve);
95
+ });
96
+
97
+ } else {
98
+ _fallbackScriptProcessor(ctx, bufferSize, durationMs, jitterTimings, resolve);
99
+ }
100
+ });
101
+
102
+ // ── Compute deltas between successive callback times ────────────────────
103
+ for (let i = 1; i < jitterTimings.length; i++) {
104
+ callbackDeltas.push(jitterTimings[i] - jitterTimings[i - 1]);
105
+ }
106
+
107
+ // ── Noise floor via AnalyserNode ─────────────────────────────────────────
108
+ // Feed a silent oscillator through an analyser; the FFT magnitude at silence
109
+ // reveals the hardware's thermal noise floor (varies per ADC/DAC chipset).
110
+ const noiseFloor = await _measureNoiseFloor(ctx);
111
+
112
+ await ctx.close().catch(() => {});
113
+
114
+ // ── Statistics ────────────────────────────────────────────────────────────
115
+ const mean = callbackDeltas.length
116
+ ? callbackDeltas.reduce((s, v) => s + v, 0) / callbackDeltas.length
117
+ : 0;
118
+ const variance = callbackDeltas.length > 1
119
+ ? callbackDeltas.reduce((s, v) => s + (v - mean) ** 2, 0) / (callbackDeltas.length - 1)
120
+ : 0;
121
+ const jitterCV = mean > 0 ? Math.sqrt(variance) / mean : 0;
122
+
123
+ return {
124
+ available: true,
125
+ workletAvailable: base.workletAvailable,
126
+ callbackJitterCV: jitterCV,
127
+ noiseFloorMean: noiseFloor.mean,
128
+ noiseFloorStd: noiseFloor.std,
129
+ sampleRate,
130
+ callbackCount: jitterTimings.length,
131
+ expectedIntervalMs: expectedInterval,
132
+ // Only include summary stats, not raw timings (privacy / size)
133
+ jitterMeanMs: mean,
134
+ jitterP95Ms: _percentile(callbackDeltas, 95),
135
+ };
136
+ }
137
+
138
+ /**
139
+ * @typedef {object} AudioJitter
140
+ * @property {boolean} available
141
+ * @property {boolean} workletAvailable
142
+ * @property {number} callbackJitterCV
143
+ * @property {number} noiseFloorMean
144
+ * @property {number} sampleRate
145
+ * @property {number} callbackCount
146
+ */
147
+
148
+ // ---------------------------------------------------------------------------
149
+ // Internal helpers
150
+ // ---------------------------------------------------------------------------
151
+
152
+ function _fallbackScriptProcessor(ctx, bufferSize, durationMs, jitterTimings, resolve) {
153
+ // ScriptProcessorNode is deprecated but universally supported.
154
+ const proc = ctx.createScriptProcessor(bufferSize, 1, 1);
155
+ proc.onaudioprocess = () => {
156
+ jitterTimings.push(ctx.currentTime * 1000);
157
+ };
158
+ // Connect to keep the graph alive
159
+ const osc = ctx.createOscillator();
160
+ osc.frequency.value = 1; // sub-audible
161
+ osc.connect(proc);
162
+ proc.connect(ctx.destination);
163
+ osc.start();
164
+
165
+ setTimeout(() => {
166
+ osc.stop();
167
+ osc.disconnect();
168
+ proc.disconnect();
169
+ resolve(proc);
170
+ }, durationMs);
171
+ }
172
+
173
+ async function _measureNoiseFloor(ctx) {
174
+ try {
175
+ const analyser = ctx.createAnalyser();
176
+ analyser.fftSize = 256;
177
+ analyser.connect(ctx.destination);
178
+
179
+ // Silent source
180
+ const buf = ctx.createBuffer(1, ctx.sampleRate * 0.1, ctx.sampleRate);
181
+ const src = ctx.createBufferSource();
182
+ src.buffer = buf;
183
+ src.connect(analyser);
184
+ src.start();
185
+
186
+ await new Promise(r => setTimeout(r, 150));
187
+
188
+ const data = new Float32Array(analyser.frequencyBinCount);
189
+ analyser.getFloatFrequencyData(data);
190
+ analyser.disconnect();
191
+
192
+ // Limit to 32 bins to keep the payload small
193
+ const trimmed = Array.from(data.slice(0, 32)).map(v =>
194
+ isFinite(v) ? Math.pow(10, v / 20) : 0 // dB → linear
195
+ );
196
+ const mean = trimmed.reduce((s, v) => s + v, 0) / trimmed.length;
197
+ const std = Math.sqrt(
198
+ trimmed.reduce((s, v) => s + (v - mean) ** 2, 0) / trimmed.length
199
+ );
200
+ return { mean, std };
201
+ } catch (_) {
202
+ return { mean: 0, std: 0 };
203
+ }
204
+ }
205
+
206
+ function _percentile(arr, p) {
207
+ if (!arr.length) return 0;
208
+ const sorted = [...arr].sort((a, b) => a - b);
209
+ const idx = (p / 100) * (sorted.length - 1);
210
+ const lo = Math.floor(idx);
211
+ const hi = Math.ceil(idx);
212
+ return sorted[lo] + (sorted[hi] - sorted[lo]) * (idx - lo);
213
+ }