synapse-shield 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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.
@@ -0,0 +1,217 @@
1
+ Metadata-Version: 2.4
2
+ Name: synapse-shield
3
+ Version: 0.1.0
4
+ Summary: FastAPI Behavioral Bot Detection Engine & Middleware
5
+ License: MIT
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Operating System :: OS Independent
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: fastapi>=0.110.0
13
+ Requires-Dist: uvicorn>=0.28.0
14
+ Requires-Dist: python-multipart>=0.0.9
15
+ Dynamic: license-file
16
+
17
+ <div align="center">
18
+
19
+ # 🛡️ SYNAPSE SHIELD
20
+
21
+ ### Next-Gen Open-Source Behavioral Biometrics & Bot Mitigation Engine
22
+
23
+ **A privacy-first, zero-friction, self-hosted alternative to Cloudflare Turnstile.**
24
+
25
+ [![License: MIT](https://img.shields.io/badge/License-MIT-00F0FF.svg)](https://opensource.org/licenses/MIT)
26
+ [![FastAPI](https://img.shields.io/badge/FastAPI-0.110+-009688.svg?logo=fastapi)](https://fastapi.tiangolo.com)
27
+ [![Python 3.12](https://img.shields.io/badge/Python-3.12-blue.svg?logo=python)](https://python.org)
28
+ [![Inference SLA](https://img.shields.io/badge/Latency-%3C0.5ms-10B981.svg)]()
29
+ [![Zero-PII](https://img.shields.io/badge/Privacy-100%25%20Zero--PII-success.svg)]()
30
+
31
+ [Features](#-key-features) • [Architecture](#-architecture) • [Quickstart](#-30-second-quickstart) • [Developer Guide](#-developer-integration) • [Benchmarks](#-attack-simulation-benchmarks)
32
+
33
+ </div>
34
+
35
+ ---
36
+
37
+ ## ⚡ Overview
38
+
39
+ **Synapse Shield** replaces intrusive legacy CAPTCHAs and proprietary cloud WAFs with **sub-millisecond behavioral biomechanics & cryptographic challenges**.
40
+
41
+ By evaluating natural human neuromuscular micro-tremors (**Jerk: $da/dt$**), cursor trajectory curvature, Fitts's Law validation (terminal deceleration profiles), and millisecond keystroke intervals, Synapse Shield autonomously classifies and mitigates bots, scrapers, and credential stuffers before they touch your backend logic.
42
+
43
+ ---
44
+
45
+ ## ✨ Key Features
46
+
47
+ - **🧩 100% Invisible & Friction-Free UX:** Zero annoying puzzle solving, image selecting, or audio challenges. Genuine human users pass instantly.
48
+ - **🔑 Cryptographic Challenge-Response:** Native protection against telemetry replay attacks. Clients fetch a single-use token from `/api/challenge` and sign their telemetry payload.
49
+ - **📈 Fitts's Law Deceleration Profiling:** Evaluates mouse deceleration as it approaches targets/clicks (`terminal_decel_ratio`) and checks velocity asymmetry (`velocity_skewness`) to detect mechanical bot paths.
50
+ - **⚡ Ultra-Low Latency (<0.5 ms):** Evaluated locally in-memory using lightweight NumPy & mathematical kinematic scoring.
51
+ - **🔒 100% Zero-PII & Privacy-First:** No keystroke characters, form inputs, or personally identifiable information are captured. Only relative millisecond delta timestamps are processed (GDPR / KVKK compliant).
52
+ - **💸 $0 Cloud Costs (Self-Hostable):** Zero third-party cloud lock-in. Run anywhere with a single packages command.
53
+ - **📊 Poisson Flooder Detection:** Catches high-frequency headless API scrapers lacking mouse telemetry using cumulative Poisson anomaly distributions.
54
+ - **🎮 Interactive 3D Security Lab:** Built-in Three.js & WebGL visual dashboard with real-time SQLite audit trails and live telemetry gauges.
55
+
56
+ ---
57
+
58
+ ## 🏛️ Architecture
59
+
60
+ ```
61
+ [ CLIENT BROWSER ]
62
+
63
+ ├── (1) GET /api/challenge ──► (Generates single-use Cryptographic Token)
64
+
65
+ ├── (2) Capture 50 Hz Biometric Telemetry (Mouse, Touch, Key Timestamps)
66
+
67
+ ▼ [Signed Telemetry Payload (Telemetry + Token)]
68
+ [ FASTAPI INGRESS GATEWAY ]
69
+
70
+ ├── (3) Token verification & Replay Attack check
71
+
72
+ ├── (4) Kinematic Feature Extraction (19D Physical Vector)
73
+ │ [Jerk: da/dt, Deceleration Ratio, Velocity Skewness, Straightness]
74
+
75
+ [ REAL-TIME DECISION ENGINE (<0.5 ms) ]
76
+
77
+ ├────────────────────────┬────────────────────────┐
78
+ ▼ ▼ ▼
79
+ [ RISK < 50% ] [ 50% ≤ RISK < 70% ] [ RISK ≥ 70% ]
80
+ Clean Human Suspicious Traffic Automated Bot
81
+ │ │ │
82
+ ▼ ▼ ▼
83
+ [ ALLOW 200 ] [ CHALLENGE / POW ] [ BLOCK 403 ]
84
+ (Seamless Pass) (Dynamic Challenge) (Access Denied)
85
+ ```
86
+
87
+ ---
88
+
89
+ ## 🚀 30-Second Quickstart
90
+
91
+ ### Installing the Command Line Tool
92
+
93
+ Since Synapse Shield is built as a pyproject.toml package, you can run CLI commands directly:
94
+
95
+ ```bash
96
+ # 1. Install dependencies
97
+ pip install -r requirements.txt
98
+
99
+ # 2. Run the Synapse Shield server (with Hot-Reload dynamic auto-reload enabled)
100
+
101
+ synapse-shield run --host 0.0.0.0 --port 8000
102
+
103
+ ````
104
+
105
+ Visit http://127.0.0.1:8000 in your browser to launch the Security Lab Cockpit dashboard.
106
+
107
+ ### Running the Simulation Suite
108
+
109
+ To run the automated adversarial Red Team simulation suite showing Fitts's Law violations and Replay Attack mitigations:
110
+
111
+ ```bash
112
+ synapse-shield test
113
+ ````
114
+
115
+ ---
116
+
117
+ ## 💻 Developer Integration
118
+
119
+ ### 1. Backend Protection (FastAPI Decorator)
120
+
121
+ Protect any API endpoint or login route using the `@shield_protect` decorator:
122
+
123
+ ```python
124
+ from fastapi import FastAPI, Request
125
+ from synapse_shield.middleware import shield_protect
126
+
127
+ app = FastAPI()
128
+
129
+ @app.post("/api/login")
130
+ @shield_protect(max_risk_score=50.0)
131
+ async def login(request: Request):
132
+ # This code only executes if Synapse Shield verifies the request as Human
133
+ return {"status": "success", "message": "Authenticated successfully"}
134
+ ```
135
+
136
+ ### 2. Frontend Integration (Vanilla JS Sync)
137
+
138
+ Include the SDK (<5 KB) and wrap your sensitive form submission:
139
+
140
+ ```html
141
+ <!-- Include SDK -->
142
+ <script src="http://your-server:8000/static/synapse-sdk.js"></script>
143
+
144
+ <script>
145
+ // Initialize biometric listener
146
+ SynapseShield.init();
147
+
148
+ async function handleLogin() {
149
+ // Automatically retrieves challenge, packages telemetry, and submits to verification endpoint
150
+ const response = await SynapseShield.submit("/api/score");
151
+ console.log("Evaluation Result:", response);
152
+ }
153
+ </script>
154
+ ```
155
+
156
+ ---
157
+
158
+ ## 🤖 Attack Simulation Benchmarks
159
+
160
+ Synapse Shield includes an automated adversarial test suite simulating 7 distinct attack vectors:
161
+
162
+ | Test Scenario | Attack Signature | Detection Mechanism | Decision | Risk Score |
163
+ | :--------------------- | :---------------------------------------- | :---------------------------------------- | :-------- | :--------- |
164
+ | **Natural Human** | Organic curves with tremors | Biological Jerk & Deceleration verified | **ALLOW** | <10.0% |
165
+ | **Linear Bot** | Selenium straight-line cursor | $\text{Straightness} = 1.000$ & Zero Jerk | **BLOCK** | 98.5% |
166
+ | **Replay Attacker** | Reuse of valid telemetry signature | Cryptographic Token Reused / Stale | **BLOCK** | 100.0% |
167
+ | **Fitts Violator Bot** | Direct speed click - no terminal slowdown | `terminal_decel_ratio > 0.85` | **BLOCK** | 80.0% |
168
+ | **Poisson Flooder** | 8 rapid requests in $<500\text{ ms}$ | Poisson frequency anomaly ($P > 95\%$) | **BLOCK** | 85.0% |
169
+ | **Selenium Webdriver** | Automated headless crawler | `navigator.webdriver = true` | **BLOCK** | 100.0% |
170
+ | **Robotic Auto-Typer** | Constant 50ms keystrokes | $\text{Key Variance} < 1.0\text{ ms}^2$ | **BLOCK** | 92.0% |
171
+
172
+ ---
173
+
174
+ ## 🧠 Kinematic & Mathematical Foundation
175
+
176
+ Synapse Shield extracts physical motion vectors derived from classical biomechanics:
177
+
178
+ **1. Jerk (Acceleration Derivative):**
179
+ $$\text{Jerk} = \frac{da}{dt} = \frac{d^3x}{dt^3}$$
180
+ Human neuromuscular micro-tremors produce continuous high-frequency Jerk, whereas mathematical bot curves (Bézier/Linear) produce near-zero or static Jerk.
181
+
182
+ **2. Fitts's Target Deceleration Profile:**
183
+ $$\text{Terminal Decel Ratio} = \frac{\bar{v}_{\text{terminal}}}{v_{\text{max}}}$$
184
+ Humans reflexively slow down when approaching a target click button ($\text{Terminal Decel Ratio} < 0.40$), whereas simple click bots maintain monotonic high speeds during clicks.
185
+
186
+ **3. Poisson Request Rate Anomaly:**
187
+ $$P(X \ge k) = 1 - \sum_{i=0}^{k-1} \frac{\lambda^i e^{-\lambda}}{i!}$$
188
+
189
+ ---
190
+
191
+ ## 📁 Repository Structure
192
+
193
+ ```
194
+ Synapse_Shield/
195
+ ├── pyproject.toml # PyPI Paket Tanımı & Yapılandırması
196
+ ├── README.md # Proje dokümantasyonu
197
+ ├── LICENSE # MIT Lisans dosyası
198
+ ├── requirements.txt # Gerekli kütüphaneler listesi
199
+ └── src/
200
+ └── synapse_shield/ # Asıl Kütüphane Paketi
201
+ ├── __init__.py # Dışa aktarılan API (shield_protect, SynapseEngine)
202
+ ├── engine.py # Karar motoru
203
+ ├── features.py # Kinematik matematik modülü
204
+ ├── middleware.py # FastAPI dekoratörü
205
+ ├── cli.py # Terminal komutu (synapse-shield run / test)
206
+ ├── tokens.py # Kriptografik Challenge-Response token üretimi & doğrulaması
207
+ ├── live_attacker.py # Saldırı simülatörü
208
+ └── static/ # Gömülü arayüz ve JS SDK
209
+ ├── index.html
210
+ └── synapse-sdk.js
211
+ ```
212
+
213
+ ---
214
+
215
+ ## 📜 License
216
+
217
+ Distributed under the MIT License. Free for both commercial and personal use.
@@ -0,0 +1,201 @@
1
+ <div align="center">
2
+
3
+ # 🛡️ SYNAPSE SHIELD
4
+
5
+ ### Next-Gen Open-Source Behavioral Biometrics & Bot Mitigation Engine
6
+
7
+ **A privacy-first, zero-friction, self-hosted alternative to Cloudflare Turnstile.**
8
+
9
+ [![License: MIT](https://img.shields.io/badge/License-MIT-00F0FF.svg)](https://opensource.org/licenses/MIT)
10
+ [![FastAPI](https://img.shields.io/badge/FastAPI-0.110+-009688.svg?logo=fastapi)](https://fastapi.tiangolo.com)
11
+ [![Python 3.12](https://img.shields.io/badge/Python-3.12-blue.svg?logo=python)](https://python.org)
12
+ [![Inference SLA](https://img.shields.io/badge/Latency-%3C0.5ms-10B981.svg)]()
13
+ [![Zero-PII](https://img.shields.io/badge/Privacy-100%25%20Zero--PII-success.svg)]()
14
+
15
+ [Features](#-key-features) • [Architecture](#-architecture) • [Quickstart](#-30-second-quickstart) • [Developer Guide](#-developer-integration) • [Benchmarks](#-attack-simulation-benchmarks)
16
+
17
+ </div>
18
+
19
+ ---
20
+
21
+ ## ⚡ Overview
22
+
23
+ **Synapse Shield** replaces intrusive legacy CAPTCHAs and proprietary cloud WAFs with **sub-millisecond behavioral biomechanics & cryptographic challenges**.
24
+
25
+ By evaluating natural human neuromuscular micro-tremors (**Jerk: $da/dt$**), cursor trajectory curvature, Fitts's Law validation (terminal deceleration profiles), and millisecond keystroke intervals, Synapse Shield autonomously classifies and mitigates bots, scrapers, and credential stuffers before they touch your backend logic.
26
+
27
+ ---
28
+
29
+ ## ✨ Key Features
30
+
31
+ - **🧩 100% Invisible & Friction-Free UX:** Zero annoying puzzle solving, image selecting, or audio challenges. Genuine human users pass instantly.
32
+ - **🔑 Cryptographic Challenge-Response:** Native protection against telemetry replay attacks. Clients fetch a single-use token from `/api/challenge` and sign their telemetry payload.
33
+ - **📈 Fitts's Law Deceleration Profiling:** Evaluates mouse deceleration as it approaches targets/clicks (`terminal_decel_ratio`) and checks velocity asymmetry (`velocity_skewness`) to detect mechanical bot paths.
34
+ - **⚡ Ultra-Low Latency (<0.5 ms):** Evaluated locally in-memory using lightweight NumPy & mathematical kinematic scoring.
35
+ - **🔒 100% Zero-PII & Privacy-First:** No keystroke characters, form inputs, or personally identifiable information are captured. Only relative millisecond delta timestamps are processed (GDPR / KVKK compliant).
36
+ - **💸 $0 Cloud Costs (Self-Hostable):** Zero third-party cloud lock-in. Run anywhere with a single packages command.
37
+ - **📊 Poisson Flooder Detection:** Catches high-frequency headless API scrapers lacking mouse telemetry using cumulative Poisson anomaly distributions.
38
+ - **🎮 Interactive 3D Security Lab:** Built-in Three.js & WebGL visual dashboard with real-time SQLite audit trails and live telemetry gauges.
39
+
40
+ ---
41
+
42
+ ## 🏛️ Architecture
43
+
44
+ ```
45
+ [ CLIENT BROWSER ]
46
+
47
+ ├── (1) GET /api/challenge ──► (Generates single-use Cryptographic Token)
48
+
49
+ ├── (2) Capture 50 Hz Biometric Telemetry (Mouse, Touch, Key Timestamps)
50
+
51
+ ▼ [Signed Telemetry Payload (Telemetry + Token)]
52
+ [ FASTAPI INGRESS GATEWAY ]
53
+
54
+ ├── (3) Token verification & Replay Attack check
55
+
56
+ ├── (4) Kinematic Feature Extraction (19D Physical Vector)
57
+ │ [Jerk: da/dt, Deceleration Ratio, Velocity Skewness, Straightness]
58
+
59
+ [ REAL-TIME DECISION ENGINE (<0.5 ms) ]
60
+
61
+ ├────────────────────────┬────────────────────────┐
62
+ ▼ ▼ ▼
63
+ [ RISK < 50% ] [ 50% ≤ RISK < 70% ] [ RISK ≥ 70% ]
64
+ Clean Human Suspicious Traffic Automated Bot
65
+ │ │ │
66
+ ▼ ▼ ▼
67
+ [ ALLOW 200 ] [ CHALLENGE / POW ] [ BLOCK 403 ]
68
+ (Seamless Pass) (Dynamic Challenge) (Access Denied)
69
+ ```
70
+
71
+ ---
72
+
73
+ ## 🚀 30-Second Quickstart
74
+
75
+ ### Installing the Command Line Tool
76
+
77
+ Since Synapse Shield is built as a pyproject.toml package, you can run CLI commands directly:
78
+
79
+ ```bash
80
+ # 1. Install dependencies
81
+ pip install -r requirements.txt
82
+
83
+ # 2. Run the Synapse Shield server (with Hot-Reload dynamic auto-reload enabled)
84
+
85
+ synapse-shield run --host 0.0.0.0 --port 8000
86
+
87
+ ````
88
+
89
+ Visit http://127.0.0.1:8000 in your browser to launch the Security Lab Cockpit dashboard.
90
+
91
+ ### Running the Simulation Suite
92
+
93
+ To run the automated adversarial Red Team simulation suite showing Fitts's Law violations and Replay Attack mitigations:
94
+
95
+ ```bash
96
+ synapse-shield test
97
+ ````
98
+
99
+ ---
100
+
101
+ ## 💻 Developer Integration
102
+
103
+ ### 1. Backend Protection (FastAPI Decorator)
104
+
105
+ Protect any API endpoint or login route using the `@shield_protect` decorator:
106
+
107
+ ```python
108
+ from fastapi import FastAPI, Request
109
+ from synapse_shield.middleware import shield_protect
110
+
111
+ app = FastAPI()
112
+
113
+ @app.post("/api/login")
114
+ @shield_protect(max_risk_score=50.0)
115
+ async def login(request: Request):
116
+ # This code only executes if Synapse Shield verifies the request as Human
117
+ return {"status": "success", "message": "Authenticated successfully"}
118
+ ```
119
+
120
+ ### 2. Frontend Integration (Vanilla JS Sync)
121
+
122
+ Include the SDK (<5 KB) and wrap your sensitive form submission:
123
+
124
+ ```html
125
+ <!-- Include SDK -->
126
+ <script src="http://your-server:8000/static/synapse-sdk.js"></script>
127
+
128
+ <script>
129
+ // Initialize biometric listener
130
+ SynapseShield.init();
131
+
132
+ async function handleLogin() {
133
+ // Automatically retrieves challenge, packages telemetry, and submits to verification endpoint
134
+ const response = await SynapseShield.submit("/api/score");
135
+ console.log("Evaluation Result:", response);
136
+ }
137
+ </script>
138
+ ```
139
+
140
+ ---
141
+
142
+ ## 🤖 Attack Simulation Benchmarks
143
+
144
+ Synapse Shield includes an automated adversarial test suite simulating 7 distinct attack vectors:
145
+
146
+ | Test Scenario | Attack Signature | Detection Mechanism | Decision | Risk Score |
147
+ | :--------------------- | :---------------------------------------- | :---------------------------------------- | :-------- | :--------- |
148
+ | **Natural Human** | Organic curves with tremors | Biological Jerk & Deceleration verified | **ALLOW** | <10.0% |
149
+ | **Linear Bot** | Selenium straight-line cursor | $\text{Straightness} = 1.000$ & Zero Jerk | **BLOCK** | 98.5% |
150
+ | **Replay Attacker** | Reuse of valid telemetry signature | Cryptographic Token Reused / Stale | **BLOCK** | 100.0% |
151
+ | **Fitts Violator Bot** | Direct speed click - no terminal slowdown | `terminal_decel_ratio > 0.85` | **BLOCK** | 80.0% |
152
+ | **Poisson Flooder** | 8 rapid requests in $<500\text{ ms}$ | Poisson frequency anomaly ($P > 95\%$) | **BLOCK** | 85.0% |
153
+ | **Selenium Webdriver** | Automated headless crawler | `navigator.webdriver = true` | **BLOCK** | 100.0% |
154
+ | **Robotic Auto-Typer** | Constant 50ms keystrokes | $\text{Key Variance} < 1.0\text{ ms}^2$ | **BLOCK** | 92.0% |
155
+
156
+ ---
157
+
158
+ ## 🧠 Kinematic & Mathematical Foundation
159
+
160
+ Synapse Shield extracts physical motion vectors derived from classical biomechanics:
161
+
162
+ **1. Jerk (Acceleration Derivative):**
163
+ $$\text{Jerk} = \frac{da}{dt} = \frac{d^3x}{dt^3}$$
164
+ Human neuromuscular micro-tremors produce continuous high-frequency Jerk, whereas mathematical bot curves (Bézier/Linear) produce near-zero or static Jerk.
165
+
166
+ **2. Fitts's Target Deceleration Profile:**
167
+ $$\text{Terminal Decel Ratio} = \frac{\bar{v}_{\text{terminal}}}{v_{\text{max}}}$$
168
+ Humans reflexively slow down when approaching a target click button ($\text{Terminal Decel Ratio} < 0.40$), whereas simple click bots maintain monotonic high speeds during clicks.
169
+
170
+ **3. Poisson Request Rate Anomaly:**
171
+ $$P(X \ge k) = 1 - \sum_{i=0}^{k-1} \frac{\lambda^i e^{-\lambda}}{i!}$$
172
+
173
+ ---
174
+
175
+ ## 📁 Repository Structure
176
+
177
+ ```
178
+ Synapse_Shield/
179
+ ├── pyproject.toml # PyPI Paket Tanımı & Yapılandırması
180
+ ├── README.md # Proje dokümantasyonu
181
+ ├── LICENSE # MIT Lisans dosyası
182
+ ├── requirements.txt # Gerekli kütüphaneler listesi
183
+ └── src/
184
+ └── synapse_shield/ # Asıl Kütüphane Paketi
185
+ ├── __init__.py # Dışa aktarılan API (shield_protect, SynapseEngine)
186
+ ├── engine.py # Karar motoru
187
+ ├── features.py # Kinematik matematik modülü
188
+ ├── middleware.py # FastAPI dekoratörü
189
+ ├── cli.py # Terminal komutu (synapse-shield run / test)
190
+ ├── tokens.py # Kriptografik Challenge-Response token üretimi & doğrulaması
191
+ ├── live_attacker.py # Saldırı simülatörü
192
+ └── static/ # Gömülü arayüz ve JS SDK
193
+ ├── index.html
194
+ └── synapse-sdk.js
195
+ ```
196
+
197
+ ---
198
+
199
+ ## 📜 License
200
+
201
+ Distributed under the MIT License. Free for both commercial and personal use.
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "synapse-shield"
7
+ version = "0.1.0"
8
+ description = "FastAPI Behavioral Bot Detection Engine & Middleware"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = {text = "MIT"}
12
+ classifiers = [
13
+ "Programming Language :: Python :: 3",
14
+ "License :: OSI Approved :: MIT License",
15
+ "Operating System :: OS Independent",
16
+ ]
17
+ dependencies = [
18
+ "fastapi>=0.110.0",
19
+ "uvicorn>=0.28.0",
20
+ "python-multipart>=0.0.9",
21
+ ]
22
+
23
+ [project.scripts]
24
+ synapse-shield = "synapse_shield.cli:main"
25
+
26
+ [tool.setuptools]
27
+ package-dir = {"" = "src"}
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["src"]
31
+
32
+ [tool.setuptools.package-data]
33
+ synapse_shield = ["static/*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,4 @@
1
+ from .middleware import shield_protect
2
+ from .engine import SynapseEngine, analyze_behavior
3
+
4
+ __all__ = ["shield_protect", "SynapseEngine", "analyze_behavior"]
@@ -0,0 +1,32 @@
1
+ """
2
+ Synapse Shield CLI Runner
3
+ """
4
+
5
+ import argparse
6
+ import uvicorn
7
+
8
+ def main():
9
+ parser = argparse.ArgumentParser(description="Synapse Shield - CLI Controller")
10
+ subparsers = parser.add_subparsers(dest="command", help="Available commands")
11
+
12
+ # Run Server Command
13
+ run_parser = subparsers.add_parser("run", help="Start the Synapse Shield server and cockpit")
14
+ run_parser.add_argument("--host", default="0.0.0.0", help="Host address (default: 0.0.0.0)")
15
+ run_parser.add_argument("--port", type=int, default=8000, help="Port number (default: 8000)")
16
+
17
+ # Run Tests Command
18
+ subparsers.add_parser("test", help="Run the 7-vector Red Team bot attack simulator")
19
+
20
+ args = parser.parse_args()
21
+
22
+ if args.command == "run" or args.command is None:
23
+ port = getattr(args, "port", 8000)
24
+ host = getattr(args, "host", "0.0.0.0")
25
+ print(f"🛡️ Starting Synapse Shield on http://{host}:{port} ...")
26
+ uvicorn.run("synapse_shield.main:app", host=host, port=port, reload=True)
27
+ elif args.command == "test":
28
+ from .live_attacker import main as run_attack_suite
29
+ run_attack_suite()
30
+
31
+ if __name__ == "__main__":
32
+ main()
@@ -0,0 +1,109 @@
1
+ import math
2
+ from typing import Dict, Any, List, Tuple
3
+ from .features import extract_features
4
+
5
+ def poisson_anomaly_score(k: int, lambda_val: float = 2.0) -> float:
6
+ if k <= 1:
7
+ return 0.0
8
+ cumulative_prob = 0.0
9
+ for i in range(k):
10
+ try:
11
+ term = (math.pow(lambda_val, i) * math.exp(-lambda_val)) / math.factorial(i)
12
+ cumulative_prob += term
13
+ except (OverflowError, ValueError):
14
+ break
15
+ return min(1.0, max(0.0, cumulative_prob))
16
+
17
+ def analyze_behavior(telemetry: Dict[str, Any], recent_request_count: int = 1) -> Tuple[float, str, List[str], Dict[str, Any]]:
18
+ features = extract_features(telemetry)
19
+ reasons = []
20
+ total_risk = 0.0
21
+
22
+ # 1. Webdriver Tespiti (Hard Block)
23
+ if features["webdriver"]:
24
+ total_risk += 100.0
25
+ reasons.append("Automation tool interface (navigator.webdriver) detected.")
26
+
27
+ # 2. Ekran Boyutları (Headless)
28
+ if not features["screen_valid"]:
29
+ total_risk += 35.0
30
+ reasons.append("Invalid or headless screen dimensions detected.")
31
+
32
+ # 3. Faresiz Form Etkileşimi
33
+ if (features["click_count"] > 0 or features["key_count"] > 0) and features["mouse_points"] == 0:
34
+ total_risk += 50.0
35
+ reasons.append("Interactive events occurred without mouse movement telemetry.")
36
+
37
+ # 4. Kinematik & Fitts Kanunu Analizi
38
+ if features["mouse_points"] > 5:
39
+ # A. Doğrusallık (Düz Çizgi Botları)
40
+ if features["total_distance"] > 30 and features["straightness"] > 0.985:
41
+ total_risk += 75.0
42
+ reasons.append(f"Euclidean straight-line trajectory detected (straightness: {features['straightness']:.4f}).")
43
+
44
+ # B. Robotik Hız & İvme Varyansı
45
+ if features["total_distance"] > 30 and features["velocity_var"] < 0.0001:
46
+ total_risk += 65.0
47
+ reasons.append("Near-zero velocity variance observed in mouse path.")
48
+
49
+ if features["total_distance"] > 30 and features["acceleration_var"] < 0.0001:
50
+ total_risk += 65.0
51
+ reasons.append("Near-zero acceleration variance observed in mouse path.")
52
+
53
+ # C. FITTS KANUNU KONTROLÜ (Hedefe Yaklaşırken Yavaşlamayan Botlar)
54
+ # İnsan bir hedefe/tıklamaya yaklaşırken hızını en az %60 düşürür (terminal_decel_ratio < 0.40)
55
+ if features["click_count"] > 0 and features["total_distance"] > 50:
56
+ if features["terminal_decel_ratio"] > 0.85:
57
+ total_risk += 45.0
58
+ reasons.append(f"Fitts's Law violation: Zero terminal deceleration before click ({features['terminal_decel_ratio']:.2f}).")
59
+
60
+ # D. İnsanüstü Hız
61
+ if features["max_velocity"] > 15.0:
62
+ total_risk += 40.0
63
+ reasons.append(f"Superhuman mouse velocity (max: {features['max_velocity']:.2f} px/ms).")
64
+
65
+ # 5. Klavye Dinamikleri
66
+ if features["key_count"] > 3:
67
+ if features["key_interval_var"] < 4.0:
68
+ total_risk += 60.0
69
+ reasons.append(f"Highly rhythmic typing pattern detected (variance: {features['key_interval_var']:.2f} ms²).")
70
+
71
+ if features["key_interval_avg"] < 25.0:
72
+ total_risk += 50.0
73
+ reasons.append(f"Superhuman input frequency (avg typing interval: {features['key_interval_avg']:.1f} ms).")
74
+
75
+ # 6. Poisson Frekans Analizi & Biyometrik Füzyon
76
+ freq_anomaly = poisson_anomaly_score(recent_request_count, lambda_val=2.0)
77
+ if freq_anomaly >= 0.95:
78
+ is_human_telemetry = (
79
+ features["mouse_points"] > 5
80
+ and features["straightness"] < 0.96
81
+ and (features["velocity_var"] > 0.001 or features["avg_jerk"] > 0.0001)
82
+ )
83
+ if is_human_telemetry:
84
+ total_risk += 25.0 * freq_anomaly
85
+ reasons.append(f"High request frequency ({recent_request_count} req/10s), but organic human kinematics verified.")
86
+ else:
87
+ total_risk += 60.0 * freq_anomaly
88
+ reasons.append(f"Poisson request frequency anomaly (rate: {recent_request_count} req/10s, risk confidence: {freq_anomaly*100:.1f}%).")
89
+
90
+ bot_score = min(100.0, total_risk)
91
+ classification = "Bot" if bot_score >= 50.0 else "Human"
92
+
93
+ if bot_score < 10.0:
94
+ reasons.append("Natural behavioral telemetry flags verified.")
95
+
96
+ details = {
97
+ "features": features,
98
+ "recent_request_count": recent_request_count,
99
+ "poisson_anomaly_score": freq_anomaly
100
+ }
101
+
102
+ return bot_score, classification, reasons, details
103
+
104
+ class SynapseEngine:
105
+ def __init__(self, lambda_val: float = 2.0):
106
+ self.lambda_val = lambda_val
107
+
108
+ def analyze(self, telemetry: Dict[str, Any], recent_request_count: int = 1) -> Tuple[float, str, List[str], Dict[str, Any]]:
109
+ return analyze_behavior(telemetry, recent_request_count)