-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathserver.py
More file actions
1252 lines (1031 loc) · 43.2 KB
/
server.py
File metadata and controls
1252 lines (1031 loc) · 43.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
FCaptcha Server - Python/FastAPI Implementation
Run: uvicorn server:app --host 0.0.0.0 --port 3000
"""
import os
import time
import hmac
import hashlib
import base64
import json
import re
from typing import Optional, Dict, Any, List
from dataclasses import dataclass, field
from enum import Enum
from collections import defaultdict
from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from pydantic import BaseModel
# Keep in sync with server-node/package.json and client/fcaptcha.js on release.
app = FastAPI(title="FCaptcha", version="1.12.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["*"],
)
SECRET_KEY = os.getenv("FCAPTCHA_SECRET", "dev-secret-change-in-production")
# Serve the browser widget alongside the API so deployments expose a single
# origin to integrators (the implicit contract behind <serverUrl>/fcaptcha.js).
# Set FCAPTCHA_SERVE_CLIENT=false to opt out — useful when hosting the widget
# on a separate CDN / edge cache. Set FCAPTCHA_CLIENT_PATH=/abs/path/fcaptcha.js
# to override the default lookup when server-python is deployed standalone.
CLIENT_PATH = os.getenv(
"FCAPTCHA_CLIENT_PATH",
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "client", "fcaptcha.js"),
)
if os.getenv("FCAPTCHA_SERVE_CLIENT", "true").lower() != "false":
@app.get("/fcaptcha.js")
async def fcaptcha_js():
return FileResponse(CLIENT_PATH, media_type="application/javascript")
# =============================================================================
# Models
# =============================================================================
class PoWSolution(BaseModel):
challengeId: str
nonce: int
hash: str
signalsHash: Optional[str] = None
class PowTiming(BaseModel):
duration: Optional[float] = None
iterations: Optional[int] = None
difficulty: Optional[int] = None
class VerifyRequest(BaseModel):
siteKey: str
signals: Dict[str, Any]
signalsJson: Optional[str] = None
powSolution: Optional[PoWSolution] = None
powTiming: Optional[PowTiming] = None
class ScoreRequest(BaseModel):
siteKey: str
signals: Dict[str, Any]
signalsJson: Optional[str] = None
action: str = ""
powSolution: Optional[PoWSolution] = None
powTiming: Optional[PowTiming] = None
class TokenVerifyRequest(BaseModel):
token: str
secret: str
# =============================================================================
# Threat Categories
# =============================================================================
class ThreatCategory(str, Enum):
VISION_AI = "vision_ai"
HEADLESS = "headless"
AUTOMATION = "automation"
CDP = "cdp"
BOT = "bot"
CAPTCHA_FARM = "captcha_farm"
BEHAVIORAL = "behavioral"
FINGERPRINT = "fingerprint"
RATE_LIMIT = "rate_limit"
DECLARED_AI = "declared_ai"
@dataclass
class Detection:
category: ThreatCategory
score: float
confidence: float
reason: str
details: Dict[str, Any] = field(default_factory=dict)
# =============================================================================
# Rate Limiter (In-Memory - Use Redis in production)
# =============================================================================
class RateLimiter:
def __init__(self):
self.requests: Dict[str, List[float]] = defaultdict(list)
def check(self, key: str, window: int = 60, max_requests: int = 10) -> tuple[bool, int]:
now = time.time()
cutoff = now - window
self.requests[key] = [t for t in self.requests[key] if t > cutoff]
count = len(self.requests[key])
if count >= max_requests:
return True, count
self.requests[key].append(now)
return False, count + 1
class FingerprintStore:
def __init__(self):
self.fingerprints: Dict[str, Dict] = {}
self.ip_fingerprints: Dict[str, set] = defaultdict(set)
def record(self, fp: str, ip: str, site_key: str):
key = f"{site_key}:{fp}"
if key not in self.fingerprints:
self.fingerprints[key] = {"count": 0, "ips": set()}
self.fingerprints[key]["count"] += 1
self.fingerprints[key]["ips"].add(ip)
self.ip_fingerprints[ip].add(fp)
def get_ip_fp_count(self, ip: str) -> int:
return len(self.ip_fingerprints.get(ip, set()))
def get_fp_ip_count(self, fp: str, site_key: str) -> int:
key = f"{site_key}:{fp}"
return len(self.fingerprints.get(key, {}).get("ips", set()))
class PoWChallengeStore:
"""Manages PoW challenges and verifies solutions."""
def __init__(self):
self.challenges: Dict[str, Dict] = {}
self.used_solutions: set = set()
def generate(self, site_key: str, ip: str, is_datacenter: bool = False) -> Dict:
import secrets
challenge_id = secrets.token_hex(16)
nonce = secrets.token_hex(16)
now = int(time.time() * 1000)
expires_at = now + (5 * 60 * 1000) # 5 minutes
# Difficulty scaling
difficulty = 4 # Default: ~100-500ms on average hardware
if is_datacenter:
difficulty = 5 # Harder for datacenter IPs
# Check rate for this IP
rate_key = f"pow:{site_key}:{ip}"
_, count = rate_limiter.check(rate_key, 60, 20)
if count > 10:
difficulty = min(6, difficulty + 1)
prefix = f"{challenge_id}:{now}:{difficulty}"
challenge = {
"id": challenge_id,
"siteKey": site_key,
"prefix": prefix,
"difficulty": difficulty,
"timestamp": now,
"expiresAt": expires_at,
"nonce": nonce,
"ip": ip
}
# Sign the challenge
sig_data = json.dumps({
"id": challenge_id,
"siteKey": site_key,
"timestamp": now,
"expiresAt": expires_at,
"difficulty": difficulty,
"prefix": prefix
}, sort_keys=True)
sig = hmac.new(SECRET_KEY.encode(), sig_data.encode(), hashlib.sha256).hexdigest()
challenge["sig"] = sig
# Store challenge
self.challenges[challenge_id] = challenge
# Cleanup old challenges periodically
if len(self.challenges) % 10 == 0:
self._cleanup()
return {
"challengeId": challenge_id,
"prefix": prefix,
"difficulty": difficulty,
"expiresAt": expires_at,
"nonce": nonce,
"sig": sig
}
def verify(self, solution: PoWSolution, site_key: str, signals_hash: str = None) -> Dict:
if not solution or not solution.challengeId:
return {"valid": False, "reason": "no_solution"}
challenge = self.challenges.get(solution.challengeId)
if not challenge:
return {"valid": False, "reason": "challenge_not_found"}
now = int(time.time() * 1000)
if now > challenge["expiresAt"]:
del self.challenges[solution.challengeId]
return {"valid": False, "reason": "challenge_expired"}
if challenge["siteKey"] != site_key:
return {"valid": False, "reason": "site_key_mismatch"}
# Check if solution was already used
solution_key = f"{solution.challengeId}:{solution.nonce}"
if solution_key in self.used_solutions:
return {"valid": False, "reason": "solution_already_used"}
# Verify the hash (with optional signalsHash binding)
if signals_hash:
input_str = f"{challenge['prefix']}:{signals_hash}:{solution.nonce}"
else:
input_str = f"{challenge['prefix']}:{solution.nonce}"
expected_hash = hashlib.sha256(input_str.encode()).hexdigest()
if solution.hash != expected_hash:
return {"valid": False, "reason": "invalid_hash"}
# Check difficulty (hash must start with N zeros)
target = "0" * challenge["difficulty"]
if not solution.hash.startswith(target):
return {"valid": False, "reason": "insufficient_difficulty"}
# Mark solution as used
self.used_solutions.add(solution_key)
# Calculate server-side elapsed time (un-spoofable)
server_elapsed = now - challenge["timestamp"]
# Delete challenge (one-time use)
del self.challenges[solution.challengeId]
return {"valid": True, "difficulty": challenge["difficulty"], "serverElapsed": server_elapsed, "nonce": challenge.get("nonce")}
def _cleanup(self):
now = int(time.time() * 1000)
expired = [cid for cid, c in self.challenges.items() if now > c["expiresAt"]]
for cid in expired:
del self.challenges[cid]
# Clear used solutions if too many
if len(self.used_solutions) > 10000:
self.used_solutions.clear()
class TokenStore:
"""Prevents token replay attacks by tracking used tokens."""
def __init__(self):
self.used_tokens: Dict[str, float] = {} # sig -> timestamp when used
def is_used(self, sig: str) -> bool:
return sig in self.used_tokens
def mark_used(self, sig: str) -> bool:
if sig in self.used_tokens:
return False # Already used
self.used_tokens[sig] = time.time()
# Cleanup old tokens periodically (tokens expire in 5 min anyway)
if len(self.used_tokens) > 1000 and len(self.used_tokens) % 100 == 0:
cutoff = time.time() - 600 # 10 minutes
self.used_tokens = {s: t for s, t in self.used_tokens.items() if t > cutoff}
return True
rate_limiter = RateLimiter()
fingerprint_store = FingerprintStore()
pow_store = PoWChallengeStore()
token_store = TokenStore()
AUTOMATION_UA_PATTERNS = [
re.compile(p, re.I) for p in [
r'headless', r'phantomjs', r'selenium', r'webdriver',
r'puppeteer', r'playwright', r'cypress', r'nightwatch',
r'zombie', r'electron', r'chromium.*headless'
]
]
WEIGHTS = {
ThreatCategory.VISION_AI: 0.15,
ThreatCategory.HEADLESS: 0.15,
ThreatCategory.AUTOMATION: 0.08,
ThreatCategory.CDP: 0.12,
ThreatCategory.BEHAVIORAL: 0.18,
ThreatCategory.FINGERPRINT: 0.08,
ThreatCategory.RATE_LIMIT: 0.01,
ThreatCategory.BOT: 0.13,
ThreatCategory.DECLARED_AI: 0.02,
}
# =============================================================================
# Detection Functions
# =============================================================================
def get_nested(d: dict, *keys, default=None):
"""Safely get nested dict values."""
for key in keys:
if isinstance(d, dict):
d = d.get(key, default)
else:
return default
return d
def detect_vision_ai(signals: Dict) -> List[Detection]:
detections = []
b = signals.get("behavioral", {})
t = signals.get("temporal", {})
# Zero/minimal mouse movement - strong indicator of AI agent or programmatic click
# Exempt: touch users (mobile) and keyboard-only users (accessibility)
total_points = b.get("totalPoints", 0)
trajectory = b.get("trajectoryLength", 0)
approach_pts = b.get("approachPoints", 0)
touch_events = b.get("touchEvents", 0)
key_events = b.get("keyEvents", 0)
is_touch_user = touch_events >= 3
is_keyboard_user = key_events >= 2 and total_points == 0
if total_points < 5 and trajectory < 10 and not is_touch_user and not is_keyboard_user:
detections.append(Detection(
ThreatCategory.VISION_AI, 0.9, 0.85,
"No mouse movement detected before click (AI agent pattern)",
{"totalPoints": total_points, "trajectoryLength": trajectory}
))
if approach_pts == 0 and not is_touch_user and not is_keyboard_user:
detections.append(Detection(
ThreatCategory.VISION_AI, 0.7, 0.8,
"No approach trajectory to target"
))
# PoW timing
pow_data = t.get("pow", {})
if pow_data:
duration = pow_data.get("duration", 0)
iterations = pow_data.get("iterations", 0)
if iterations > 0:
expected_min = (iterations / 500000) * 1000
expected_max = (iterations / 50000) * 1000
if duration < expected_min * 0.5:
detections.append(Detection(
ThreatCategory.VISION_AI, 0.8, 0.7,
"PoW completed impossibly fast",
{"duration": duration, "expected_min": expected_min}
))
elif duration > expected_max * 3:
detections.append(Detection(
ThreatCategory.VISION_AI, 0.6, 0.5,
"PoW timing suggests external processing"
))
# Micro-tremor
micro_tremor = b.get("microTremorScore", 0.5)
if micro_tremor < 0.15:
detections.append(Detection(
ThreatCategory.VISION_AI, 0.7, 0.6,
"Mouse movement lacks natural micro-tremor",
{"microTremorScore": micro_tremor}
))
# Approach directness
approach = b.get("approachDirectness", 0.5)
if approach > 0.95:
detections.append(Detection(
ThreatCategory.VISION_AI, 0.5, 0.5,
"Mouse path to target is unnaturally direct"
))
# Click precision
precision = b.get("clickPrecision", 10)
if 0 < precision < 2:
detections.append(Detection(
ThreatCategory.VISION_AI, 0.4, 0.5,
"Click precision is unnaturally accurate"
))
# Exploration
exploration = b.get("explorationRatio", 0.3)
trajectory = b.get("trajectoryLength", 0)
if exploration < 0.05 and trajectory > 50:
detections.append(Detection(
ThreatCategory.VISION_AI, 0.4, 0.4,
"No exploratory mouse movement before click"
))
# Input-event forensics: teleport clicks and agent think-time cadence.
fcs = b.get("inputForensics")
if fcs:
teleports = fcs.get("teleportClicks", 0)
if teleports >= 1 and not is_touch_user:
detections.append(Detection(
ThreatCategory.VISION_AI, 0.7, 0.7,
f"Click injected with no pointer trajectory ({int(teleports)} teleport clicks)"
))
# Bursts of activity separated by multi-second perfect silence — the agent
# act -> screenshot -> inference loop. Low confidence (slow humans idle too);
# requires silence to dominate. Keyboard-only users are exempt.
if (not is_keyboard_user
and fcs.get("cadenceEvents", 0) >= 12
and fcs.get("cadenceSilentGaps", 0) >= 3
and fcs.get("cadenceGapCV", 0) > 2.5
and fcs.get("cadenceSilentRatio", 0) > 0.6):
detections.append(Detection(
ThreatCategory.VISION_AI, 0.6, 0.5,
"Interaction cadence matches agent act/think loop (bursts + dead air)"
))
return detections
def detect_headless(signals: Dict, user_agent: str) -> List[Detection]:
detections = []
env = signals.get("environmental", {})
headless = env.get("headlessIndicators", {})
automation = env.get("automationFlags", {})
# WebDriver
if env.get("webdriver"):
detections.append(Detection(
ThreatCategory.HEADLESS, 0.95, 0.95,
"WebDriver detected (navigator.webdriver = true)"
))
# Automation flags
if automation:
if automation.get("plugins", 1) == 0:
detections.append(Detection(
ThreatCategory.HEADLESS, 0.6, 0.6,
"No browser plugins detected"
))
if not automation.get("languages"):
detections.append(Detection(
ThreatCategory.HEADLESS, 0.5, 0.5,
"No navigator.languages"
))
# Headless indicators
if headless:
if not headless.get("hasOuterDimensions"):
detections.append(Detection(
ThreatCategory.HEADLESS, 0.7, 0.7,
"Window lacks outer dimensions"
))
if headless.get("innerEqualsOuter"):
detections.append(Detection(
ThreatCategory.HEADLESS, 0.4, 0.5,
"Viewport equals window size"
))
if headless.get("notificationPermission") == "denied":
detections.append(Detection(
ThreatCategory.HEADLESS, 0.3, 0.4,
"Notifications pre-denied"
))
# User-Agent patterns
for pattern in AUTOMATION_UA_PATTERNS:
if pattern.search(user_agent):
detections.append(Detection(
ThreatCategory.HEADLESS, 0.9, 0.9,
"Automation pattern in User-Agent"
))
break
# WebGL renderer
webgl = env.get("webglInfo", {})
renderer = (webgl.get("renderer") or "").lower()
if "swiftshader" in renderer or "llvmpipe" in renderer:
detections.append(Detection(
ThreatCategory.HEADLESS, 0.8, 0.8,
"Software WebGL renderer detected"
))
# Playwright-specific detection
playwright = env.get("playwright", {})
if playwright.get("detected"):
score_map = {
"playwright_globals": 0.95,
"webdriver_deleted": 0.8,
"webdriver_configurable": 0.7,
"chrome_runtime_missing": 0.6,
}
for sig in playwright.get("signals", []):
sig_score = score_map.get(sig, 0.7)
detections.append(Detection(
ThreatCategory.HEADLESS, sig_score, 0.8,
f"Playwright artifact detected: {sig}"
))
return detections
def detect_automation(signals: Dict) -> List[Detection]:
detections = []
env = signals.get("environmental", {})
b = signals.get("behavioral", {})
# JS execution timing
js_time = get_nested(env, "jsExecutionTime", "mathOps", default=0)
if js_time > 0:
if js_time < 0.1:
detections.append(Detection(
ThreatCategory.AUTOMATION, 0.4, 0.3,
"JS execution unusually fast"
))
elif js_time > 50:
detections.append(Detection(
ThreatCategory.AUTOMATION, 0.3, 0.3,
"JS execution unusually slow"
))
# RAF consistency
raf = env.get("rafConsistency", {})
if raf and raf.get("frameTimeVariance", 1) < 0.1:
detections.append(Detection(
ThreatCategory.AUTOMATION, 0.5, 0.4,
"RequestAnimationFrame timing too consistent"
))
# Event timing
event_var = b.get("eventDeltaVariance", 10)
total_points = b.get("totalPoints", 0)
if event_var < 2 and total_points > 10:
detections.append(Detection(
ThreatCategory.AUTOMATION, 0.6, 0.6,
"Mouse event timing unnaturally consistent"
))
return detections
def detect_cdp(signals: Dict) -> List[Detection]:
"""Detect Chrome DevTools Protocol (CDP) automation artifacts."""
detections = []
env = signals.get("environmental", {})
cdp = env.get("cdp", {})
# Input-event forensics: catch CDP-injected input that reports isTrusted=true
# and so evades the global-based checks below. Touch users are exempt.
b = signals.get("behavioral", {})
is_touch_user = b.get("touchEvents", 0) >= 3
fcs = b.get("inputForensics")
if fcs and not is_touch_user:
# Real mice coalesce several hardware samples per frame; a stream of
# pointermoves that NEVER coalesced is synthetic injection.
if fcs.get("coalescedSamples", 0) >= 20 and fcs.get("coalescedMax", 0) <= 1:
detections.append(Detection(
ThreatCategory.CDP, 0.8, 0.6,
"Pointer moves never coalesced across many samples (synthetic/CDP input)"
))
# movementX/Y incoherent with actual position deltas across most moves.
if fcs.get("pointerMoveSamples", 0) >= 20 and fcs.get("pointerMoveZeroRatio", 0) > 0.9:
detections.append(Detection(
ThreatCategory.CDP, 0.6, 0.5,
"Pointer movement deltas incoherent with position (synthetic input)"
))
# CDP Runtime/DevTools console consumer attached. Low confidence: a developer
# with DevTools open also trips this, so it contributes rather than blocks.
if env.get("cdpRuntime", {}).get("consoleAttached"):
detections.append(Detection(
ThreatCategory.CDP, 0.6, 0.5,
"CDP/DevTools console consumer attached (automation protocol or open DevTools)"
))
if not cdp.get("detected"):
return detections
signal_list = cdp.get("signals", [])
signal_count = len(signal_list)
if signal_count == 0:
return detections
# High-confidence signals
high_conf_signals = ['chromedriver_cdc', 'puppeteer_eval', 'cdp_script_injection']
has_high_conf = any(s in high_conf_signals for s in signal_list)
signals_joined = ', '.join(signal_list)
if has_high_conf:
detections.append(Detection(
ThreatCategory.CDP, 0.9, 0.95,
f"CDP automation detected: {signals_joined}"
))
elif signal_count >= 2:
detections.append(Detection(
ThreatCategory.CDP, 0.8, 0.85,
f"Multiple CDP indicators: {signals_joined}"
))
else:
detections.append(Detection(
ThreatCategory.CDP, 0.6, 0.7,
f"CDP indicator: {signals_joined}"
))
return detections
def detect_behavioral(signals: Dict) -> List[Detection]:
detections = []
b = signals.get("behavioral", {})
t = signals.get("temporal", {})
# Insufficient mouse data - critical check for zero-click bots
# Exempt: touch users (mobile) and keyboard-only users (accessibility)
total_points = b.get("totalPoints", 0)
trajectory = b.get("trajectoryLength", 0)
touch_events = b.get("touchEvents", 0)
key_events = b.get("keyEvents", 0)
is_touch_user = touch_events >= 3
is_keyboard_user = key_events >= 2 and total_points == 0
if total_points == 0 and not is_touch_user and not is_keyboard_user:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.8, 0.9,
"Zero mouse, touch, or keyboard events recorded"
))
elif total_points < 10 and not is_touch_user and not is_keyboard_user and trajectory < 30:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.6, 0.7,
"Insufficient mouse movement before interaction",
{"totalPoints": total_points, "trajectoryLength": trajectory}
))
# Velocity variance
vel_var = b.get("velocityVariance", 1)
if vel_var < 0.02 and trajectory > 50:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.6, 0.6,
"Mouse velocity too consistent"
))
# Overshoot
overshoots = b.get("overshootCorrections", 0)
if overshoots == 0 and trajectory > 200:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.4, 0.4,
"No overshoot corrections on long trajectory"
))
# Interaction speed
interaction_time = b.get("interactionDuration", 1000)
if 0 < interaction_time < 200:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.7, 0.7,
"Interaction completed too quickly"
))
elif interaction_time > 60000:
detections.append(Detection(
ThreatCategory.CAPTCHA_FARM, 0.3, 0.3,
"Unusually long interaction time"
))
# First interaction timing
first_int = t.get("pageLoadToFirstInteraction")
if first_int is not None and 0 < first_int < 100:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.5, 0.5,
"First interaction too soon after page load"
))
# Mouse event rate
event_rate = b.get("mouseEventRate", 60)
if event_rate > 200:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.6, 0.5,
"Mouse event rate abnormally high"
))
elif 0 < event_rate < 10:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.4, 0.4,
"Mouse event rate abnormally low"
))
# Straight line ratio
straight = b.get("straightLineRatio", 0)
if straight > 0.8 and trajectory > 100:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.5, 0.5,
"Mouse movements too straight"
))
# Direction changes
dir_changes = b.get("directionChanges", 10)
total_points = b.get("totalPoints", 0)
if total_points > 50 and dir_changes < 3:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.4, 0.4,
"Too few direction changes"
))
return detections
# =============================================================================
# Mobile-native detectors (touch authenticity, sensor entropy, touch kinematics)
# UA-gated on mobile. Non-mobile UAs: no-op. Designed never to penalize iOS
# Safari without DeviceMotion permission (absence treated as neutral).
# =============================================================================
_MOBILE_UA_PATTERN = re.compile(r"mobile|android|iphone|ipad|ipod", re.IGNORECASE)
def _is_mobile_ua(user_agent: str) -> bool:
return bool(_MOBILE_UA_PATTERN.search(user_agent or ""))
def detect_touch_authenticity(signals: Dict, user_agent: str) -> List[Detection]:
detections: List[Detection] = []
if not _is_mobile_ua(user_agent):
return detections
b = signals.get("behavioral", {}) or {}
touch_points = b.get("touchTotalPoints") or b.get("touchEvents") or 0
if touch_points < 3:
return detections
force_variance = b.get("touchForceVariance", 0) or 0
radius_variance = b.get("touchRadiusVariance", 0) or 0
force_all_one = b.get("touchForceAllOne") is True
unique_ids = b.get("touchUniqueIdentifiers", 0) or 0
force_max = b.get("touchForceMax", 0) or 0
radius_max = b.get("touchRadiusMax", 0) or 0
# Uniform non-zero force across all events → synthetic injection.
# Older Android returning all-zero is legitimate — only penalize uniformity
# when max > 0.
if force_variance == 0 and force_max > 0 and touch_points >= 5:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.75, 0.85,
"Touch force is identical across all events (synthetic touch)"
))
if force_all_one and touch_points >= 5:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.8, 0.9,
"All touches report force=1.0 exactly (synthetic pattern)"
))
if radius_variance == 0 and radius_max > 0 and touch_points >= 5:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.7, 0.8,
"Touch contact radius identical across all events"
))
if touch_points >= 5 and unique_ids == 0:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.6, 0.7,
"Mobile touches lack identifier tracking (synthetic injection)"
))
return detections
def detect_sensor_entropy(signals: Dict, user_agent: str) -> List[Detection]:
detections: List[Detection] = []
if not _is_mobile_ua(user_agent):
return detections
env = signals.get("environmental", {}) or {}
sensor = env.get("sensor", {}) or {}
motion_count = sensor.get("motionEventCount", 0) or 0
motion_variance = sensor.get("motionAccelVariance", 0) or 0
orientation_count = sensor.get("orientationEventCount", 0) or 0
orientation_variance = sensor.get("orientationVariance", 0) or 0
if motion_count >= 10 and motion_variance < 0.01:
detections.append(Detection(
ThreatCategory.HEADLESS, 0.7, 0.8,
f"Motion sensor active but flat (variance={motion_variance:.4f}) — likely emulator"
))
if orientation_count >= 10 and orientation_variance < 0.01:
detections.append(Detection(
ThreatCategory.HEADLESS, 0.6, 0.7,
"Orientation sensor active but completely flat — likely emulator"
))
# motion_count == 0 is NEUTRAL (iOS without permission is common).
return detections
def detect_touch_kinematics(signals: Dict) -> List[Detection]:
detections: List[Detection] = []
b = signals.get("behavioral", {}) or {}
touch_points = b.get("touchTotalPoints", 0) or 0
if touch_points < 10:
return detections
straight_line = b.get("touchStraightLineRatio", 0) or 0
tremor = b.get("touchMicroTremorScore", 0) or 0
dir_changes = b.get("touchDirectionChanges", 0) or 0
if straight_line > 0.85 and touch_points >= 20:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.65, 0.75,
f"Touch path too straight (ratio={straight_line:.2f}) — automation pattern"
))
if tremor < 0.05 and touch_points >= 30:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.55, 0.65,
"Touch path has no micro-tremor (unnaturally smooth)"
))
if dir_changes == 0 and touch_points >= 30:
detections.append(Detection(
ThreatCategory.BEHAVIORAL, 0.5, 0.6,
"Touch path has zero direction changes over long trajectory"
))
return detections
def detect_fingerprint(signals: Dict, ip: str, site_key: str) -> List[Detection]:
detections = []
env = signals.get("environmental", {})
automation = env.get("automationFlags", {})
# Generate fingerprint
components = [
str(get_nested(env, "canvasHash", "hash", default="")),
str(get_nested(env, "webglInfo", "renderer", default="")),
str(automation.get("platform", "")),
str(automation.get("hardwareConcurrency", ""))
]
fp = hashlib.sha256("|".join(components).encode()).hexdigest()[:16]
fingerprint_store.record(fp, ip, site_key)
# IP fingerprint count
ip_fp_count = fingerprint_store.get_ip_fp_count(ip)
if ip_fp_count > 5:
detections.append(Detection(
ThreatCategory.FINGERPRINT, 0.6, 0.6,
"IP has used many different fingerprints",
{"count": ip_fp_count}
))
# Fingerprint IP count
fp_ip_count = fingerprint_store.get_fp_ip_count(fp, site_key)
if fp_ip_count > 10:
detections.append(Detection(
ThreatCategory.FINGERPRINT, 0.5, 0.5,
"Fingerprint seen from many IPs",
{"count": fp_ip_count}
))
# Canvas issues
canvas = env.get("canvasHash", {})
if canvas.get("error") or not canvas.get("supported"):
detections.append(Detection(
ThreatCategory.FINGERPRINT, 0.4, 0.4,
"Canvas fingerprinting blocked or failed"
))
return detections
def detect_rate_abuse(ip: str, site_key: str) -> List[Detection]:
detections = []
key = f"{site_key}:{ip}"
exceeded, count = rate_limiter.check(key, 60, 10)
if exceeded:
detections.append(Detection(
ThreatCategory.RATE_LIMIT, 0.8, 0.9,
"Rate limit exceeded",
{"count": count}
))
elif count > 5:
detections.append(Detection(
ThreatCategory.RATE_LIMIT, 0.3, 0.5,
"High request rate",
{"count": count}
))
return detections
# =============================================================================
# Scoring
# =============================================================================
def calculate_category_scores(detections: List[Detection]) -> Dict[str, float]:
category_data: Dict[ThreatCategory, List[tuple]] = defaultdict(list)
for d in detections:
category_data[d.category].append((d.score, d.confidence))
result = {}
for cat, scores in category_data.items():
if scores:
total_weight = sum(conf for _, conf in scores)
if total_weight > 0:
weighted_sum = sum(score * conf for score, conf in scores)
result[cat.value] = min(1.0, weighted_sum / total_weight)
# Fill missing
for cat in ThreatCategory:
if cat.value not in result:
result[cat.value] = 0.0
return result
def calculate_final_score(category_scores: Dict[str, float]) -> float:
total = 0.0
for cat, weight in WEIGHTS.items():
total += category_scores.get(cat.value, 0.0) * weight
return min(1.0, total)
def generate_token(ip: str, site_key: str, score: float) -> str:
ip_hash = hashlib.sha256(ip.encode()).hexdigest()[:8]
data = {
"site_key": site_key,
"timestamp": int(time.time()),
"score": round(score, 3),
"ip_hash": ip_hash
}
payload = json.dumps(data, sort_keys=True)
sig = hmac.new(SECRET_KEY.encode(), payload.encode(), hashlib.sha256).hexdigest()
data["sig"] = sig
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
def verify_token(token: str, ip: str = None) -> Dict:
try:
decoded = json.loads(base64.urlsafe_b64decode(token).decode())
# Check expiration
if time.time() - decoded.get("timestamp", 0) > 300:
return {"valid": False, "reason": "expired"}
sig = decoded.pop("sig", "")
ip_hash = decoded.get("ip_hash", "")
payload = json.dumps(decoded, sort_keys=True)
expected_sig = hmac.new(SECRET_KEY.encode(), payload.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(sig, expected_sig):
return {"valid": False, "reason": "invalid_signature"}
# Check for token replay (single-use tokens)
if token_store.is_used(sig):
return {"valid": False, "reason": "token_already_used"}
# Verify IP matches (if provided)
if ip:
expected_ip_hash = hashlib.sha256(ip.encode()).hexdigest()[:8]
if ip_hash != expected_ip_hash:
return {"valid": False, "reason": "ip_mismatch"}
# Mark token as used (prevents replay)
token_store.mark_used(sig)
return {
"valid": True,
"site_key": decoded.get("site_key"),
"timestamp": decoded.get("timestamp"),
"score": decoded.get("score"),
"ip_hash": ip_hash