🛡️ SYNAPSE SHIELD
Next-Gen Open-Source Behavioral Biometrics & Bot Mitigation Engine
A privacy-first, zero-friction, self-hosted alternative to Cloudflare Turnstile.
Key Features • Architecture • Quickstart • Developer Guide • Benchmarks • Math
⚡ Overview
Synapse Shield replaces intrusive legacy CAPTCHAs and expensive proprietary cloud WAFs with sub-millisecond behavioral biomechanics.
By evaluating natural human neuromuscular micro-tremors (Jerk: $\frac{da}{dt}$), Fitts's Law terminal deceleration profiles, cursor curvature, and millisecond keystroke dynamics, Synapse Shield autonomously classifies and mitigates bots, scrapers, and credential stuffers before they touch your backend logic.
✨ Key Features & Security Architecture (v0.8.0)
| Feature | Description |
|---|---|
| ⚡ Microsecond Benchmark Suite | Built-in CLI command (synapse-shield benchmark) profiles 19D Kinematics ($73.7,\mu s$), 1D-CNN inference ($451.2,\mu s$), and end-to-end evaluation ($828.1,\mu s$, ~1,200 req/sec) with ASCII/JSON reports (v0.7.9). |
| 🧬 Biological Synthetic Human Generator | Multi-bell submovement velocity decomposition with natural valleys, biomechanical arm curvature, and inertia-filtered neuromuscular micro-tremor achieving 100% human verification accuracy (v0.7.9). |
| 🛡️ Isolated Weight & Bootstrap Architecture | Fine-tuning saves to ./synapse_weights.npz (or SYNAPSE_WEIGHTS_PATH), isolating package distribution weights. --bootstrap enables zero-data model calibration on clean installs (v0.7.9). |
| 🌊 FFT Tremor Spectral Analysis (DSP) | Fast Fourier Transform (np.fft.rfft) decomposes velocity sequences to evaluate Power Spectral Density (spectral_purity & spectral_entropy), mitigating synthetic harmonic oscillator tremors ($\sin(2\pi ft)$) in the frequency domain (v0.7.8). |
| 🖐️ Sub-Movement Kinematic Decomposition | Decomposes trajectory paths into discrete ballistic and corrective velocity pulses based on Fitts's Law. Trajectories lacking physiological sub-movements (submovement_count <= 1) are flagged as polynomial bots (v0.7.8). |
| 🔄 Session-Level Behavioral Invariance | Stateful sliding-window telemetry tracking across session requests. Mitigates attackers rotating random seeds or repeating deterministic kinetic templates (v0.7.8). |
| 🎯 Adversarial AI Retraining Pipeline | Built-in synthetic telemetry generator (synapse_shield.adversarial) enriches 1D-CNN active learning with adversarial Bézier, sinusoidal, and minimum-jerk curves, eliminating out-of-distribution blindspots (v0.7.8). |
| 🛡️ Comprehensive Security Hardening | Full remediation across all vector layers (P0-P2): Stored XSS defense, admin-authenticated WebSocket terminal, SSRF & DNS rebinding allowlist for webhooks, and gated Brave Farbling logic (v0.7.7). |
| ⚡ Sub-Millisecond Composite SQLite Index | Composite index (idx_ip_strikes_ip_ts) eliminates table scans, enabling sub-millisecond bot strike counting under high-throughput DDoS conditions (v0.7.7). |
| 🔄 Transparent Token Expiration Recovery | Clean separation of expired tokens (HTTP 400 EXPIRED) from active replay attacks, allowing the SDK to seamlessly renegotiate challenges without false-positive IP bans (v0.7.7). |
| 🧱 O(N) Keystroke DoS Defense | Queued hold-time analysis with strict input bounds (150 keys/scrolls max), neutralizing algorithmic complexity exhaustion attacks (v0.7.7). |
| 🧪 Poisoning-Resistant AI Fine-Tuning | Telemetry ingestion filters reject non-human or farbling-exempted traffic from the active learning dataset pool, preserving model classification integrity (v0.7.7). |
| 🔔 Instant Discord & Telegram Webhooks | Real-time security incident dispatch. Critical threat mitigations (BLOCK) and IP bans are automatically forwarded to configured Discord/Telegram channels via non-blocking background tasks (v0.7.6). |
| ⚡ Distributed State & Redis Cluster | Enterprise multi-server architecture (SYNAPSE_REDIS_URL). Atomic cross-worker replay protection (SET NX EX), synchronized IP quarantine, and zero-downtime SQLite fallback (v0.7.5). |
| 🧩 Dynamic Yielding Proof-of-Work | Sub-second client-side SHA-256 cryptographic puzzle with UI yielding to prevent main-thread blocking. Replay-attack resistant on retries (v0.7.2). |
| 🛡️ Iframe-based Prototype Unhooking | Advanced anti-stealth mechanism using hidden iframes to access clean native browser prototypes (Canvas, WebGL), bypassing attacker overwrites (v0.7.2). |
| 🔒 SDK Runtime Immutability | Object.freeze protects internal SDK states/configurations from malicious tampering on the host page (v0.7.2). |
| 📱 Zero-Jank Mobile Events | Passive touch listeners ({ passive: true }) ensure seamless 60 FPS mobile scrolling without blocking the UI thread (v0.7.2). |
| 🪟 Sliding Window IP Ban Shield | Stateful 60-second sliding time-window (SSRT-2026-004 defense). Prevents streak-reset evasion attacks even when attackers inject synthetic human requests. |
| 🔄 NumPy-Only Active Learning | Built-in synapse-shield retrain command enabling transfer learning on 1D-CNN FC layers in <3s directly from SQLite logs without PyTorch/TensorFlow. |
| 🕵️ Anti-Stealth & Tamper Proofing | Dynamically detects headless browser fingerprints (navigator.webdriver), fake plugin arrays, and native toString overwrites in WebGL/Canvas APIs. |
| 🗄️ Continuous Learning Collector | Integrated drop-in store.html telemetry collector endpoint (/api/collect_dataset) for continuous 1D-CNN Fine-Tuning with raw human datasets. |
| 🤖 Pure-NumPy 1D-CNN Micro-Brain | The Sequence Tokenizer fuses kinematics and keystroke stats into an 8D and 5D tensor architecture, fully processed by a 15KB NumPy-based 1D-CNN (Zero-PyTorch). |
| 🛡️ Max Gating (Fusion Engine) | Dynamically unifies Heuristic/Mathematical rules with the 1D-CNN AI confidence score. If either engine flags the telemetry as a Bot, the request is unconditionally blocked. |
| 🔗 Zero-Dependency Multimodal Tokenizer | Fuses 5D Mouse Sequence [dx, dy, dt, velocity, jerk] with 8D Static Keystroke/Scroll Vector via Late Fusion. |
| 🧩 100% Invisible UX | Zero annoying puzzles, image selections, or audio challenges. Legitimate humans pass friction-free. |
| ⚡ Async Non-Blocking SLA (<0.5 ms) | Heavy CPU-bound kinematics processed via asyncio.to_thread, guaranteeing zero event-loop blocking under high concurrency. |
| 🔐 Cryptographic Replay Defense | Every session is bound to a single-use HMAC-SHA256 signed nonce. Intercepted tokens cannot be replayed. |
| 🧠 Fitts's Law Deceleration Kinematics | Distinguishes advanced Bézier curve bots (ghost-cursor) from organic human hands by analyzing terminal velocity drops before click actions. |
| ⚛️ React, Next.js & Vue 3 / Nuxt 3 Support | Native packages (synapse-shield-react & synapse-shield-vue) with hooks/composables and <SynapseProtect /> drop-in protection components. |
| 🐍 Multi-Framework Adapters | Native middlewares and decorators for Django (SynapseShieldMiddleware) and Flask (@shield_protect_flask). |
| ♿ Accessibility Mode | Graceful risk scaling (accessibility_mode=True) prevents false positives for motor-impaired and assistive device users. |
| 📈 Enterprise Prometheus Metrics | Built-in /metrics endpoint supporting multi-process Gunicorn/Uvicorn aggregation via PROMETHEUS_MULTIPROC_DIR. |
| 🔒 100% Zero-PII & Privacy-First | No keystroke characters or form values collected — strictly relative millisecond timing deltas processed (GDPR & KVKK compliant). |
| 📊 Poisson Flooder Defense | Statistical Poisson anomaly detection identifies high-frequency headless API flooders and applies dynamic IP rate penalties. |
| 💾 SQLite WAL with Auto-Pruning | In-memory TTL nonce management + Write-Ahead Logging (WAL) with 10s timeouts prevents database locks during async BackgroundTasks. |
| 🧱 Memory Exhaustion Defense | Strict 256KB/512KB payload body limits evaluated at stream-read time (await request.body()) protecting against chunked-transfer inflation attacks. |
| 🔑 Secure Admin APIs | Administrative operations (/api/clear) are cryptographically authenticated via the SYNAPSE_ADMIN_SECRET environment variable to prevent unauthorized telemetry tampering. |
| 🚨 Zero-Latency Webhook Alerts | Instant real-time Telegram and Discord notifications upon bot detection via asyncio.to_thread without blocking the main event loop. Configurable directly from the Cockpit. |
🏛️ Architecture & Sequence Diagram
┌─────────────────┐ ┌─────────────────────┐ ┌─────────────────────────┐
│ Client Browser │ │ FastAPI Gateway │ │ Kinematic Decision │
│ (synapse-sdk) │ │ (Synapse Shield) │ │ Engine (<0.5ms SLA) │
└────────┬────────┘ └──────────┬──────────┘ └────────────┬────────────┘
│ │ │
│── 1. GET /api/challenge ───────►│ │
│◄── 2. { nonce, ts, hmac_sig } ──│ (Generates single-use signed nonce)│
│ │ │
[User moves cursor / types] │ │
[SDK bundles 50Hz telemetry] │ │
│ │ │
│── 3. POST /api/score {token} ──►│ (1. Validates HMAC signature) │
│ │ (2. Checks 60s TTL freshness) │
│ │ (3. Checks Replay Attack nonce) │
│ │ │
│ │── 4. asyncio.to_thread ────────────►│ (19D Kinematics)
│ │ │ (Jerk & Fitts's Law)
│ │ │ (Poisson Anomaly)
│ │◄── 5. (bot_score, ALLOW/BLOCK) ─────│
│ │ │
│ │── 6. Save Log to SQLite (WAL) │
│◄── 7. HTTP 200 {ALLOW/BLOCK} ───│ │
🚀 30-Second Quickstart
Option 1: Install via PyPI
pip install synapse-shield
Run the server and live cockpit directly from your terminal:
synapse-shield run --port 8000
Run the automated 7-vector adversarial security test suite:
synapse-shield test
Retrain the 1D-CNN AI model autonomously on local SQLite telemetry (Active Learning):
synapse-shield retrain --epochs 5 --lr 0.01
Option 2: Clone & Local Development
git clone https://github.com/0xStoic-bit/Synapse_Shield.git
cd Synapse_Shield
pip install -e .
python test_suite.py
Visit http://127.0.0.1:8000 in your browser to launch the Live Security Cockpit.
Option 3: Docker Deployment (Recommended)
Run the entire Synapse Shield stack, including the backend engine, SQLite WAL persistence, and the telemetry collector in a single container.
# Start the container in detached mode
docker-compose up -d
# View real-time logs
docker-compose logs -f
The Synapse API and Live Cockpit will be available at http://localhost:8000.
🚨 Real-time Webhook Alerts (Telegram & Discord)
Synapse Shield features zero-latency background webhook notifications. When a critical threat is blocked (e.g., STEALTH_AUTOMATION, POISSON_FLOOD), you receive an instant alert on your phone.
Setting up Telegram Alerts
- Open Telegram and message @BotFather with
/newbot. - Follow the steps to get your HTTP API Token (e.g.,
123456:ABC-DEF...). - Send a message like "Hello" to your newly created bot to initialize the chat.
- Message @userinfobot and press
STARTto get your Chat ID (e.g.,123456789). - Open the Synapse Shield Cockpit (
http://127.0.0.1:8000), click WEBHOOKS, and paste your Token and Chat ID.
Setting up Discord Alerts
- Go to your Discord Server settings > Integrations > Webhooks > New Webhook.
- Copy the Webhook URL.
- Open the Synapse Shield Cockpit, click WEBHOOKS, and paste the URL.
💻 Developer Integration
1. FastAPI Integration
Protect any API endpoint using the @shield_protect decorator or global middleware:
from fastapi import FastAPI, Request
from synapse_shield import shield_protect, SynapseShieldMiddleware
app = FastAPI()
app.add_middleware(SynapseShieldMiddleware, protected_paths=["/api/auth"])
@app.post("/api/login")
@shield_protect(max_risk_score=50.0, accessibility_mode=False)
async def login(request: Request):
return {"status": "authenticated"}
2. Django & Flask Integration
Native support for Django and Flask environments.
Django (settings.py):
MIDDLEWARE = [
# ...
'synapse_shield.django.SynapseShieldMiddleware',
]
SYNAPSE_SHIELD_PROTECTED_PATHS = ['/api/login']
SYNAPSE_SHIELD_MAX_RISK = 50.0
SYNAPSE_SHIELD_ACCESSIBILITY = False
Flask:
from flask import Flask
from synapse_shield.flask import shield_protect_flask
app = Flask(__name__)
@app.route("/login", methods=["POST"])
@shield_protect_flask(max_risk_score=50.0)
def login():
return {"status": "authenticated"}
3. React / Next.js Integration
We provide a drop-in "use client" compatible React package.
import { useSynapseShield, SynapseProtect } from 'synapse-shield-react';
export default function LoginForm() {
const { getProtectedPayload } = useSynapseShield();
const handleSubmit = async (e) => {
e.preventDefault();
const payload = getProtectedPayload();
// Send payload.token to your backend
};
return (
<form onSubmit={handleSubmit}>
<SynapseProtect />
<button type="submit">Login</button>
</form>
);
}
4. Vue 3 / Nuxt 3 Integration
Official Vue 3 composable and component package (synapse-shield-vue). Fully SSR-safe for Nuxt 3.
<script setup>
import { ref } from 'vue';
import { useSynapseShield, SynapseProtect } from 'synapse-shield-vue';
const { getProtectedPayload } = useSynapseShield();
const username = ref('');
const password = ref('');
const handleSubmit = async () => {
const payload = getProtectedPayload();
// Submit payload.token to backend
};
</script>
<template>
<form @submit.prevent="handleSubmit">
<SynapseProtect />
<input v-model="username" type="text" placeholder="Username" />
<input v-model="password" type="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
</template>
5. Prometheus Metrics
Enterprise observability out of the box. Automatically exposes latency and block rates. To enable multi-process support (e.g., Gunicorn workers), set the environment variable:
export PROMETHEUS_MULTIPROC_DIR=/tmp/synapse_metrics
5. Vanilla JS / HTML SDK
Add the lightweight SDK (<5 KB) to your vanilla project:
<script src="http://localhost:8000/static/synapse-sdk.js"></script>
<script>
SynapseShield.init();
async function handleLogin() {
const payload = SynapseShield.getPayload();
// Submit payload
}
</script>
🤖 Attack Simulation Benchmarks
Run the full adversarial suite anytime:
synapse-shield test
| Attack Vector | Simulated Signature | Detection Mechanism | Decision | Risk Score | Latency |
|---|---|---|---|---|---|
| Selenium Crawler | navigator.webdriver = true |
WebDriver API Detection | 🔴 BLOCK | 100.0% | 0.01 ms |
| Linear Bot | Straightness = 1.000 & Zero Jerk | Straightness > 0.985 & Jerk ~ 0 | 🔴 BLOCK | 100.0% | 0.18 ms |
| Bézier Stealth Bot | Mathematical curved trajectory | Fitts's Law + Zero Accel Variance | 🔴 BLOCK | 65.0% | 0.22 ms |
| Robotic Auto-Typer | Fixed-interval key injections | Keystroke Variance < 1.0 ms² | 🔴 BLOCK | 50.0% | 0.15 ms |
| Poisson Flooder | 8 rapid requests in <500 ms | Poisson anomaly (P > 99%) | 🔴 BLOCK | 60.0% | 0.08 ms |
| Replay Attack | Re-sending captured valid token | Single-use HMAC Nonce reuse | 🔴 BLOCK | 100.0% | 0.05 ms |
| Natural Human | Organic curves with tremors | Biologic Jerk & Deceleration | 🟢 ALLOW | 0.0% | 0.24 ms |
🧠 Kinematic & Mathematical Foundations
1. Jerk — Neuromuscular Tremor Fingerprint
$$\text{Jerk} = \frac{da}{dt} = \frac{d^3x}{dt^3}$$
Human muscle tremors produce continuous high-frequency Jerk. Mathematical bot curves (Bézier/Linear) produce near-zero or static Jerk.
2. Fitts's Law Terminal Deceleration Index
$$\text{Terminal Decel Ratio} = \frac{\bar{v}{\text{terminal (last 25%)}}}{v{\text{peak}}}$$
Humans naturally decelerate ($< 0.40$) as they approach the target click point.
3. Cumulative Poisson Anomaly Distribution
$$P(X < k) = \sum_{i=0}^{k-1} \frac{\lambda^i e^{-\lambda}}{i!}$$
📁 Repository Structure
Synapse_Shield/
├── .github/
│ └── workflows/
│ └── ci.yml # Automated CI matrix (Python 3.10, 3.11, 3.12)
├── src/
│ └── synapse_shield/
│ ├── __init__.py # Public API exports
│ ├── cli.py # CLI Controller (run / test commands)
│ ├── engine.py # Real-time Decision & Poisson Engine
│ ├── features.py # 19D Kinematics, Fitts's Law & Multimodal Tokenizer
│ ├── models.py # Zero-Dependency NumPy 1D-CNN Inference Engine
│ ├── weights.npz # 4KB Serialized Neural Network Weights
│ ├── main.py # Async FastAPI Gateway & SQLite Logger
│ ├── middleware.py # @shield_protect & Middleware classes
│ ├── django.py # Django Middleware Adapter
│ ├── flask.py # Flask Route Decorator
│ ├── metrics.py # Prometheus Multi-Process Exporter
│ ├── tokens.py # HMAC-SHA256 Challenge & Replay Defense
│ ├── train.py # Zero-Dependency NumPy Active Learning Pipeline
│ ├── live_attacker.py # 7-Vector Red Team Simulation Suite
│ └── static/ # Embedded 3D Cockpit & Client SDK
│ ├── index.html
│ └── synapse-sdk.js
├── synapse-shield-react/ # React / Next.js SDK Package
│ ├── src/
│ │ ├── SynapseProtect.tsx # "use client" Drop-in Component
│ │ ├── useSynapseShield.ts# React Hook with event throttling
│ │ └── index.ts
│ ├── package.json
│ └── tsconfig.json
├── tests/ # Modular Pytest Suite
│ ├── test_features.py
│ ├── test_tokens.py
│ ├── test_engine.py
│ └── test_api.py
├── test_suite.py # Standalone Zero-Dependency Test Runner
├── pyproject.toml # PEP 517/621 Package Definition
├── requirements.txt # Core Dependencies
├── LICENSE # MIT License
└── README.md
📜 License
Distributed under the MIT License. Free for commercial and personal use.
Release files for synapse-shield 0.8.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| synapse_shield-0.8.0.tar.gz | 106.6 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| synapse_shield-0.8.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 192.1 kB
Release files / synapse_shield-0.8.0.tar.gz
| Download URL | synapse_shield-0.8.0.tar.gz |
|---|---|
| Size | 106.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d7e97c15ec283de341ceba40f66a1ea8822107d6b28356f9b062f560343f7bfe
|
|
BLAKE2b-256 checksum How to use checksums |
1f6def6377bdf4a02e46499916713d9ab56a50040cf78fcd8b0a91770e737fd5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.10.10
|
Release files / synapse_shield-0.8.0-py3-none-any.whl
| Download URL | synapse_shield-0.8.0-py3-none-any.whl |
|---|---|
| Size | 85.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b718258f5609c1b652df889a991abd68ea0d8a001a83787f340e93664fb19483
|
|
BLAKE2b-256 checksum How to use checksums |
f52ab6d927a68f339af62bec5288526c3d4a1817b681f5dc4f4714cef6550903
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.10.10
|