synapse-shield-vue 0.0.0-stage → 0.12.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Synapse Shield Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,134 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # Synapse Shield Vue 3 & Nuxt 3 SDK
2
+
3
+ Official Vue 3 and Nuxt 3 integration for **Synapse Shield** behavioral biometrics, bot mitigation, and anti-stealth engine.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install synapse-shield-vue
9
+ # or
10
+ pnpm add synapse-shield-vue
11
+ # or
12
+ yarn add synapse-shield-vue
13
+ ```
14
+
15
+ ## Quick Start (Vue 3 / Vite)
16
+
17
+ ### Using the Composable (`useSynapseShield`)
18
+
19
+ ```vue
20
+ <script setup lang="ts">
21
+ import { ref } from 'vue';
22
+ import { useSynapseShield } from 'synapse-shield-vue';
23
+
24
+ const { getProtectedPayload, isReady } = useSynapseShield({
25
+ apiEndpoint: '/api',
26
+ });
27
+
28
+ const username = ref('');
29
+ const password = ref('');
30
+ const message = ref('');
31
+
32
+ const handleLogin = async () => {
33
+ // Get cryptographically signed token with behavioral biometrics
34
+ const payload = getProtectedPayload();
35
+
36
+ const response = await fetch('/api/login', {
37
+ method: 'POST',
38
+ headers: {
39
+ 'Content-Type': 'application/json',
40
+ 'X-Synapse-Token': payload.token, // canonical token header
41
+ },
42
+ body: JSON.stringify({
43
+ username: username.value,
44
+ password: password.value,
45
+ // token: payload.token, // or in JSON body as 'token' (or 'synapse_token' compatibility alias)
46
+ }),
47
+ });
48
+
49
+ const result = await response.json();
50
+ message.value = result.message || 'Done';
51
+ };
52
+ </script>
53
+
54
+ <template>
55
+ <form @submit.prevent="handleLogin" class="login-form">
56
+ <h2>Secure Login</h2>
57
+ <input v-model="username" type="text" placeholder="Username" required />
58
+ <input v-model="password" type="password" placeholder="Password" required />
59
+ <button type="submit" :disabled="!isReady">Sign In</button>
60
+ <p v-if="message">{{ message }}</p>
61
+ </form>
62
+ </template>
63
+ ```
64
+
65
+ ### Telemetry Shield Component (`SynapseProtect`)
66
+
67
+ `<SynapseProtect />` mounts passive telemetry listeners inside your Vue template. Note that backend adapters require JSON bodies or `X-Synapse-Token` headers (traditional non-JS form POSTs are not gated). To submit protected form data, use `submitProtected()` or fetch with `X-Synapse-Token`:
68
+
69
+ ```vue
70
+ <script setup lang="ts">
71
+ import { SynapseProtect } from 'synapse-shield-vue';
72
+ </script>
73
+
74
+ <template>
75
+ <div>
76
+ <SynapseProtect />
77
+ <!-- Component mounts biometric telemetry listeners into this view -->
78
+ </div>
79
+ </template>
80
+ ```
81
+
82
+ ### Automatic Proof-of-Work retry (`submitProtected`)
83
+
84
+ Same API as the React SDK. On HTTP 429 `challenge_required` it fetches a fresh challenge, solves the PoW and retries **once**. A second 429 is returned as is.
85
+
86
+ ```ts
87
+ const { submitProtected } = useSynapseShield();
88
+
89
+ const res = await submitProtected('/api/login', (p) => ({
90
+ username: username.value,
91
+ token: p.token, // canonical body token (or via X-Synapse-Token header; 'synapse_token' alias accepted)
92
+ pow_salt: p.pow_salt, // set only on the retry
93
+ pow_nonce: p.pow_nonce, // read by the server middleware from the top level of the JSON body
94
+ }));
95
+ ```
96
+
97
+ The retry waits 1.6-3 s (up to 8 s only when needed to keep the last 3 mouse points). It then sends the most recent telemetry window the server accepts. A long session is scored on its last few seconds. Tokens only carry events their challenge can vouch for, so long SPA sessions are not rejected as stale. Autofill, paste and IME entry are recorded in `input_events` as `{ t, kind }` only (no content, `key_count` unchanged).
98
+
99
+ ---
100
+
101
+ ## Nuxt 3 (SSR Safe)
102
+
103
+ `synapse-shield-vue` is completely SSR-safe and guards all browser interactions with `onMounted` and `typeof window !== 'undefined'`. No special plugins or SSR flags are required!
104
+
105
+ ```vue
106
+ <!-- pages/login.vue in Nuxt 3 -->
107
+ <script setup>
108
+ import { useSynapseShield } from 'synapse-shield-vue';
109
+
110
+ const { getProtectedPayload } = useSynapseShield();
111
+ // Works automatically on client mount
112
+ </script>
113
+ ```
114
+
115
+ ---
116
+
117
+ ## Features (v0.12.2)
118
+
119
+ - **Universal Keystroke Zero-PII Shield (v0.10.4):** Automatic client-side masking of all single-character inputs (`rawKey.length === 1 -> "masked"`) and sensitive fields, local digraph frequency computation (`is_freq_digraph`), transmitting zero raw text or PII across the wire (GDPR & KVKK compliant).
120
+ - **SPA Token Lifecycle & Coalescing Mutex (v0.10.3):** Single-use challenge token lifecycle invalidation to eliminate 403 Replay Attack loops in Vue 3 and Nuxt applications.
121
+ - **PoW Telemetry Retention (v0.10.3):** Shifts historical telemetry timestamps forward upon PoW challenge retry, eliminating empty telemetry 403 blocks for genuine users.
122
+ - **Mobile SDK v2.0 & Handheld Biometrics (v0.10.0):** Tap hold duration tracking (`tap_duration_ms`), passive 3-axis gyroscope motion variance, and WebGL emulator detection.
123
+ - **Hardened Security Architecture:** Full alignment with Synapse Shield production hardening (Algorithmic DoS mitigation, Rust SIMD differential curvature $\kappa(t)$, zero-copy buffers, and keystroke entropy analysis).
124
+ - **Transparent Token Expiration Refresh:** Seamlessly renegotiates expired tokens (`HTTP 400 EXPIRED`) without triggering IP quarantine or streak bans.
125
+ - **Distributed State & Redis Support:** Full compatibility with Synapse Shield multi-worker cluster deployments.
126
+ - **Transient Iframe Prototype Unhooking:** Detects stealth tools tampering with `Function.prototype.toString`.
127
+ - **Zero-Jank Touch Events:** Passive listeners (`touchstart`, `touchmove`, `touchend`) for high-precision mobile biometrics with zero scroll jank.
128
+ - **Dynamic Yielding PoW Solver:** `solvePow(powSalt, difficulty)` takes the signed `pow_salt` from the server's `challenge_required` response (sha256(salt + nonce), bounded at 20M attempts) and yields to the UI thread every 1,000 iterations to avoid freezing browser rendering. `getProtectedPayload()` consumes the single-use challenge and fetches the next one in the background.
129
+ - **Safe Unicode Base64:** Robust UTF-8 payload encoding across internationalized environments.
130
+ - **Docker Ready Backend:** See the main repository `README.md` for zero-configuration `docker-compose` engine deployment instructions.
131
+
132
+ ## License
133
+
134
+ MIT © Mustafa Güngör
@@ -0,0 +1,15 @@
1
+ export declare const SynapseProtect: import("vue").DefineComponent<import("vue").ExtractPropTypes<{
2
+ apiEndpoint: {
3
+ type: StringConstructor;
4
+ default: string;
5
+ };
6
+ }>, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
7
+ [key: string]: any;
8
+ }>, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<import("vue").ExtractPropTypes<{
9
+ apiEndpoint: {
10
+ type: StringConstructor;
11
+ default: string;
12
+ };
13
+ }>> & Readonly<{}>, {
14
+ apiEndpoint: string;
15
+ }, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
@@ -0,0 +1,19 @@
1
+ import { defineComponent, h } from 'vue';
2
+ import { useSynapseShield } from './useSynapseShield.js';
3
+ export const SynapseProtect = defineComponent({
4
+ name: 'SynapseProtect',
5
+ props: {
6
+ apiEndpoint: {
7
+ type: String,
8
+ default: '/api',
9
+ },
10
+ },
11
+ setup(props) {
12
+ useSynapseShield({ apiEndpoint: props.apiEndpoint });
13
+ return () => h('input', {
14
+ type: 'hidden',
15
+ name: 'synapse_shield_protected',
16
+ value: 'true',
17
+ });
18
+ },
19
+ });
@@ -0,0 +1,4 @@
1
+ export { useSynapseShield } from './useSynapseShield.js';
2
+ export type { SynapseTelemetry, SynapsePayload, UseSynapseShieldOptions, } from './useSynapseShield.js';
3
+ export type { SynapseInputKind } from './timing.js';
4
+ export { SynapseProtect } from './SynapseProtect.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { useSynapseShield } from './useSynapseShield.js';
2
+ export { SynapseProtect } from './SynapseProtect.js';
@@ -0,0 +1,33 @@
1
+ export declare const MIN_CHALLENGE_AGE_MS = 1600;
2
+ export type SynapseInputKind = "autofill" | "paste" | "ime" | "insert";
3
+ type TimedEvent = {
4
+ [field: string]: any;
5
+ };
6
+ export interface TelemetryLists {
7
+ mouse_movements: TimedEvent[];
8
+ clicks: TimedEvent[];
9
+ keystrokes: TimedEvent[];
10
+ scrolls: TimedEvent[];
11
+ input_events: TimedEvent[];
12
+ }
13
+ export declare function challengeTimestamp(challenge: string | null): number | null;
14
+ /**
15
+ * Returns a copy of `t` holding only the events the server can accept for a challenge issued at `challengeTs`
16
+ * that is `ageMs` old: the most recent window of length age + 0.4 s and, for epoch timestamps, nothing older than
17
+ * challenge_ts - 4.9 s. An event is dropped as a whole when any of its time fields (t / down / up) is outside.
18
+ */
19
+ export declare function fitTelemetry<T extends TelemetryLists>(t: T, challengeTs: number | null, ageMs: number): T;
20
+ /** How old a fresh retry challenge must be before sending: <= 3 s (<= 8 s only to keep the last 3 mouse points). */
21
+ export declare function retryWaitMs(t: TelemetryLists): number;
22
+ /**
23
+ * Retry preparation (in place): keep the most recent window the token age allows (span <= age + 0.4 s) and shift
24
+ * it just past `challengeTs` so the Stale rule holds. Intervals between events are preserved.
25
+ */
26
+ export declare function alignForRetry(t: TelemetryLists, challengeTs: number, ageMs: number): void;
27
+ /**
28
+ * Zero-PII input-path classification: only the kind of an insertion, never its content (e.data, clipboard and
29
+ * field values are not read). Autofill / password managers commonly fire plain `input` events without
30
+ * InputEvent.inputType, or "insertReplacementText"; paste and IME commits are counted by their own events.
31
+ */
32
+ export declare function inputEventKind(e: Event): SynapseInputKind | null;
33
+ export {};
package/dist/timing.js ADDED
@@ -0,0 +1,122 @@
1
+ // Server freshness contract (tokens.py verify_and_consume_token), applied with a 100 ms safety margin:
2
+ // token age >= 1.5 s; telemetry span <= token age + 0.5 s (Time Travel);
3
+ // epoch-ms timestamps: min_t >= challenge_ts - 5 s (Stale Telemetry) and max_t <= now + 2 s.
4
+ // Kept identical in synapse-shield-react/src/timing.ts and synapse-shield-vue/src/timing.ts.
5
+ export const MIN_CHALLENGE_AGE_MS = 1600;
6
+ const STALE_LIMIT_MS = 4900;
7
+ const SPAN_SLACK_MS = 400;
8
+ // Retry after a fresh challenge: wait at most this long, then send the most recent window that fits...
9
+ const MAX_RETRY_WAIT_MS = 3000;
10
+ // ...unless that window would leave fewer than 3 mouse points while the session had them (engine.py rejects
11
+ // 0-2 point "teleport" sessions); then wait up to this long so the last 3 points fit.
12
+ const MAX_MOUSE_GUARD_WAIT_MS = 8000;
13
+ const TIME_FIELDS = ["t", "down", "up", "time"];
14
+ const LIST_KEYS = ["mouse_movements", "clicks", "keystrokes", "scrolls", "input_events"];
15
+ export function challengeTimestamp(challenge) {
16
+ if (!challenge)
17
+ return null;
18
+ const parts = challenge.split(".");
19
+ if (parts.length < 2)
20
+ return null;
21
+ const parsed = parseInt(parts[1], 10);
22
+ return isNaN(parsed) ? null : parsed;
23
+ }
24
+ function eventMinTime(ev) {
25
+ let min = Infinity;
26
+ if (!ev)
27
+ return min;
28
+ for (const f of TIME_FIELDS) {
29
+ const v = ev[f];
30
+ if (typeof v === "number" && v < min)
31
+ min = v;
32
+ }
33
+ return min;
34
+ }
35
+ function bounds(t) {
36
+ let min = Infinity;
37
+ let max = -Infinity;
38
+ for (const key of LIST_KEYS) {
39
+ for (const ev of t[key] || []) {
40
+ for (const f of TIME_FIELDS) {
41
+ const v = ev ? ev[f] : undefined;
42
+ if (typeof v === "number") {
43
+ if (v < min)
44
+ min = v;
45
+ if (v > max)
46
+ max = v;
47
+ }
48
+ }
49
+ }
50
+ }
51
+ return min === Infinity ? null : { min, max };
52
+ }
53
+ /**
54
+ * Returns a copy of `t` holding only the events the server can accept for a challenge issued at `challengeTs`
55
+ * that is `ageMs` old: the most recent window of length age + 0.4 s and, for epoch timestamps, nothing older than
56
+ * challenge_ts - 4.9 s. An event is dropped as a whole when any of its time fields (t / down / up) is outside.
57
+ */
58
+ export function fitTelemetry(t, challengeTs, ageMs) {
59
+ const b = bounds(t);
60
+ if (!b)
61
+ return t;
62
+ let cutoff = b.max - Math.max(0, ageMs) - SPAN_SLACK_MS;
63
+ if (b.min > 10000000000 && challengeTs !== null)
64
+ cutoff = Math.max(cutoff, challengeTs - STALE_LIMIT_MS);
65
+ const out = { ...t };
66
+ for (const key of LIST_KEYS)
67
+ out[key] = (t[key] || []).filter((ev) => eventMinTime(ev) >= cutoff);
68
+ return out;
69
+ }
70
+ /** How old a fresh retry challenge must be before sending: <= 3 s (<= 8 s only to keep the last 3 mouse points). */
71
+ export function retryWaitMs(t) {
72
+ const b = bounds(t);
73
+ if (!b)
74
+ return MIN_CHALLENGE_AGE_MS;
75
+ let target = Math.min(b.max - b.min, MAX_RETRY_WAIT_MS + SPAN_SLACK_MS);
76
+ const moves = t.mouse_movements || [];
77
+ if (moves.length >= 3) {
78
+ const needed = b.max - eventMinTime(moves[moves.length - 3]);
79
+ if (needed > target)
80
+ target = Math.min(needed, MAX_MOUSE_GUARD_WAIT_MS + SPAN_SLACK_MS);
81
+ }
82
+ return Math.max(MIN_CHALLENGE_AGE_MS, target - SPAN_SLACK_MS);
83
+ }
84
+ /**
85
+ * Retry preparation (in place): keep the most recent window the token age allows (span <= age + 0.4 s) and shift
86
+ * it just past `challengeTs` so the Stale rule holds. Intervals between events are preserved.
87
+ */
88
+ export function alignForRetry(t, challengeTs, ageMs) {
89
+ const fitted = fitTelemetry(t, null, ageMs);
90
+ for (const key of LIST_KEYS)
91
+ t[key] = fitted[key];
92
+ const b = bounds(t);
93
+ if (!b || b.min >= challengeTs)
94
+ return;
95
+ const shift = challengeTs - b.min + 50;
96
+ for (const key of LIST_KEYS) {
97
+ for (const ev of t[key]) {
98
+ for (const f of TIME_FIELDS)
99
+ if (typeof ev[f] === "number")
100
+ ev[f] += shift;
101
+ }
102
+ }
103
+ }
104
+ /**
105
+ * Zero-PII input-path classification: only the kind of an insertion, never its content (e.data, clipboard and
106
+ * field values are not read). Autofill / password managers commonly fire plain `input` events without
107
+ * InputEvent.inputType, or "insertReplacementText"; paste and IME commits are counted by their own events.
108
+ */
109
+ export function inputEventKind(e) {
110
+ const type = typeof e.inputType === "string" ? e.inputType : "";
111
+ if (!type || type === "insertReplacementText")
112
+ return "autofill";
113
+ if (type === "insertFromDrop")
114
+ return "paste";
115
+ if (type === "insertFromPaste" || type === "insertFromPasteAsQuotation")
116
+ return null;
117
+ if (type === "insertCompositionText" || type === "insertFromComposition")
118
+ return null;
119
+ if (type.indexOf("insert") === 0)
120
+ return "insert";
121
+ return null;
122
+ }
@@ -0,0 +1,180 @@
1
+ import type { SynapseInputKind } from './timing.js';
2
+ export interface SynapseTelemetry {
3
+ mouse_movements: Array<{
4
+ x: number;
5
+ y: number;
6
+ t: number;
7
+ r?: number;
8
+ f?: number;
9
+ source?: string;
10
+ }>;
11
+ clicks: Array<{
12
+ x: number;
13
+ y: number;
14
+ t: number;
15
+ r?: number;
16
+ tap_duration_ms?: number;
17
+ source?: string;
18
+ }>;
19
+ keystrokes: Array<{
20
+ type: string;
21
+ key?: string;
22
+ t: number;
23
+ down?: number;
24
+ up?: number;
25
+ duration_ms?: number;
26
+ is_freq_digraph?: boolean;
27
+ }>;
28
+ scrolls: Array<{
29
+ y: number;
30
+ t: number;
31
+ }>;
32
+ /** Zero-PII non-keyboard text entry (autofill, paste, IME, typed insertions): kind and time only, never content. */
33
+ input_events: Array<{
34
+ t: number;
35
+ kind: SynapseInputKind;
36
+ }>;
37
+ browser: {
38
+ webdriver: boolean;
39
+ screen_width: number;
40
+ screen_height: number;
41
+ device_pixel_ratio?: number;
42
+ touch_supported: boolean;
43
+ max_touch_points?: number;
44
+ motion_variance?: number;
45
+ webgl_renderer?: string;
46
+ orientation?: string;
47
+ is_plugin_array_fake?: boolean;
48
+ has_webdriver_own_prop?: boolean;
49
+ is_webgl_hooked?: boolean;
50
+ is_canvas_hooked?: boolean;
51
+ };
52
+ }
53
+ export interface SynapsePayload {
54
+ telemetry?: SynapseTelemetry;
55
+ token?: string;
56
+ pow_salt?: string;
57
+ pow_nonce?: number;
58
+ }
59
+ export interface UseSynapseShieldOptions {
60
+ apiEndpoint?: string;
61
+ autoChallenge?: boolean;
62
+ moveThrottleMs?: number;
63
+ scrollThrottleMs?: number;
64
+ }
65
+ export declare function telemetryKeyName(key: string | undefined | null, isSensitive: boolean): string;
66
+ export declare function useSynapseShield(options?: UseSynapseShieldOptions): {
67
+ currentChallenge: import("vue").Ref<string | null, string | null>;
68
+ isReady: import("vue").Ref<boolean, boolean>;
69
+ isSolvingPow: import("vue").Ref<boolean, boolean>;
70
+ telemetry: import("vue").Ref<{
71
+ mouse_movements: {
72
+ x: number;
73
+ y: number;
74
+ t: number;
75
+ r?: number | undefined;
76
+ f?: number | undefined;
77
+ source?: string | undefined;
78
+ }[];
79
+ clicks: {
80
+ x: number;
81
+ y: number;
82
+ t: number;
83
+ r?: number | undefined;
84
+ tap_duration_ms?: number | undefined;
85
+ source?: string | undefined;
86
+ }[];
87
+ keystrokes: {
88
+ type: string;
89
+ key?: string | undefined;
90
+ t: number;
91
+ down?: number | undefined;
92
+ up?: number | undefined;
93
+ duration_ms?: number | undefined;
94
+ is_freq_digraph?: boolean | undefined;
95
+ }[];
96
+ scrolls: {
97
+ y: number;
98
+ t: number;
99
+ }[];
100
+ input_events: {
101
+ t: number;
102
+ kind: SynapseInputKind;
103
+ }[];
104
+ browser: {
105
+ webdriver: boolean;
106
+ screen_width: number;
107
+ screen_height: number;
108
+ device_pixel_ratio?: number | undefined;
109
+ touch_supported: boolean;
110
+ max_touch_points?: number | undefined;
111
+ motion_variance?: number | undefined;
112
+ webgl_renderer?: string | undefined;
113
+ orientation?: string | undefined;
114
+ is_plugin_array_fake?: boolean | undefined;
115
+ has_webdriver_own_prop?: boolean | undefined;
116
+ is_webgl_hooked?: boolean | undefined;
117
+ is_canvas_hooked?: boolean | undefined;
118
+ };
119
+ }, SynapseTelemetry | {
120
+ mouse_movements: {
121
+ x: number;
122
+ y: number;
123
+ t: number;
124
+ r?: number | undefined;
125
+ f?: number | undefined;
126
+ source?: string | undefined;
127
+ }[];
128
+ clicks: {
129
+ x: number;
130
+ y: number;
131
+ t: number;
132
+ r?: number | undefined;
133
+ tap_duration_ms?: number | undefined;
134
+ source?: string | undefined;
135
+ }[];
136
+ keystrokes: {
137
+ type: string;
138
+ key?: string | undefined;
139
+ t: number;
140
+ down?: number | undefined;
141
+ up?: number | undefined;
142
+ duration_ms?: number | undefined;
143
+ is_freq_digraph?: boolean | undefined;
144
+ }[];
145
+ scrolls: {
146
+ y: number;
147
+ t: number;
148
+ }[];
149
+ input_events: {
150
+ t: number;
151
+ kind: SynapseInputKind;
152
+ }[];
153
+ browser: {
154
+ webdriver: boolean;
155
+ screen_width: number;
156
+ screen_height: number;
157
+ device_pixel_ratio?: number | undefined;
158
+ touch_supported: boolean;
159
+ max_touch_points?: number | undefined;
160
+ motion_variance?: number | undefined;
161
+ webgl_renderer?: string | undefined;
162
+ orientation?: string | undefined;
163
+ is_plugin_array_fake?: boolean | undefined;
164
+ has_webdriver_own_prop?: boolean | undefined;
165
+ is_webgl_hooked?: boolean | undefined;
166
+ is_canvas_hooked?: boolean | undefined;
167
+ };
168
+ }>;
169
+ refreshChallenge: () => Promise<string | null>;
170
+ solvePow: (powSalt: string, difficulty?: number) => Promise<{
171
+ salt: string;
172
+ nonce: number;
173
+ } | null>;
174
+ getProtectedPayload: (powResult?: {
175
+ salt: string;
176
+ nonce: number;
177
+ }) => SynapsePayload;
178
+ submitProtected: (url: string, buildBody: (payload: SynapsePayload) => unknown, init?: RequestInit) => Promise<Response>;
179
+ reset: () => void;
180
+ };
@@ -0,0 +1,614 @@
1
+ import { ref, onMounted, onBeforeUnmount } from 'vue';
2
+ import { MIN_CHALLENGE_AGE_MS, alignForRetry, challengeTimestamp, fitTelemetry, inputEventKind, retryWaitMs, } from './timing.js';
3
+ // Safe UTF-8 Base64 Encoder (SSR Safe)
4
+ function safeBtoa(str) {
5
+ try {
6
+ if (typeof window !== "undefined" && typeof window.btoa === "function") {
7
+ return window.btoa(str);
8
+ }
9
+ if (typeof Buffer !== "undefined") {
10
+ return Buffer.from(str).toString("base64");
11
+ }
12
+ return "";
13
+ }
14
+ catch (e) {
15
+ if (typeof window !== "undefined" && typeof window.btoa === "function") {
16
+ return window.btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (_, p1) {
17
+ return String.fromCharCode(parseInt(p1, 16));
18
+ }));
19
+ }
20
+ return typeof Buffer !== "undefined" ? Buffer.from(str).toString("base64") : "";
21
+ }
22
+ }
23
+ // Get pristine Function.prototype.toString using an ephemeral iframe to defeat prototype hooks
24
+ function getCleanFunctionToString() {
25
+ try {
26
+ if (typeof document === "undefined" || !document.createElement) {
27
+ return Function.prototype.toString;
28
+ }
29
+ const iframe = document.createElement("iframe");
30
+ iframe.style.display = "none";
31
+ const root = document.body || document.documentElement;
32
+ if (!root)
33
+ return Function.prototype.toString;
34
+ root.appendChild(iframe);
35
+ const cleanToString = iframe.contentWindow.Function.prototype.toString;
36
+ root.removeChild(iframe);
37
+ return cleanToString;
38
+ }
39
+ catch (e) {
40
+ return Function.prototype.toString;
41
+ }
42
+ }
43
+ function getWebGLRenderer() {
44
+ try {
45
+ if (typeof document === "undefined" || !document.createElement)
46
+ return "";
47
+ const canvas = document.createElement("canvas");
48
+ const gl = (canvas.getContext("webgl") || canvas.getContext("experimental-webgl"));
49
+ if (!gl)
50
+ return "";
51
+ const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");
52
+ if (debugInfo) {
53
+ return String(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) || "");
54
+ }
55
+ return String(gl.getParameter(gl.RENDERER) || "");
56
+ }
57
+ catch (e) {
58
+ return "";
59
+ }
60
+ }
61
+ const FREQUENT_DIGRAPHS = new Set([
62
+ "th", "er", "on", "an", "re", "he", "in", "ed", "nd", "ha",
63
+ "at", "en", "es", "of", "or", "nt", "ea", "ti", "to", "it",
64
+ "st", "io", "le", "is", "ou", "ar", "as", "de", "rt", "ve",
65
+ "er", "en", "de", "an", "ar", "in", "la", "le",
66
+ "ik", "ak", "el", "al", "ma", "me", "ba", "ka"
67
+ ]);
68
+ // Zero-PII: only standard named keys (UI Events "key" values such as "Enter", "ArrowLeft",
69
+ // "Unidentified", "F1") may leave the browser by name. Anything else is printed text and is
70
+ // masked — including values longer than one UTF-16 unit (emoji, ligature keys such as "لا",
71
+ // combining sequences, and Turkish "İ" whose lower-case form is two code units).
72
+ const NAMED_KEYS = new Set([
73
+ "enter", "backspace", "tab", "shift", "control", "alt", "altgraph", "meta",
74
+ "capslock", "escape", "arrowleft", "arrowright", "arrowup", "arrowdown", "home", "end",
75
+ "pageup", "pagedown", "insert", "delete", "dead", "process", "unidentified", "numlock",
76
+ "scrolllock", "contextmenu", "pause", "printscreen", "clear", "compose", "f1", "f2",
77
+ "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10",
78
+ "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18",
79
+ "f19", "f20", "f21", "f22", "f23", "f24",
80
+ ]);
81
+ export function telemetryKeyName(key, isSensitive) {
82
+ if (!key)
83
+ return "unknown";
84
+ if (isSensitive || !NAMED_KEYS.has(key.toLowerCase()))
85
+ return "masked";
86
+ return key.toLowerCase();
87
+ }
88
+ function isSensitiveInput(target) {
89
+ if (!target)
90
+ return false;
91
+ try {
92
+ const type = (target.getAttribute && target.getAttribute("type")) || target.type || "";
93
+ const name = (target.getAttribute && target.getAttribute("name")) || target.name || "";
94
+ const id = target.id || "";
95
+ const autocomplete = (target.getAttribute && target.getAttribute("autocomplete")) || target.autocomplete || "";
96
+ const sensitiveRegex = /password|passcode|secret|pin|cvv|cvc|card|credit|security_code|token/i;
97
+ const tLower = String(type).toLowerCase();
98
+ const aLower = String(autocomplete).toLowerCase();
99
+ if (tLower === "password" ||
100
+ aLower === "current-password" ||
101
+ aLower === "new-password" ||
102
+ aLower === "cc-number" ||
103
+ aLower === "cc-csc") {
104
+ return true;
105
+ }
106
+ if (sensitiveRegex.test(String(name)) || sensitiveRegex.test(String(id))) {
107
+ return true;
108
+ }
109
+ }
110
+ catch (e) { }
111
+ return false;
112
+ }
113
+ export function useSynapseShield(options = {}) {
114
+ const { apiEndpoint = '/api', autoChallenge = true, moveThrottleMs = 30, scrollThrottleMs = 100, } = options;
115
+ const currentChallenge = ref(null);
116
+ const isReady = ref(false);
117
+ const isSolvingPow = ref(false);
118
+ const telemetry = ref({
119
+ mouse_movements: [],
120
+ clicks: [],
121
+ keystrokes: [],
122
+ scrolls: [],
123
+ input_events: [],
124
+ browser: {
125
+ webdriver: false,
126
+ screen_width: 0,
127
+ screen_height: 0,
128
+ touch_supported: false,
129
+ },
130
+ });
131
+ let lastMoveTime = 0;
132
+ let lastScrollTime = 0;
133
+ let lastMotionTime = 0;
134
+ let lastTouchStartTime = 0;
135
+ let motionSamples = [];
136
+ const activeKeys = {};
137
+ let lastRawKey = "";
138
+ // Local time at which the current challenge arrived (its age decides which telemetry the server accepts).
139
+ let challengeFetchedAt = 0;
140
+ let refreshPromise = null;
141
+ const fetchChallenge = async () => {
142
+ if (typeof window === 'undefined')
143
+ return null;
144
+ try {
145
+ const res = await fetch(`${apiEndpoint}/challenge`);
146
+ if (res.ok) {
147
+ const data = await res.json();
148
+ return typeof data.challenge === "string" ? data.challenge : null;
149
+ }
150
+ }
151
+ catch (e) {
152
+ console.warn("[Synapse Shield] Could not fetch challenge, falling back to unsigned mode.");
153
+ }
154
+ return null;
155
+ };
156
+ const refreshChallenge = async () => {
157
+ if (refreshPromise)
158
+ return refreshPromise;
159
+ refreshPromise = (async () => {
160
+ try {
161
+ const challenge = await fetchChallenge();
162
+ if (challenge) {
163
+ currentChallenge.value = challenge;
164
+ challengeFetchedAt = Date.now();
165
+ }
166
+ return challenge;
167
+ }
168
+ finally {
169
+ refreshPromise = null;
170
+ }
171
+ })();
172
+ return refreshPromise;
173
+ };
174
+ /**
175
+ * Solves the server's proof-of-work: find `nonce` so that sha256(powSalt + nonce) starts with `difficulty`
176
+ * zeros. `powSalt` MUST be the signed `pow_salt` from the `challenge_required` response (the server verifies
177
+ * its HMAC, expiry and difficulty); a client-generated salt can never be accepted.
178
+ */
179
+ const solvePow = async (powSalt, difficulty = 4) => {
180
+ if (typeof crypto === 'undefined' || !crypto.subtle)
181
+ return null;
182
+ isSolvingPow.value = true;
183
+ try {
184
+ const targetPrefix = '0'.repeat(difficulty);
185
+ const salt = powSalt;
186
+ let nonce = 0;
187
+ const maxAttempts = 20000000;
188
+ const encoder = new TextEncoder();
189
+ while (nonce < maxAttempts) {
190
+ // Yield to browser UI thread periodically to avoid jank
191
+ if (nonce % 1000 === 0 && nonce > 0) {
192
+ await new Promise((r) => setTimeout(r, 0));
193
+ }
194
+ const data = encoder.encode(salt + nonce);
195
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
196
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
197
+ const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
198
+ if (hashHex.startsWith(targetPrefix)) {
199
+ return { salt, nonce };
200
+ }
201
+ nonce++;
202
+ }
203
+ return null;
204
+ }
205
+ finally {
206
+ isSolvingPow.value = false;
207
+ }
208
+ };
209
+ const reset = () => {
210
+ telemetry.value.mouse_movements = [];
211
+ telemetry.value.clicks = [];
212
+ telemetry.value.keystrokes = [];
213
+ telemetry.value.scrolls = [];
214
+ telemetry.value.input_events = [];
215
+ motionSamples = [];
216
+ lastTouchStartTime = 0;
217
+ };
218
+ const getProtectedPayload = (powResult) => {
219
+ const n = motionSamples.length;
220
+ if (n >= 2) {
221
+ const mean = motionSamples.reduce((a, b) => a + b, 0) / n;
222
+ const variance = motionSamples.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / n;
223
+ telemetry.value.browser.motion_variance = Math.round(variance * 1000000) / 1000000;
224
+ }
225
+ else {
226
+ telemetry.value.browser.motion_variance = 0;
227
+ }
228
+ if (currentChallenge.value) {
229
+ // Only the events this challenge can vouch for: older ones (long SPA session, renewed challenge) would make
230
+ // the server reject the whole token as Stale Telemetry / Time Travel.
231
+ const envelope = {
232
+ challenge: currentChallenge.value,
233
+ telemetry: fitTelemetry(telemetry.value, challengeTimestamp(currentChallenge.value), Date.now() - challengeFetchedAt),
234
+ created_at: Date.now(),
235
+ };
236
+ if (powResult) {
237
+ envelope.pow_salt = powResult.salt;
238
+ envelope.pow_nonce = powResult.nonce;
239
+ }
240
+ // The challenge is single-use: consume it and fetch the next one in the background so a second
241
+ // submission in the same SPA session does not replay it (HTTP 403).
242
+ currentChallenge.value = null;
243
+ void refreshChallenge();
244
+ return {
245
+ token: safeBtoa(JSON.stringify(envelope)),
246
+ ...(powResult ? { pow_salt: powResult.salt, pow_nonce: powResult.nonce } : {}),
247
+ };
248
+ }
249
+ return { telemetry: telemetry.value };
250
+ };
251
+ /**
252
+ * POSTs a protected request and transparently handles the gray-area proof-of-work challenge (parity with the
253
+ * React SDK). `buildBody` receives the payload (`token`, plus `pow_salt`/`pow_nonce` on the retry) and returns the
254
+ * JSON body; put `pow_salt` and `pow_nonce` at the top level of that body, where the server middleware reads them.
255
+ * On HTTP 429 `challenge_required` it fetches a fresh challenge, solves the PoW and retries exactly ONCE.
256
+ * The final Response (including a second 429) is returned as is; there is no further retry.
257
+ */
258
+ const submitProtected = async (url, buildBody, init = {}) => {
259
+ const send = (payload) => {
260
+ const headers = new Headers(init.headers);
261
+ if (!headers.has("Content-Type"))
262
+ headers.set("Content-Type", "application/json");
263
+ return fetch(url, {
264
+ ...init,
265
+ method: init.method || "POST",
266
+ headers,
267
+ body: JSON.stringify(buildBody(payload)),
268
+ });
269
+ };
270
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
271
+ // A missing or nearly-expired challenge (60 s lifetime) is renewed first; any challenge younger than the
272
+ // server's 1.5 s minimum is aged first. getProtectedPayload() then drops events older than its window.
273
+ if (!currentChallenge.value || Date.now() - challengeFetchedAt > 45000) {
274
+ await refreshChallenge();
275
+ }
276
+ const age = Date.now() - challengeFetchedAt;
277
+ if (currentChallenge.value && age < MIN_CHALLENGE_AGE_MS)
278
+ await sleep(MIN_CHALLENGE_AGE_MS - age);
279
+ const hadChallenge = Boolean(currentChallenge.value);
280
+ const first = await send(getProtectedPayload());
281
+ if (first.status === 503) {
282
+ if (refreshPromise)
283
+ await refreshPromise;
284
+ else if (!hadChallenge && !currentChallenge.value)
285
+ await refreshChallenge();
286
+ return first;
287
+ }
288
+ if (first.status !== 429) {
289
+ reset();
290
+ return first;
291
+ }
292
+ let body = null;
293
+ try {
294
+ body = await first.clone().json();
295
+ }
296
+ catch (e) { }
297
+ const challenge = [body, body?.detail, body?.extra].find((c) => c && typeof c === "object" && c.status === "challenge_required");
298
+ if (!challenge || typeof challenge.pow_salt !== "string" || !challenge.pow_salt) {
299
+ reset();
300
+ return first;
301
+ }
302
+ // The first token consumed our challenge: fetch a fresh one while the PoW is solved.
303
+ let freshAt = 0;
304
+ const [fresh, solution] = await Promise.all([
305
+ fetchChallenge().then((c) => {
306
+ freshAt = Date.now();
307
+ return c;
308
+ }),
309
+ solvePow(challenge.pow_salt, Number(challenge.pow_difficulty) || 4),
310
+ ]);
311
+ if (!fresh || !solution)
312
+ return first; // cannot comply (no Web Crypto / no challenge); caller sees the 429
313
+ // Server checks: token age >= 1.5 s and telemetry span <= token age + 0.5 s. Wait briefly (<= 3 s; <= 8 s only
314
+ // to keep the last 3 mouse points), then send the most recent window that fits, shifted past challenge_ts.
315
+ const remaining = retryWaitMs(telemetry.value) - (Date.now() - freshAt);
316
+ if (remaining > 0)
317
+ await sleep(remaining);
318
+ alignForRetry(telemetry.value, challengeTimestamp(fresh) ?? freshAt, Date.now() - freshAt);
319
+ // Re-assert our challenge: a background refresh started by the first payload may have replaced it.
320
+ currentChallenge.value = fresh;
321
+ challengeFetchedAt = freshAt;
322
+ const second = await send(getProtectedPayload(solution));
323
+ if (second.status === 503) {
324
+ if (refreshPromise)
325
+ await refreshPromise;
326
+ return second;
327
+ }
328
+ reset();
329
+ return second;
330
+ };
331
+ // Non-keyboard text entry: counted in input_events so key_count is never inflated (Zero-PII: no content read).
332
+ const pushInputEvent = (kind) => {
333
+ telemetry.value.input_events.push({ t: Date.now(), kind });
334
+ if (telemetry.value.input_events.length > 50)
335
+ telemetry.value.input_events.shift();
336
+ };
337
+ const handleInput = (e) => {
338
+ const kind = inputEventKind(e);
339
+ if (kind)
340
+ pushInputEvent(kind);
341
+ };
342
+ const handlePaste = () => pushInputEvent("paste");
343
+ const handleCompositionEnd = () => pushInputEvent("ime");
344
+ // Event handlers
345
+ const handleMouseMove = (e) => {
346
+ const now = Date.now();
347
+ if (now - lastMoveTime >= moveThrottleMs) {
348
+ telemetry.value.mouse_movements.push({ x: e.clientX, y: e.clientY, t: now });
349
+ lastMoveTime = now;
350
+ if (telemetry.value.mouse_movements.length > 500)
351
+ telemetry.value.mouse_movements.shift();
352
+ }
353
+ };
354
+ const handleTouchStart = (e) => {
355
+ if (!e.touches || e.touches.length === 0)
356
+ return;
357
+ const touch = e.touches[0];
358
+ const now = Date.now();
359
+ lastTouchStartTime = now;
360
+ const rX = touch.radiusX || touch.webkitRadiusX || 0;
361
+ const rY = touch.radiusY || touch.webkitRadiusY || rX;
362
+ const r = (rX + rY) * 0.5;
363
+ const f = touch.force || touch.webkitForce || 0;
364
+ telemetry.value.mouse_movements.push({
365
+ x: touch.clientX,
366
+ y: touch.clientY,
367
+ t: now,
368
+ r: Math.round(r * 1000) / 1000,
369
+ f: Math.round(f * 1000) / 1000,
370
+ source: "touch",
371
+ });
372
+ lastMoveTime = now;
373
+ if (telemetry.value.mouse_movements.length > 500)
374
+ telemetry.value.mouse_movements.shift();
375
+ };
376
+ const handleTouchMove = (e) => {
377
+ if (!e.touches || e.touches.length === 0)
378
+ return;
379
+ const now = Date.now();
380
+ if (now - lastMoveTime >= moveThrottleMs) {
381
+ const touch = e.touches[0];
382
+ const rX = touch.radiusX || touch.webkitRadiusX || 0;
383
+ const rY = touch.radiusY || touch.webkitRadiusY || rX;
384
+ const r = (rX + rY) * 0.5;
385
+ const f = touch.force || touch.webkitForce || 0;
386
+ telemetry.value.mouse_movements.push({
387
+ x: touch.clientX,
388
+ y: touch.clientY,
389
+ t: now,
390
+ r: Math.round(r * 1000) / 1000,
391
+ f: Math.round(f * 1000) / 1000,
392
+ source: "touch",
393
+ });
394
+ lastMoveTime = now;
395
+ if (telemetry.value.mouse_movements.length > 500)
396
+ telemetry.value.mouse_movements.shift();
397
+ }
398
+ };
399
+ const handleTouchEnd = (e) => {
400
+ if (e.changedTouches && e.changedTouches.length > 0) {
401
+ const touch = e.changedTouches[0];
402
+ const now = Date.now();
403
+ const rX = touch.radiusX || touch.webkitRadiusX || 0;
404
+ const rY = touch.radiusY || touch.webkitRadiusY || rX;
405
+ const r = (rX + rY) * 0.5;
406
+ const tapDuration = lastTouchStartTime > 0 ? Math.max(1, now - lastTouchStartTime) : 0;
407
+ telemetry.value.clicks.push({
408
+ x: touch.clientX,
409
+ y: touch.clientY,
410
+ t: now,
411
+ r: Math.round(r * 1000) / 1000,
412
+ tap_duration_ms: tapDuration,
413
+ source: "touch",
414
+ });
415
+ if (telemetry.value.clicks.length > 50)
416
+ telemetry.value.clicks.shift();
417
+ }
418
+ };
419
+ const handleDeviceMotion = (e) => {
420
+ const now = Date.now();
421
+ if (now - lastMotionTime < 50)
422
+ return;
423
+ const acc = e.accelerationIncludingGravity || e.acceleration;
424
+ const rot = e.rotationRate;
425
+ let mag = 0;
426
+ if (acc && (acc.x !== null || acc.y !== null || acc.z !== null)) {
427
+ const ax = Number(acc.x) || 0;
428
+ const ay = Number(acc.y) || 0;
429
+ const az = Number(acc.z) || 0;
430
+ mag += Math.sqrt(ax * ax + ay * ay + az * az);
431
+ }
432
+ if (rot && (rot.alpha !== null || rot.beta !== null || rot.gamma !== null)) {
433
+ const ra = Number(rot.alpha) || 0;
434
+ const rb = Number(rot.beta) || 0;
435
+ const rg = Number(rot.gamma) || 0;
436
+ mag += Math.sqrt(ra * ra + rb * rb + rg * rg) * 0.1;
437
+ }
438
+ if (mag > 0) {
439
+ motionSamples.push(mag);
440
+ lastMotionTime = now;
441
+ if (motionSamples.length > 40)
442
+ motionSamples.shift();
443
+ }
444
+ };
445
+ const handleClick = (e) => {
446
+ const now = Date.now();
447
+ if (lastTouchStartTime > 0 && now - lastTouchStartTime < 800) {
448
+ return;
449
+ }
450
+ telemetry.value.clicks.push({ x: e.clientX, y: e.clientY, t: now });
451
+ if (telemetry.value.clicks.length > 50)
452
+ telemetry.value.clicks.shift();
453
+ };
454
+ const handleKeyDown = (e) => {
455
+ const isSens = isSensitiveInput(e.target);
456
+ const rawKey = e.key ? (e.key.length === 1 ? e.key.toLowerCase() : e.key.toLowerCase() || e.code || "unknown") : "unknown";
457
+ const lookupId = e.code || rawKey;
458
+ const now = Date.now();
459
+ let isFreq = false;
460
+ if (lastRawKey && rawKey && lastRawKey.length === 1 && rawKey.length === 1) {
461
+ isFreq = FREQUENT_DIGRAPHS.has(lastRawKey + rawKey);
462
+ }
463
+ lastRawKey = rawKey;
464
+ const keyName = telemetryKeyName(e.key, isSens);
465
+ if (!activeKeys[lookupId]) {
466
+ activeKeys[lookupId] = { down: now, isFreq };
467
+ }
468
+ telemetry.value.keystrokes.push({
469
+ type: "down",
470
+ key: keyName,
471
+ t: now,
472
+ is_freq_digraph: isFreq,
473
+ });
474
+ if (telemetry.value.keystrokes.length > 50)
475
+ telemetry.value.keystrokes.shift();
476
+ };
477
+ const handleKeyUp = (e) => {
478
+ const isSens = isSensitiveInput(e.target);
479
+ const rawKey = e.key ? (e.key.length === 1 ? e.key.toLowerCase() : e.key.toLowerCase() || e.code || "unknown") : "unknown";
480
+ const lookupId = e.code || rawKey;
481
+ const keyName = telemetryKeyName(e.key, isSens);
482
+ const now = Date.now();
483
+ const keyState = activeKeys[lookupId];
484
+ delete activeKeys[lookupId];
485
+ const downTime = keyState ? keyState.down : now;
486
+ const isFreq = keyState ? keyState.isFreq : false;
487
+ const duration = keyState ? (now - downTime) : 0;
488
+ telemetry.value.keystrokes.push({
489
+ type: "up",
490
+ key: keyName,
491
+ t: now,
492
+ down: downTime,
493
+ up: now,
494
+ duration_ms: duration,
495
+ is_freq_digraph: isFreq,
496
+ });
497
+ if (telemetry.value.keystrokes.length > 50)
498
+ telemetry.value.keystrokes.shift();
499
+ };
500
+ const handleScroll = () => {
501
+ const now = Date.now();
502
+ if (now - lastScrollTime >= scrollThrottleMs) {
503
+ telemetry.value.scrolls.push({
504
+ y: window.scrollY || document.documentElement.scrollTop,
505
+ t: now,
506
+ });
507
+ lastScrollTime = now;
508
+ if (telemetry.value.scrolls.length > 200)
509
+ telemetry.value.scrolls.shift();
510
+ }
511
+ };
512
+ onMounted(async () => {
513
+ if (typeof window === 'undefined')
514
+ return;
515
+ // Advanced Tamper Detection
516
+ const checkWebGLHook = () => {
517
+ try {
518
+ const canvas = document.createElement("canvas");
519
+ const gl = (canvas.getContext("webgl") || canvas.getContext("experimental-webgl"));
520
+ if (gl) {
521
+ const cleanToString = getCleanFunctionToString();
522
+ const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");
523
+ if (debugInfo) {
524
+ const getParameterFunc = gl.getParameter;
525
+ const str = cleanToString.call(getParameterFunc);
526
+ if (str.indexOf("[native code]") === -1)
527
+ return true;
528
+ }
529
+ }
530
+ }
531
+ catch (e) { }
532
+ return false;
533
+ };
534
+ const checkCanvasHook = () => {
535
+ try {
536
+ const cleanToString = getCleanFunctionToString();
537
+ const str = cleanToString.call(HTMLCanvasElement.prototype.toDataURL);
538
+ if (str.indexOf("[native code]") === -1)
539
+ return true;
540
+ }
541
+ catch (e) { }
542
+ return false;
543
+ };
544
+ const isPluginArrayFake = () => {
545
+ try {
546
+ if (navigator.plugins && navigator.plugins.length > 0) {
547
+ if (navigator.plugins.constructor !== PluginArray)
548
+ return true;
549
+ }
550
+ }
551
+ catch (e) { }
552
+ return false;
553
+ };
554
+ telemetry.value.browser = {
555
+ webdriver: navigator.webdriver || false,
556
+ screen_width: window.innerWidth || window.screen.width,
557
+ screen_height: window.innerHeight || window.screen.height,
558
+ device_pixel_ratio: window.devicePixelRatio || 1,
559
+ touch_supported: "ontouchstart" in window || navigator.maxTouchPoints > 0,
560
+ max_touch_points: typeof navigator !== "undefined" ? navigator.maxTouchPoints || 0 : 0,
561
+ motion_variance: 0,
562
+ webgl_renderer: getWebGLRenderer(),
563
+ orientation: (window.screen && window.screen.orientation && window.screen.orientation.type) ? window.screen.orientation.type : "",
564
+ is_plugin_array_fake: isPluginArrayFake(),
565
+ has_webdriver_own_prop: Object.prototype.hasOwnProperty.call(navigator, "webdriver"),
566
+ is_webgl_hooked: checkWebGLHook(),
567
+ is_canvas_hooked: checkCanvasHook(),
568
+ };
569
+ if (autoChallenge) {
570
+ await refreshChallenge();
571
+ }
572
+ // Attach passive listeners
573
+ window.addEventListener("mousemove", handleMouseMove, { passive: true });
574
+ window.addEventListener("touchstart", handleTouchStart, { passive: true });
575
+ window.addEventListener("touchmove", handleTouchMove, { passive: true });
576
+ window.addEventListener("touchend", handleTouchEnd, { passive: true });
577
+ window.addEventListener("devicemotion", handleDeviceMotion, { passive: true });
578
+ window.addEventListener("click", handleClick, { passive: true });
579
+ window.addEventListener("keydown", handleKeyDown, { passive: true });
580
+ window.addEventListener("keyup", handleKeyUp, { passive: true });
581
+ window.addEventListener("scroll", handleScroll, { passive: true });
582
+ window.addEventListener("input", handleInput, { passive: true, capture: true });
583
+ window.addEventListener("paste", handlePaste, { passive: true, capture: true });
584
+ window.addEventListener("compositionend", handleCompositionEnd, { passive: true, capture: true });
585
+ isReady.value = true;
586
+ });
587
+ onBeforeUnmount(() => {
588
+ if (typeof window === 'undefined')
589
+ return;
590
+ window.removeEventListener("mousemove", handleMouseMove);
591
+ window.removeEventListener("touchstart", handleTouchStart);
592
+ window.removeEventListener("touchmove", handleTouchMove);
593
+ window.removeEventListener("touchend", handleTouchEnd);
594
+ window.removeEventListener("devicemotion", handleDeviceMotion);
595
+ window.removeEventListener("click", handleClick);
596
+ window.removeEventListener("keydown", handleKeyDown);
597
+ window.removeEventListener("keyup", handleKeyUp);
598
+ window.removeEventListener("scroll", handleScroll);
599
+ window.removeEventListener("input", handleInput, true);
600
+ window.removeEventListener("paste", handlePaste, true);
601
+ window.removeEventListener("compositionend", handleCompositionEnd, true);
602
+ });
603
+ return {
604
+ currentChallenge,
605
+ isReady,
606
+ isSolvingPow,
607
+ telemetry,
608
+ refreshChallenge,
609
+ solvePow,
610
+ getProtectedPayload,
611
+ submitProtected,
612
+ reset,
613
+ };
614
+ }
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
- {
2
- "name": "synapse-shield-vue",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
1
+ {
2
+ "name": "synapse-shield-vue",
3
+ "version": "0.12.2",
4
+ "description": "Vue 3 and Nuxt 3 integration for Synapse Shield Behavioral Biometrics",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "sideEffects": false,
10
+ "engines": {
11
+ "node": ">=18"
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsc",
20
+ "prepublishOnly": "npm run build"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/0xStoic-bit/Synapse_Shield.git",
25
+ "directory": "synapse-shield-vue"
26
+ },
27
+ "bugs": {
28
+ "url": "https://github.com/0xStoic-bit/Synapse_Shield/issues"
29
+ },
30
+ "homepage": "https://github.com/0xStoic-bit/Synapse_Shield/tree/main/synapse-shield-vue#readme",
31
+ "keywords": [
32
+ "vue",
33
+ "vue3",
34
+ "nuxt",
35
+ "nuxt3",
36
+ "synapse-shield",
37
+ "bot-protection",
38
+ "biometrics",
39
+ "anti-bot"
40
+ ],
41
+ "author": "Mustafa G\u00fcng\u00f6r",
42
+ "license": "MIT",
43
+ "peerDependencies": {
44
+ "vue": ">=3.0.0"
45
+ },
46
+ "devDependencies": {
47
+ "typescript": "^5.0.0",
48
+ "vue": "^3.4.0"
49
+ }
6
50
  }