@webdecoy/node 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +86 -2
- package/dist/index.d.mts +652 -1
- package/dist/index.d.ts +652 -1
- package/dist/index.js +1946 -2
- package/dist/index.mjs +1928 -1
- package/package.json +6 -2
package/dist/index.mjs
CHANGED
|
@@ -1295,11 +1295,1938 @@ function rateLimit(config) {
|
|
|
1295
1295
|
function filter(config) {
|
|
1296
1296
|
return new FilterRule(config);
|
|
1297
1297
|
}
|
|
1298
|
+
|
|
1299
|
+
// src/detection/weights.ts
|
|
1300
|
+
var DEFAULT_WEIGHTS = {
|
|
1301
|
+
vision_ai: 0.15,
|
|
1302
|
+
headless: 0.15,
|
|
1303
|
+
automation: 0.08,
|
|
1304
|
+
cdp: 0.12,
|
|
1305
|
+
behavioral: 0.18,
|
|
1306
|
+
fingerprint: 0.08,
|
|
1307
|
+
rate_limit: 0.01,
|
|
1308
|
+
datacenter: 0.07,
|
|
1309
|
+
tor_vpn: 0.01,
|
|
1310
|
+
bot: 0.15
|
|
1311
|
+
};
|
|
1312
|
+
var AUTOMATION_UA_PATTERNS = [
|
|
1313
|
+
/headless/i,
|
|
1314
|
+
/phantomjs/i,
|
|
1315
|
+
/selenium/i,
|
|
1316
|
+
/webdriver/i,
|
|
1317
|
+
/puppeteer/i,
|
|
1318
|
+
/playwright/i,
|
|
1319
|
+
/cypress/i,
|
|
1320
|
+
/nightwatch/i,
|
|
1321
|
+
/zombie/i,
|
|
1322
|
+
/electron/i,
|
|
1323
|
+
/chromium.*headless/i
|
|
1324
|
+
];
|
|
1325
|
+
|
|
1326
|
+
// src/detection/ip.ts
|
|
1327
|
+
import { isIPv4 } from "net";
|
|
1328
|
+
var DATACENTER_CIDRS = [
|
|
1329
|
+
// AWS
|
|
1330
|
+
"3.0.0.0/8",
|
|
1331
|
+
"13.0.0.0/8",
|
|
1332
|
+
"18.0.0.0/8",
|
|
1333
|
+
"34.0.0.0/8",
|
|
1334
|
+
"35.0.0.0/8",
|
|
1335
|
+
"52.0.0.0/8",
|
|
1336
|
+
"54.0.0.0/8",
|
|
1337
|
+
"99.0.0.0/8",
|
|
1338
|
+
// Google Cloud
|
|
1339
|
+
"34.64.0.0/10",
|
|
1340
|
+
"35.184.0.0/13",
|
|
1341
|
+
"104.154.0.0/15",
|
|
1342
|
+
"104.196.0.0/14",
|
|
1343
|
+
// Azure
|
|
1344
|
+
"13.64.0.0/11",
|
|
1345
|
+
"20.0.0.0/8",
|
|
1346
|
+
"40.64.0.0/10",
|
|
1347
|
+
"52.224.0.0/11",
|
|
1348
|
+
// DigitalOcean
|
|
1349
|
+
"64.225.0.0/16",
|
|
1350
|
+
"68.183.0.0/16",
|
|
1351
|
+
"104.131.0.0/16",
|
|
1352
|
+
"134.209.0.0/16",
|
|
1353
|
+
"138.68.0.0/16",
|
|
1354
|
+
"139.59.0.0/16",
|
|
1355
|
+
"142.93.0.0/16",
|
|
1356
|
+
"157.245.0.0/16",
|
|
1357
|
+
// Linode
|
|
1358
|
+
"45.33.0.0/16",
|
|
1359
|
+
"45.56.0.0/16",
|
|
1360
|
+
"45.79.0.0/16",
|
|
1361
|
+
"139.162.0.0/16",
|
|
1362
|
+
// Vultr
|
|
1363
|
+
"45.32.0.0/16",
|
|
1364
|
+
"45.63.0.0/16",
|
|
1365
|
+
"45.76.0.0/16",
|
|
1366
|
+
"108.61.0.0/16",
|
|
1367
|
+
// Hetzner
|
|
1368
|
+
"5.9.0.0/16",
|
|
1369
|
+
"46.4.0.0/14",
|
|
1370
|
+
"78.46.0.0/15",
|
|
1371
|
+
"88.99.0.0/16",
|
|
1372
|
+
"95.216.0.0/14",
|
|
1373
|
+
"135.181.0.0/16",
|
|
1374
|
+
// OVH
|
|
1375
|
+
"51.38.0.0/16",
|
|
1376
|
+
"51.68.0.0/16",
|
|
1377
|
+
"51.75.0.0/16",
|
|
1378
|
+
"137.74.0.0/16",
|
|
1379
|
+
"139.99.0.0/16",
|
|
1380
|
+
"144.217.0.0/16",
|
|
1381
|
+
"149.56.0.0/16"
|
|
1382
|
+
];
|
|
1383
|
+
function ipToLong(ip) {
|
|
1384
|
+
const parts = ip.split(".").map(Number);
|
|
1385
|
+
return (parts[0] << 24 | parts[1] << 16 | parts[2] << 8 | parts[3]) >>> 0;
|
|
1386
|
+
}
|
|
1387
|
+
function cidrContains(cidr, ip) {
|
|
1388
|
+
const [range, bits] = cidr.split("/");
|
|
1389
|
+
const mask = ~((1 << 32 - parseInt(bits, 10)) - 1) >>> 0;
|
|
1390
|
+
const rangeStart = ipToLong(range) & mask;
|
|
1391
|
+
const ipLong = ipToLong(ip);
|
|
1392
|
+
return (ipLong & mask) === rangeStart;
|
|
1393
|
+
}
|
|
1394
|
+
function isDatacenterIP2(ip) {
|
|
1395
|
+
if (!isIPv4(ip)) return false;
|
|
1396
|
+
return DATACENTER_CIDRS.some((cidr) => cidrContains(cidr, ip));
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
// src/detection/stores.ts
|
|
1400
|
+
var InMemoryFingerprintStore = class {
|
|
1401
|
+
constructor() {
|
|
1402
|
+
this.fingerprints = /* @__PURE__ */ new Map();
|
|
1403
|
+
this.ipFingerprints = /* @__PURE__ */ new Map();
|
|
1404
|
+
}
|
|
1405
|
+
record(fp, ip, siteKey) {
|
|
1406
|
+
const key = `${siteKey}:${fp}`;
|
|
1407
|
+
let data = this.fingerprints.get(key);
|
|
1408
|
+
if (!data) {
|
|
1409
|
+
data = { count: 0, ips: /* @__PURE__ */ new Set() };
|
|
1410
|
+
this.fingerprints.set(key, data);
|
|
1411
|
+
}
|
|
1412
|
+
data.count++;
|
|
1413
|
+
data.ips.add(ip);
|
|
1414
|
+
let ipSet = this.ipFingerprints.get(ip);
|
|
1415
|
+
if (!ipSet) {
|
|
1416
|
+
ipSet = /* @__PURE__ */ new Set();
|
|
1417
|
+
this.ipFingerprints.set(ip, ipSet);
|
|
1418
|
+
}
|
|
1419
|
+
ipSet.add(fp);
|
|
1420
|
+
}
|
|
1421
|
+
getIpFpCount(ip) {
|
|
1422
|
+
return this.ipFingerprints.get(ip)?.size ?? 0;
|
|
1423
|
+
}
|
|
1424
|
+
getFpIpCount(fp, siteKey) {
|
|
1425
|
+
return this.fingerprints.get(`${siteKey}:${fp}`)?.ips.size ?? 0;
|
|
1426
|
+
}
|
|
1427
|
+
};
|
|
1428
|
+
var InMemoryRateLimiter2 = class {
|
|
1429
|
+
constructor() {
|
|
1430
|
+
this.requests = /* @__PURE__ */ new Map();
|
|
1431
|
+
}
|
|
1432
|
+
check(key, windowSeconds = 60, maxRequests = 10) {
|
|
1433
|
+
const now = Date.now();
|
|
1434
|
+
const cutoff = now - windowSeconds * 1e3;
|
|
1435
|
+
let timestamps = (this.requests.get(key) ?? []).filter((t) => t > cutoff);
|
|
1436
|
+
const count = timestamps.length;
|
|
1437
|
+
if (count >= maxRequests) {
|
|
1438
|
+
this.requests.set(key, timestamps);
|
|
1439
|
+
return [true, count];
|
|
1440
|
+
}
|
|
1441
|
+
timestamps.push(now);
|
|
1442
|
+
this.requests.set(key, timestamps);
|
|
1443
|
+
return [false, count + 1];
|
|
1444
|
+
}
|
|
1445
|
+
};
|
|
1446
|
+
|
|
1447
|
+
// src/detection/scoring.ts
|
|
1448
|
+
function calculateCategoryScores(detections, weights) {
|
|
1449
|
+
var _a;
|
|
1450
|
+
const categoryData = {};
|
|
1451
|
+
for (const d of detections) {
|
|
1452
|
+
(categoryData[_a = d.category] ?? (categoryData[_a] = [])).push([d.score, d.confidence]);
|
|
1453
|
+
}
|
|
1454
|
+
const result = {};
|
|
1455
|
+
for (const [cat, scores] of Object.entries(categoryData)) {
|
|
1456
|
+
if (scores.length > 0) {
|
|
1457
|
+
const totalWeight = scores.reduce((sum, [, conf]) => sum + conf, 0);
|
|
1458
|
+
if (totalWeight > 0) {
|
|
1459
|
+
const weightedSum = scores.reduce((sum, [score, conf]) => sum + score * conf, 0);
|
|
1460
|
+
result[cat] = Math.min(1, weightedSum / totalWeight);
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
for (const cat of Object.keys(weights)) {
|
|
1465
|
+
if (!(cat in result)) result[cat] = 0;
|
|
1466
|
+
}
|
|
1467
|
+
return result;
|
|
1468
|
+
}
|
|
1469
|
+
function calculateFinalScore(categoryScores, weights) {
|
|
1470
|
+
let total = 0;
|
|
1471
|
+
for (const [cat, weight] of Object.entries(weights)) {
|
|
1472
|
+
total += (categoryScores[cat] ?? 0) * weight;
|
|
1473
|
+
}
|
|
1474
|
+
return Math.min(1, total);
|
|
1475
|
+
}
|
|
1476
|
+
function recommend(finalScore) {
|
|
1477
|
+
if (finalScore < 0.3) return "allow";
|
|
1478
|
+
if (finalScore < 0.6) return "challenge";
|
|
1479
|
+
return "block";
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
// src/detection/detectors/vision-ai.ts
|
|
1483
|
+
function detectVisionAI(signals) {
|
|
1484
|
+
const detections = [];
|
|
1485
|
+
const b = signals.behavioral ?? {};
|
|
1486
|
+
const t = signals.temporal ?? {};
|
|
1487
|
+
const totalPoints = b.totalPoints ?? 0;
|
|
1488
|
+
const trajectory = b.trajectoryLength ?? 0;
|
|
1489
|
+
const approachPts = b.approachPoints ?? 0;
|
|
1490
|
+
const touchEvents = b.touchEvents ?? 0;
|
|
1491
|
+
const keyEvents = b.keyEvents ?? 0;
|
|
1492
|
+
const isTouchUser = touchEvents >= 3;
|
|
1493
|
+
const isKeyboardUser = keyEvents >= 2 && totalPoints === 0;
|
|
1494
|
+
if (totalPoints < 5 && trajectory < 10 && !isTouchUser && !isKeyboardUser) {
|
|
1495
|
+
detections.push({
|
|
1496
|
+
category: "vision_ai",
|
|
1497
|
+
score: 0.9,
|
|
1498
|
+
confidence: 0.85,
|
|
1499
|
+
reason: "No mouse movement detected before click (AI agent pattern)"
|
|
1500
|
+
});
|
|
1501
|
+
}
|
|
1502
|
+
if (approachPts === 0 && !isTouchUser && !isKeyboardUser) {
|
|
1503
|
+
detections.push({
|
|
1504
|
+
category: "vision_ai",
|
|
1505
|
+
score: 0.7,
|
|
1506
|
+
confidence: 0.8,
|
|
1507
|
+
reason: "No approach trajectory to target"
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
const pow = t.pow ?? {};
|
|
1511
|
+
if (pow.duration && pow.iterations) {
|
|
1512
|
+
const expectedMin = pow.iterations / 5e5 * 1e3;
|
|
1513
|
+
const expectedMax = pow.iterations / 5e4 * 1e3;
|
|
1514
|
+
if (pow.duration < expectedMin * 0.5) {
|
|
1515
|
+
detections.push({
|
|
1516
|
+
category: "vision_ai",
|
|
1517
|
+
score: 0.8,
|
|
1518
|
+
confidence: 0.7,
|
|
1519
|
+
reason: "PoW completed impossibly fast"
|
|
1520
|
+
});
|
|
1521
|
+
} else if (pow.duration > expectedMax * 3) {
|
|
1522
|
+
detections.push({
|
|
1523
|
+
category: "vision_ai",
|
|
1524
|
+
score: 0.6,
|
|
1525
|
+
confidence: 0.5,
|
|
1526
|
+
reason: "PoW timing suggests external processing"
|
|
1527
|
+
});
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
const microTremor = b.microTremorScore ?? 0.5;
|
|
1531
|
+
if (microTremor < 0.15) {
|
|
1532
|
+
detections.push({
|
|
1533
|
+
category: "vision_ai",
|
|
1534
|
+
score: 0.7,
|
|
1535
|
+
confidence: 0.6,
|
|
1536
|
+
reason: "Mouse movement lacks natural micro-tremor"
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
if ((b.approachDirectness ?? 0) > 0.95) {
|
|
1540
|
+
detections.push({
|
|
1541
|
+
category: "vision_ai",
|
|
1542
|
+
score: 0.5,
|
|
1543
|
+
confidence: 0.5,
|
|
1544
|
+
reason: "Mouse path to target is unnaturally direct"
|
|
1545
|
+
});
|
|
1546
|
+
}
|
|
1547
|
+
const precision = b.clickPrecision ?? 10;
|
|
1548
|
+
if (precision > 0 && precision < 2) {
|
|
1549
|
+
detections.push({
|
|
1550
|
+
category: "vision_ai",
|
|
1551
|
+
score: 0.4,
|
|
1552
|
+
confidence: 0.5,
|
|
1553
|
+
reason: "Click precision is unnaturally accurate"
|
|
1554
|
+
});
|
|
1555
|
+
}
|
|
1556
|
+
const exploration = b.explorationRatio ?? 0.3;
|
|
1557
|
+
if (exploration < 0.05 && trajectory > 50) {
|
|
1558
|
+
detections.push({
|
|
1559
|
+
category: "vision_ai",
|
|
1560
|
+
score: 0.4,
|
|
1561
|
+
confidence: 0.4,
|
|
1562
|
+
reason: "No exploratory mouse movement before click"
|
|
1563
|
+
});
|
|
1564
|
+
}
|
|
1565
|
+
return detections;
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
// src/detection/detectors/headless.ts
|
|
1569
|
+
var PLAYWRIGHT_SCORE_MAP = {
|
|
1570
|
+
playwright_globals: 0.95,
|
|
1571
|
+
webdriver_deleted: 0.8,
|
|
1572
|
+
webdriver_configurable: 0.7,
|
|
1573
|
+
chrome_runtime_missing: 0.6
|
|
1574
|
+
};
|
|
1575
|
+
function detectHeadless(signals, userAgent) {
|
|
1576
|
+
const detections = [];
|
|
1577
|
+
const env = signals.environmental ?? {};
|
|
1578
|
+
const headless = env.headlessIndicators ?? {};
|
|
1579
|
+
const automation = env.automationFlags ?? {};
|
|
1580
|
+
if (env.webdriver) {
|
|
1581
|
+
detections.push({
|
|
1582
|
+
category: "headless",
|
|
1583
|
+
score: 0.95,
|
|
1584
|
+
confidence: 0.95,
|
|
1585
|
+
reason: "WebDriver detected"
|
|
1586
|
+
});
|
|
1587
|
+
}
|
|
1588
|
+
if (automation.plugins === 0) {
|
|
1589
|
+
detections.push({
|
|
1590
|
+
category: "headless",
|
|
1591
|
+
score: 0.6,
|
|
1592
|
+
confidence: 0.6,
|
|
1593
|
+
reason: "No browser plugins detected"
|
|
1594
|
+
});
|
|
1595
|
+
}
|
|
1596
|
+
if (automation.languages === false) {
|
|
1597
|
+
detections.push({
|
|
1598
|
+
category: "headless",
|
|
1599
|
+
score: 0.5,
|
|
1600
|
+
confidence: 0.5,
|
|
1601
|
+
reason: "No navigator.languages"
|
|
1602
|
+
});
|
|
1603
|
+
}
|
|
1604
|
+
if (headless.hasOuterDimensions === false) {
|
|
1605
|
+
detections.push({
|
|
1606
|
+
category: "headless",
|
|
1607
|
+
score: 0.7,
|
|
1608
|
+
confidence: 0.7,
|
|
1609
|
+
reason: "Window lacks outer dimensions"
|
|
1610
|
+
});
|
|
1611
|
+
}
|
|
1612
|
+
if (headless.innerEqualsOuter === true) {
|
|
1613
|
+
detections.push({
|
|
1614
|
+
category: "headless",
|
|
1615
|
+
score: 0.4,
|
|
1616
|
+
confidence: 0.5,
|
|
1617
|
+
reason: "Viewport equals window size"
|
|
1618
|
+
});
|
|
1619
|
+
}
|
|
1620
|
+
if (headless.notificationPermission === "denied") {
|
|
1621
|
+
detections.push({
|
|
1622
|
+
category: "headless",
|
|
1623
|
+
score: 0.3,
|
|
1624
|
+
confidence: 0.4,
|
|
1625
|
+
reason: "Notifications pre-denied"
|
|
1626
|
+
});
|
|
1627
|
+
}
|
|
1628
|
+
for (const pattern of AUTOMATION_UA_PATTERNS) {
|
|
1629
|
+
if (pattern.test(userAgent)) {
|
|
1630
|
+
detections.push({
|
|
1631
|
+
category: "headless",
|
|
1632
|
+
score: 0.9,
|
|
1633
|
+
confidence: 0.9,
|
|
1634
|
+
reason: "Automation pattern in User-Agent"
|
|
1635
|
+
});
|
|
1636
|
+
break;
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
const renderer = (env.webglInfo?.renderer ?? "").toLowerCase();
|
|
1640
|
+
if (renderer.includes("swiftshader") || renderer.includes("llvmpipe")) {
|
|
1641
|
+
detections.push({
|
|
1642
|
+
category: "headless",
|
|
1643
|
+
score: 0.8,
|
|
1644
|
+
confidence: 0.8,
|
|
1645
|
+
reason: "Software WebGL renderer detected"
|
|
1646
|
+
});
|
|
1647
|
+
}
|
|
1648
|
+
const playwright = env.playwright ?? {};
|
|
1649
|
+
if (playwright.detected) {
|
|
1650
|
+
for (const sig of playwright.signals ?? []) {
|
|
1651
|
+
detections.push({
|
|
1652
|
+
category: "headless",
|
|
1653
|
+
score: PLAYWRIGHT_SCORE_MAP[sig] ?? 0.7,
|
|
1654
|
+
confidence: 0.8,
|
|
1655
|
+
reason: `Playwright artifact detected: ${sig}`
|
|
1656
|
+
});
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
return detections;
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
// src/detection/detectors/automation.ts
|
|
1663
|
+
function detectAutomation(signals) {
|
|
1664
|
+
const detections = [];
|
|
1665
|
+
const env = signals.environmental ?? {};
|
|
1666
|
+
const b = signals.behavioral ?? {};
|
|
1667
|
+
const jsTime = env.jsExecutionTime?.mathOps ?? 0;
|
|
1668
|
+
if (jsTime > 0) {
|
|
1669
|
+
if (jsTime < 0.1) {
|
|
1670
|
+
detections.push({
|
|
1671
|
+
category: "automation",
|
|
1672
|
+
score: 0.4,
|
|
1673
|
+
confidence: 0.3,
|
|
1674
|
+
reason: "JS execution unusually fast"
|
|
1675
|
+
});
|
|
1676
|
+
} else if (jsTime > 50) {
|
|
1677
|
+
detections.push({
|
|
1678
|
+
category: "automation",
|
|
1679
|
+
score: 0.3,
|
|
1680
|
+
confidence: 0.3,
|
|
1681
|
+
reason: "JS execution unusually slow"
|
|
1682
|
+
});
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
const raf = env.rafConsistency ?? {};
|
|
1686
|
+
if (raf.frameTimeVariance !== void 0 && raf.frameTimeVariance < 0.1) {
|
|
1687
|
+
detections.push({
|
|
1688
|
+
category: "automation",
|
|
1689
|
+
score: 0.5,
|
|
1690
|
+
confidence: 0.4,
|
|
1691
|
+
reason: "RequestAnimationFrame timing too consistent"
|
|
1692
|
+
});
|
|
1693
|
+
}
|
|
1694
|
+
const eventVar = b.eventDeltaVariance ?? 10;
|
|
1695
|
+
const totalPoints = b.totalPoints ?? 0;
|
|
1696
|
+
if (eventVar < 2 && totalPoints > 10) {
|
|
1697
|
+
detections.push({
|
|
1698
|
+
category: "automation",
|
|
1699
|
+
score: 0.6,
|
|
1700
|
+
confidence: 0.6,
|
|
1701
|
+
reason: "Mouse event timing unnaturally consistent"
|
|
1702
|
+
});
|
|
1703
|
+
}
|
|
1704
|
+
return detections;
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
// src/detection/detectors/cdp.ts
|
|
1708
|
+
var HIGH_CONFIDENCE_SIGNALS = ["chromedriver_cdc", "puppeteer_eval", "cdp_script_injection"];
|
|
1709
|
+
function detectCDP(signals) {
|
|
1710
|
+
const detections = [];
|
|
1711
|
+
const cdp = signals.environmental?.cdp ?? {};
|
|
1712
|
+
if (!cdp.detected) return detections;
|
|
1713
|
+
const signalList = cdp.signals ?? [];
|
|
1714
|
+
const signalCount = signalList.length;
|
|
1715
|
+
const hasHighConf = signalList.some((s) => HIGH_CONFIDENCE_SIGNALS.includes(s));
|
|
1716
|
+
if (hasHighConf) {
|
|
1717
|
+
detections.push({
|
|
1718
|
+
category: "cdp",
|
|
1719
|
+
score: 0.9,
|
|
1720
|
+
confidence: 0.95,
|
|
1721
|
+
reason: `CDP automation detected: ${signalList.join(", ")}`
|
|
1722
|
+
});
|
|
1723
|
+
} else if (signalCount >= 2) {
|
|
1724
|
+
detections.push({
|
|
1725
|
+
category: "cdp",
|
|
1726
|
+
score: 0.8,
|
|
1727
|
+
confidence: 0.85,
|
|
1728
|
+
reason: `Multiple CDP indicators: ${signalList.join(", ")}`
|
|
1729
|
+
});
|
|
1730
|
+
} else if (signalCount === 1) {
|
|
1731
|
+
detections.push({
|
|
1732
|
+
category: "cdp",
|
|
1733
|
+
score: 0.6,
|
|
1734
|
+
confidence: 0.7,
|
|
1735
|
+
reason: `CDP indicator: ${signalList.join(", ")}`
|
|
1736
|
+
});
|
|
1737
|
+
}
|
|
1738
|
+
return detections;
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
// src/detection/detectors/behavioral.ts
|
|
1742
|
+
function detectBehavioral(signals) {
|
|
1743
|
+
const detections = [];
|
|
1744
|
+
const b = signals.behavioral ?? {};
|
|
1745
|
+
const t = signals.temporal ?? {};
|
|
1746
|
+
const totalPoints = b.totalPoints ?? 0;
|
|
1747
|
+
const trajectory = b.trajectoryLength ?? 0;
|
|
1748
|
+
const touchEvts = b.touchEvents ?? 0;
|
|
1749
|
+
const keyEvts = b.keyEvents ?? 0;
|
|
1750
|
+
const isTouchUsr = touchEvts >= 3;
|
|
1751
|
+
const isKbdUser = keyEvts >= 2 && totalPoints === 0;
|
|
1752
|
+
if (totalPoints === 0 && !isTouchUsr && !isKbdUser) {
|
|
1753
|
+
detections.push({
|
|
1754
|
+
category: "behavioral",
|
|
1755
|
+
score: 0.8,
|
|
1756
|
+
confidence: 0.9,
|
|
1757
|
+
reason: "Zero mouse, touch, or keyboard events recorded"
|
|
1758
|
+
});
|
|
1759
|
+
} else if (totalPoints < 10 && !isTouchUsr && !isKbdUser && trajectory < 30) {
|
|
1760
|
+
detections.push({
|
|
1761
|
+
category: "behavioral",
|
|
1762
|
+
score: 0.6,
|
|
1763
|
+
confidence: 0.7,
|
|
1764
|
+
reason: "Insufficient mouse movement before interaction"
|
|
1765
|
+
});
|
|
1766
|
+
}
|
|
1767
|
+
const velVar = b.velocityVariance ?? 1;
|
|
1768
|
+
if (velVar < 0.02 && trajectory > 50) {
|
|
1769
|
+
detections.push({
|
|
1770
|
+
category: "behavioral",
|
|
1771
|
+
score: 0.6,
|
|
1772
|
+
confidence: 0.6,
|
|
1773
|
+
reason: "Mouse velocity too consistent"
|
|
1774
|
+
});
|
|
1775
|
+
}
|
|
1776
|
+
const overshoots = b.overshootCorrections ?? 0;
|
|
1777
|
+
if (overshoots === 0 && trajectory > 200) {
|
|
1778
|
+
detections.push({
|
|
1779
|
+
category: "behavioral",
|
|
1780
|
+
score: 0.4,
|
|
1781
|
+
confidence: 0.4,
|
|
1782
|
+
reason: "No overshoot corrections on long trajectory"
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
const interactionTime = b.interactionDuration ?? 1e3;
|
|
1786
|
+
if (interactionTime > 0 && interactionTime < 200) {
|
|
1787
|
+
detections.push({
|
|
1788
|
+
category: "behavioral",
|
|
1789
|
+
score: 0.7,
|
|
1790
|
+
confidence: 0.7,
|
|
1791
|
+
reason: "Interaction completed too quickly"
|
|
1792
|
+
});
|
|
1793
|
+
} else if (interactionTime > 6e4) {
|
|
1794
|
+
detections.push({
|
|
1795
|
+
category: "captcha_farm",
|
|
1796
|
+
score: 0.3,
|
|
1797
|
+
confidence: 0.3,
|
|
1798
|
+
reason: "Unusually long interaction time"
|
|
1799
|
+
});
|
|
1800
|
+
}
|
|
1801
|
+
const firstInt = t.pageLoadToFirstInteraction;
|
|
1802
|
+
if (firstInt !== null && firstInt !== void 0 && firstInt > 0 && firstInt < 100) {
|
|
1803
|
+
detections.push({
|
|
1804
|
+
category: "behavioral",
|
|
1805
|
+
score: 0.5,
|
|
1806
|
+
confidence: 0.5,
|
|
1807
|
+
reason: "First interaction too soon after page load"
|
|
1808
|
+
});
|
|
1809
|
+
}
|
|
1810
|
+
const eventRate = b.mouseEventRate ?? 60;
|
|
1811
|
+
if (eventRate > 200) {
|
|
1812
|
+
detections.push({
|
|
1813
|
+
category: "behavioral",
|
|
1814
|
+
score: 0.6,
|
|
1815
|
+
confidence: 0.5,
|
|
1816
|
+
reason: "Mouse event rate abnormally high"
|
|
1817
|
+
});
|
|
1818
|
+
} else if (eventRate > 0 && eventRate < 10) {
|
|
1819
|
+
detections.push({
|
|
1820
|
+
category: "behavioral",
|
|
1821
|
+
score: 0.4,
|
|
1822
|
+
confidence: 0.4,
|
|
1823
|
+
reason: "Mouse event rate abnormally low"
|
|
1824
|
+
});
|
|
1825
|
+
}
|
|
1826
|
+
const straight = b.straightLineRatio ?? 0;
|
|
1827
|
+
if (straight > 0.8 && trajectory > 100) {
|
|
1828
|
+
detections.push({
|
|
1829
|
+
category: "behavioral",
|
|
1830
|
+
score: 0.5,
|
|
1831
|
+
confidence: 0.5,
|
|
1832
|
+
reason: "Mouse movements too straight"
|
|
1833
|
+
});
|
|
1834
|
+
}
|
|
1835
|
+
const dirChanges = b.directionChanges ?? 10;
|
|
1836
|
+
if (totalPoints > 50 && dirChanges < 3) {
|
|
1837
|
+
detections.push({
|
|
1838
|
+
category: "behavioral",
|
|
1839
|
+
score: 0.4,
|
|
1840
|
+
confidence: 0.4,
|
|
1841
|
+
reason: "Too few direction changes"
|
|
1842
|
+
});
|
|
1843
|
+
}
|
|
1844
|
+
return detections;
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
// src/detection/ua.ts
|
|
1848
|
+
var BOT_UA_PATTERNS = [
|
|
1849
|
+
/bot/i,
|
|
1850
|
+
/spider/i,
|
|
1851
|
+
/crawler/i,
|
|
1852
|
+
/scraper/i,
|
|
1853
|
+
/curl/i,
|
|
1854
|
+
/wget/i,
|
|
1855
|
+
/python/i,
|
|
1856
|
+
/java\//i,
|
|
1857
|
+
/httpie/i,
|
|
1858
|
+
/postman/i,
|
|
1859
|
+
/insomnia/i,
|
|
1860
|
+
/axios/i,
|
|
1861
|
+
/node-fetch/i,
|
|
1862
|
+
/go-http/i,
|
|
1863
|
+
/okhttp/i
|
|
1864
|
+
];
|
|
1865
|
+
var MOBILE_UA_PATTERN = /mobile|android|iphone|ipad|ipod/;
|
|
1866
|
+
function isMobileUA(userAgent) {
|
|
1867
|
+
return MOBILE_UA_PATTERN.test((userAgent || "").toLowerCase());
|
|
1868
|
+
}
|
|
1869
|
+
function parseUserAgent(ua) {
|
|
1870
|
+
const info = {
|
|
1871
|
+
browser: null,
|
|
1872
|
+
os: null,
|
|
1873
|
+
isMobile: false,
|
|
1874
|
+
isBot: false,
|
|
1875
|
+
botName: null
|
|
1876
|
+
};
|
|
1877
|
+
for (const pattern of BOT_UA_PATTERNS) {
|
|
1878
|
+
const match = ua.match(pattern);
|
|
1879
|
+
if (match) {
|
|
1880
|
+
info.isBot = true;
|
|
1881
|
+
info.botName = match[0];
|
|
1882
|
+
return info;
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
if (ua.includes("Edg/")) info.browser = "Edge";
|
|
1886
|
+
else if (ua.includes("Chrome/")) info.browser = "Chrome";
|
|
1887
|
+
else if (ua.includes("Firefox/")) info.browser = "Firefox";
|
|
1888
|
+
else if (ua.includes("Safari/") && !ua.includes("Chrome")) info.browser = "Safari";
|
|
1889
|
+
if (ua.includes("Windows")) info.os = "Windows";
|
|
1890
|
+
else if (ua.includes("Mac OS X") || ua.includes("Macintosh")) info.os = "macOS";
|
|
1891
|
+
else if (ua.includes("Linux")) info.os = "Linux";
|
|
1892
|
+
else if (ua.includes("Android")) {
|
|
1893
|
+
info.os = "Android";
|
|
1894
|
+
info.isMobile = true;
|
|
1895
|
+
} else if (ua.includes("iPhone") || ua.includes("iPad")) {
|
|
1896
|
+
info.os = "iOS";
|
|
1897
|
+
info.isMobile = true;
|
|
1898
|
+
}
|
|
1899
|
+
if (ua.includes("Mobile")) info.isMobile = true;
|
|
1900
|
+
return info;
|
|
1901
|
+
}
|
|
1902
|
+
|
|
1903
|
+
// src/detection/detectors/mobile.ts
|
|
1904
|
+
function detectTouchAuthenticity(signals, userAgent) {
|
|
1905
|
+
const detections = [];
|
|
1906
|
+
if (!isMobileUA(userAgent)) return detections;
|
|
1907
|
+
const b = signals.behavioral ?? {};
|
|
1908
|
+
const touchPoints = b.touchTotalPoints ?? b.touchEvents ?? 0;
|
|
1909
|
+
if (touchPoints < 3) return detections;
|
|
1910
|
+
const forceVariance = b.touchForceVariance ?? 0;
|
|
1911
|
+
const radiusVariance = b.touchRadiusVariance ?? 0;
|
|
1912
|
+
const forceAllOne = b.touchForceAllOne === true;
|
|
1913
|
+
const uniqueIds = b.touchUniqueIdentifiers ?? 0;
|
|
1914
|
+
const forceMax = b.touchForceMax ?? 0;
|
|
1915
|
+
const radiusMax = b.touchRadiusMax ?? 0;
|
|
1916
|
+
if (forceVariance === 0 && forceMax > 0 && touchPoints >= 5) {
|
|
1917
|
+
detections.push({
|
|
1918
|
+
category: "behavioral",
|
|
1919
|
+
score: 0.75,
|
|
1920
|
+
confidence: 0.85,
|
|
1921
|
+
reason: "Touch force is identical across all events (synthetic touch)"
|
|
1922
|
+
});
|
|
1923
|
+
}
|
|
1924
|
+
if (forceAllOne && touchPoints >= 5) {
|
|
1925
|
+
detections.push({
|
|
1926
|
+
category: "behavioral",
|
|
1927
|
+
score: 0.8,
|
|
1928
|
+
confidence: 0.9,
|
|
1929
|
+
reason: "All touches report force=1.0 exactly (synthetic pattern)"
|
|
1930
|
+
});
|
|
1931
|
+
}
|
|
1932
|
+
if (radiusVariance === 0 && radiusMax > 0 && touchPoints >= 5) {
|
|
1933
|
+
detections.push({
|
|
1934
|
+
category: "behavioral",
|
|
1935
|
+
score: 0.7,
|
|
1936
|
+
confidence: 0.8,
|
|
1937
|
+
reason: "Touch contact radius identical across all events"
|
|
1938
|
+
});
|
|
1939
|
+
}
|
|
1940
|
+
if (touchPoints >= 5 && uniqueIds === 0) {
|
|
1941
|
+
detections.push({
|
|
1942
|
+
category: "behavioral",
|
|
1943
|
+
score: 0.6,
|
|
1944
|
+
confidence: 0.7,
|
|
1945
|
+
reason: "Mobile touches lack identifier tracking (synthetic injection)"
|
|
1946
|
+
});
|
|
1947
|
+
}
|
|
1948
|
+
return detections;
|
|
1949
|
+
}
|
|
1950
|
+
function detectSensorEntropy(signals, userAgent) {
|
|
1951
|
+
const detections = [];
|
|
1952
|
+
if (!isMobileUA(userAgent)) return detections;
|
|
1953
|
+
const sensor = signals.environmental?.sensor ?? {};
|
|
1954
|
+
const motionCount = sensor.motionEventCount ?? 0;
|
|
1955
|
+
const motionVariance = sensor.motionAccelVariance ?? 0;
|
|
1956
|
+
const orientationCount = sensor.orientationEventCount ?? 0;
|
|
1957
|
+
const orientationVariance = sensor.orientationVariance ?? 0;
|
|
1958
|
+
if (motionCount >= 10 && motionVariance < 0.01) {
|
|
1959
|
+
detections.push({
|
|
1960
|
+
category: "headless",
|
|
1961
|
+
score: 0.7,
|
|
1962
|
+
confidence: 0.8,
|
|
1963
|
+
reason: `Motion sensor active but flat (variance=${motionVariance.toFixed(4)}) \u2014 likely emulator`
|
|
1964
|
+
});
|
|
1965
|
+
}
|
|
1966
|
+
if (orientationCount >= 10 && orientationVariance < 0.01) {
|
|
1967
|
+
detections.push({
|
|
1968
|
+
category: "headless",
|
|
1969
|
+
score: 0.6,
|
|
1970
|
+
confidence: 0.7,
|
|
1971
|
+
reason: "Orientation sensor active but completely flat \u2014 likely emulator"
|
|
1972
|
+
});
|
|
1973
|
+
}
|
|
1974
|
+
return detections;
|
|
1975
|
+
}
|
|
1976
|
+
function detectTouchKinematics(signals) {
|
|
1977
|
+
const detections = [];
|
|
1978
|
+
const b = signals.behavioral ?? {};
|
|
1979
|
+
const touchPoints = b.touchTotalPoints ?? 0;
|
|
1980
|
+
if (touchPoints < 10) return detections;
|
|
1981
|
+
const straightLine = b.touchStraightLineRatio ?? 0;
|
|
1982
|
+
const tremor = b.touchMicroTremorScore ?? 0;
|
|
1983
|
+
const dirChanges = b.touchDirectionChanges ?? 0;
|
|
1984
|
+
if (straightLine > 0.85 && touchPoints >= 20) {
|
|
1985
|
+
detections.push({
|
|
1986
|
+
category: "behavioral",
|
|
1987
|
+
score: 0.65,
|
|
1988
|
+
confidence: 0.75,
|
|
1989
|
+
reason: `Touch path too straight (ratio=${straightLine.toFixed(2)}) \u2014 automation pattern`
|
|
1990
|
+
});
|
|
1991
|
+
}
|
|
1992
|
+
if (tremor < 0.05 && touchPoints >= 30) {
|
|
1993
|
+
detections.push({
|
|
1994
|
+
category: "behavioral",
|
|
1995
|
+
score: 0.55,
|
|
1996
|
+
confidence: 0.65,
|
|
1997
|
+
reason: "Touch path has no micro-tremor (unnaturally smooth)"
|
|
1998
|
+
});
|
|
1999
|
+
}
|
|
2000
|
+
if (dirChanges === 0 && touchPoints >= 30) {
|
|
2001
|
+
detections.push({
|
|
2002
|
+
category: "behavioral",
|
|
2003
|
+
score: 0.5,
|
|
2004
|
+
confidence: 0.6,
|
|
2005
|
+
reason: "Touch path has zero direction changes over long trajectory"
|
|
2006
|
+
});
|
|
2007
|
+
}
|
|
2008
|
+
return detections;
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
// src/detection/detectors/fingerprint.ts
|
|
2012
|
+
import { createHash } from "crypto";
|
|
2013
|
+
function detectFingerprint(signals, ip, siteKey, store) {
|
|
2014
|
+
const detections = [];
|
|
2015
|
+
const env = signals.environmental ?? {};
|
|
2016
|
+
const automation = env.automationFlags ?? {};
|
|
2017
|
+
const components = [
|
|
2018
|
+
String(env.canvasHash?.hash ?? ""),
|
|
2019
|
+
String(env.webglInfo?.renderer ?? ""),
|
|
2020
|
+
String(automation.platform ?? ""),
|
|
2021
|
+
String(automation.hardwareConcurrency ?? "")
|
|
2022
|
+
];
|
|
2023
|
+
const fp = createHash("sha256").update(components.join("|")).digest("hex").slice(0, 16);
|
|
2024
|
+
store.record(fp, ip, siteKey);
|
|
2025
|
+
if (store.getIpFpCount(ip) > 5) {
|
|
2026
|
+
detections.push({
|
|
2027
|
+
category: "fingerprint",
|
|
2028
|
+
score: 0.6,
|
|
2029
|
+
confidence: 0.6,
|
|
2030
|
+
reason: "IP has used many different fingerprints"
|
|
2031
|
+
});
|
|
2032
|
+
}
|
|
2033
|
+
if (store.getFpIpCount(fp, siteKey) > 10) {
|
|
2034
|
+
detections.push({
|
|
2035
|
+
category: "fingerprint",
|
|
2036
|
+
score: 0.5,
|
|
2037
|
+
confidence: 0.5,
|
|
2038
|
+
reason: "Fingerprint seen from many IPs"
|
|
2039
|
+
});
|
|
2040
|
+
}
|
|
2041
|
+
const canvas = env.canvasHash ?? {};
|
|
2042
|
+
if (canvas.error || canvas.supported === false) {
|
|
2043
|
+
detections.push({
|
|
2044
|
+
category: "fingerprint",
|
|
2045
|
+
score: 0.4,
|
|
2046
|
+
confidence: 0.4,
|
|
2047
|
+
reason: "Canvas fingerprinting blocked or failed"
|
|
2048
|
+
});
|
|
2049
|
+
}
|
|
2050
|
+
return detections;
|
|
2051
|
+
}
|
|
2052
|
+
|
|
2053
|
+
// src/detection/detectors/rate.ts
|
|
2054
|
+
function detectRateAbuse(ip, siteKey, limiter) {
|
|
2055
|
+
const detections = [];
|
|
2056
|
+
const [exceeded, count] = limiter.check(`${siteKey}:${ip}`, 60, 10);
|
|
2057
|
+
if (exceeded) {
|
|
2058
|
+
detections.push({
|
|
2059
|
+
category: "rate_limit",
|
|
2060
|
+
score: 0.8,
|
|
2061
|
+
confidence: 0.9,
|
|
2062
|
+
reason: "Rate limit exceeded"
|
|
2063
|
+
});
|
|
2064
|
+
} else if (count > 5) {
|
|
2065
|
+
detections.push({
|
|
2066
|
+
category: "rate_limit",
|
|
2067
|
+
score: 0.3,
|
|
2068
|
+
confidence: 0.5,
|
|
2069
|
+
reason: "High request rate"
|
|
2070
|
+
});
|
|
2071
|
+
}
|
|
2072
|
+
return detections;
|
|
2073
|
+
}
|
|
2074
|
+
|
|
2075
|
+
// src/detection/detectors/headers.ts
|
|
2076
|
+
var SUSPICIOUS_HEADERS = /* @__PURE__ */ new Set([
|
|
2077
|
+
"x-requested-with",
|
|
2078
|
+
"x-forwarded-for",
|
|
2079
|
+
"x-real-ip",
|
|
2080
|
+
"via",
|
|
2081
|
+
"forwarded",
|
|
2082
|
+
"x-originating-ip",
|
|
2083
|
+
"cf-connecting-ip",
|
|
2084
|
+
"true-client-ip",
|
|
2085
|
+
"x-cluster-client-ip"
|
|
2086
|
+
]);
|
|
2087
|
+
var EXPECTED_BROWSER_HEADERS = ["accept", "accept-language", "accept-encoding", "user-agent"];
|
|
2088
|
+
function analyzeHeaders(headers) {
|
|
2089
|
+
const detections = [];
|
|
2090
|
+
const headersLower = {};
|
|
2091
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
2092
|
+
headersLower[key.toLowerCase()] = value;
|
|
2093
|
+
}
|
|
2094
|
+
let missingCount = 0;
|
|
2095
|
+
for (const header of EXPECTED_BROWSER_HEADERS) {
|
|
2096
|
+
if (!(header in headersLower)) missingCount++;
|
|
2097
|
+
}
|
|
2098
|
+
if (missingCount > 1) {
|
|
2099
|
+
detections.push({
|
|
2100
|
+
category: "bot",
|
|
2101
|
+
score: 0.4,
|
|
2102
|
+
confidence: 0.5,
|
|
2103
|
+
reason: `Missing ${missingCount} expected browser headers`
|
|
2104
|
+
});
|
|
2105
|
+
}
|
|
2106
|
+
for (const header of Object.keys(headersLower)) {
|
|
2107
|
+
if (SUSPICIOUS_HEADERS.has(header)) {
|
|
2108
|
+
detections.push({
|
|
2109
|
+
category: "bot",
|
|
2110
|
+
score: 0.3,
|
|
2111
|
+
confidence: 0.4,
|
|
2112
|
+
reason: `Suspicious header present: ${header}`
|
|
2113
|
+
});
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
const acceptLang = headersLower["accept-language"] ?? "";
|
|
2117
|
+
if (acceptLang === "" || acceptLang === "*") {
|
|
2118
|
+
detections.push({
|
|
2119
|
+
category: "bot",
|
|
2120
|
+
score: 0.3,
|
|
2121
|
+
confidence: 0.4,
|
|
2122
|
+
reason: "Invalid Accept-Language header"
|
|
2123
|
+
});
|
|
2124
|
+
}
|
|
2125
|
+
const acceptEnc = headersLower["accept-encoding"] ?? "";
|
|
2126
|
+
if (acceptEnc && !acceptEnc.includes("gzip") && !acceptEnc.includes("deflate")) {
|
|
2127
|
+
detections.push({
|
|
2128
|
+
category: "bot",
|
|
2129
|
+
score: 0.2,
|
|
2130
|
+
confidence: 0.3,
|
|
2131
|
+
reason: "Unusual Accept-Encoding"
|
|
2132
|
+
});
|
|
2133
|
+
}
|
|
2134
|
+
return detections;
|
|
2135
|
+
}
|
|
2136
|
+
|
|
2137
|
+
// src/detection/detectors/consistency.ts
|
|
2138
|
+
function checkBrowserConsistency(ua, signals) {
|
|
2139
|
+
const detections = [];
|
|
2140
|
+
const uaInfo = parseUserAgent(ua);
|
|
2141
|
+
if (uaInfo.isBot) {
|
|
2142
|
+
detections.push({
|
|
2143
|
+
category: "bot",
|
|
2144
|
+
score: 0.9,
|
|
2145
|
+
confidence: 0.95,
|
|
2146
|
+
reason: `User-Agent indicates bot: ${uaInfo.botName}`
|
|
2147
|
+
});
|
|
2148
|
+
return detections;
|
|
2149
|
+
}
|
|
2150
|
+
const env = signals.environmental ?? {};
|
|
2151
|
+
const nav = env.navigator ?? {};
|
|
2152
|
+
const automation = env.automationFlags ?? {};
|
|
2153
|
+
const platform = nav.platform ?? automation.platform ?? "";
|
|
2154
|
+
if (uaInfo.os === "Windows" && !platform.includes("Win")) {
|
|
2155
|
+
detections.push({
|
|
2156
|
+
category: "bot",
|
|
2157
|
+
score: 0.6,
|
|
2158
|
+
confidence: 0.7,
|
|
2159
|
+
reason: `UA/platform mismatch: UA claims Windows, platform=${platform}`
|
|
2160
|
+
});
|
|
2161
|
+
}
|
|
2162
|
+
if (uaInfo.os === "macOS" && !platform.includes("Mac")) {
|
|
2163
|
+
detections.push({
|
|
2164
|
+
category: "bot",
|
|
2165
|
+
score: 0.6,
|
|
2166
|
+
confidence: 0.7,
|
|
2167
|
+
reason: `UA/platform mismatch: UA claims macOS, platform=${platform}`
|
|
2168
|
+
});
|
|
2169
|
+
}
|
|
2170
|
+
if (uaInfo.os === "Linux" && !platform.includes("Linux")) {
|
|
2171
|
+
detections.push({
|
|
2172
|
+
category: "bot",
|
|
2173
|
+
score: 0.6,
|
|
2174
|
+
confidence: 0.7,
|
|
2175
|
+
reason: `UA/platform mismatch: UA claims Linux, platform=${platform}`
|
|
2176
|
+
});
|
|
2177
|
+
}
|
|
2178
|
+
const maxTouch = nav.maxTouchPoints ?? automation.maxTouchPoints ?? 0;
|
|
2179
|
+
if (uaInfo.isMobile && maxTouch === 0) {
|
|
2180
|
+
detections.push({
|
|
2181
|
+
category: "bot",
|
|
2182
|
+
score: 0.5,
|
|
2183
|
+
confidence: 0.6,
|
|
2184
|
+
reason: "UA claims mobile but no touch support"
|
|
2185
|
+
});
|
|
2186
|
+
}
|
|
2187
|
+
if (uaInfo.browser === "Chrome" && !automation.chrome) {
|
|
2188
|
+
detections.push({
|
|
2189
|
+
category: "bot",
|
|
2190
|
+
score: 0.7,
|
|
2191
|
+
confidence: 0.8,
|
|
2192
|
+
reason: "UA claims Chrome but window.chrome missing"
|
|
2193
|
+
});
|
|
2194
|
+
}
|
|
2195
|
+
return detections;
|
|
2196
|
+
}
|
|
2197
|
+
|
|
2198
|
+
// src/detection/detectors/tls.ts
|
|
2199
|
+
var KNOWN_BOT_JA3_HASHES = {
|
|
2200
|
+
"3b5074b1b5d032e5620f69f9f700ff0e": "Python requests",
|
|
2201
|
+
b32309a26951912be7dba376398abc3b: "Python urllib",
|
|
2202
|
+
"9e10692f1b7f78228b2d4e424db3a98c": "Go net/http",
|
|
2203
|
+
"473cd7cb9faa642487833865d516e578": "curl",
|
|
2204
|
+
c12f54a3f91dc7bafd92cb59fe009a35: "Wget",
|
|
2205
|
+
"2d1eb5817ece335c24904f516ad5da2f": "Java HttpClient",
|
|
2206
|
+
fc54fe03db02a25e1be5bb5a7678b7a4: "Node.js axios",
|
|
2207
|
+
"579ccef312d18482fc42e2b822ca2430": "Node.js node-fetch",
|
|
2208
|
+
"5d7974c9fe7862e0f9a3eb35a6a5d9c8": "Puppeteer default"
|
|
2209
|
+
};
|
|
2210
|
+
var KNOWN_BOT_JA4_HASHES = {};
|
|
2211
|
+
function checkJA3Fingerprint(ja3Hash) {
|
|
2212
|
+
if (!ja3Hash) return [];
|
|
2213
|
+
const match = KNOWN_BOT_JA3_HASHES[ja3Hash];
|
|
2214
|
+
if (match) {
|
|
2215
|
+
return [
|
|
2216
|
+
{
|
|
2217
|
+
category: "bot",
|
|
2218
|
+
score: 0.8,
|
|
2219
|
+
confidence: 0.9,
|
|
2220
|
+
reason: `TLS fingerprint matches: ${match}`
|
|
2221
|
+
}
|
|
2222
|
+
];
|
|
2223
|
+
}
|
|
2224
|
+
return [];
|
|
2225
|
+
}
|
|
2226
|
+
function checkJA4Fingerprint(ja4) {
|
|
2227
|
+
if (!ja4) return [];
|
|
2228
|
+
const match = KNOWN_BOT_JA4_HASHES[ja4];
|
|
2229
|
+
if (match) {
|
|
2230
|
+
return [
|
|
2231
|
+
{
|
|
2232
|
+
category: "fingerprint",
|
|
2233
|
+
score: 0.8,
|
|
2234
|
+
confidence: 0.9,
|
|
2235
|
+
reason: `TLS JA4 fingerprint matches: ${match}`
|
|
2236
|
+
}
|
|
2237
|
+
];
|
|
2238
|
+
}
|
|
2239
|
+
return [];
|
|
2240
|
+
}
|
|
2241
|
+
function readJA4FromHeaders(headers, trustedHeaderNames) {
|
|
2242
|
+
if (!trustedHeaderNames || trustedHeaderNames.length === 0) return null;
|
|
2243
|
+
for (const name of trustedHeaderNames) {
|
|
2244
|
+
const v = headers[name];
|
|
2245
|
+
if (v && typeof v === "string" && v.trim()) return v.trim();
|
|
2246
|
+
}
|
|
2247
|
+
return null;
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
// src/detection/stats.ts
|
|
2251
|
+
function mean(arr) {
|
|
2252
|
+
if (arr.length === 0) return 0;
|
|
2253
|
+
return arr.reduce((a, b) => a + b, 0) / arr.length;
|
|
2254
|
+
}
|
|
2255
|
+
function stddev(arr) {
|
|
2256
|
+
if (arr.length < 2) return 0;
|
|
2257
|
+
const m = mean(arr);
|
|
2258
|
+
const variance = arr.reduce((acc, v) => acc + (v - m) * (v - m), 0) / arr.length;
|
|
2259
|
+
return Math.sqrt(variance);
|
|
2260
|
+
}
|
|
2261
|
+
function erf(x) {
|
|
2262
|
+
const sign = x >= 0 ? 1 : -1;
|
|
2263
|
+
x = Math.abs(x);
|
|
2264
|
+
const t = 1 / (1 + 0.3275911 * x);
|
|
2265
|
+
const y = 1 - ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-x * x);
|
|
2266
|
+
return sign * y;
|
|
2267
|
+
}
|
|
2268
|
+
function normalCDF(x, mu, sigma) {
|
|
2269
|
+
if (sigma <= 0) return x >= mu ? 1 : 0;
|
|
2270
|
+
return 0.5 * (1 + erf((x - mu) / (sigma * Math.SQRT2)));
|
|
2271
|
+
}
|
|
2272
|
+
function ksTestStatistic(samples, cdfFn) {
|
|
2273
|
+
const n = samples.length;
|
|
2274
|
+
if (n === 0) return 0;
|
|
2275
|
+
const sorted = [...samples].sort((a, b) => a - b);
|
|
2276
|
+
let maxD = 0;
|
|
2277
|
+
for (let i = 0; i < n; i++) {
|
|
2278
|
+
const empirical = (i + 1) / n;
|
|
2279
|
+
const theoretical = cdfFn(sorted[i]);
|
|
2280
|
+
const d1 = Math.abs(empirical - theoretical);
|
|
2281
|
+
const d2 = Math.abs(i / n - theoretical);
|
|
2282
|
+
maxD = Math.max(maxD, d1, d2);
|
|
2283
|
+
}
|
|
2284
|
+
return maxD;
|
|
2285
|
+
}
|
|
2286
|
+
function shannonEntropy(arr, bins) {
|
|
2287
|
+
if (arr.length === 0) return 0;
|
|
2288
|
+
const min = Math.min(...arr);
|
|
2289
|
+
const max = Math.max(...arr);
|
|
2290
|
+
if (max === min) return 0;
|
|
2291
|
+
const binWidth = (max - min) / bins;
|
|
2292
|
+
const counts = new Array(bins).fill(0);
|
|
2293
|
+
for (const v of arr) {
|
|
2294
|
+
let idx = Math.floor((v - min) / binWidth);
|
|
2295
|
+
if (idx >= bins) idx = bins - 1;
|
|
2296
|
+
counts[idx]++;
|
|
2297
|
+
}
|
|
2298
|
+
const n = arr.length;
|
|
2299
|
+
let entropy = 0;
|
|
2300
|
+
for (const c of counts) {
|
|
2301
|
+
if (c > 0) {
|
|
2302
|
+
const p = c / n;
|
|
2303
|
+
entropy -= p * Math.log2(p);
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
return entropy;
|
|
2307
|
+
}
|
|
2308
|
+
function lag1Autocorrelation(arr) {
|
|
2309
|
+
if (arr.length < 3) return 0;
|
|
2310
|
+
const n = arr.length - 1;
|
|
2311
|
+
const x = arr.slice(0, n);
|
|
2312
|
+
const y = arr.slice(1);
|
|
2313
|
+
const mx = mean(x);
|
|
2314
|
+
const my = mean(y);
|
|
2315
|
+
let num = 0;
|
|
2316
|
+
let dx2 = 0;
|
|
2317
|
+
let dy2 = 0;
|
|
2318
|
+
for (let i = 0; i < n; i++) {
|
|
2319
|
+
const dx = x[i] - mx;
|
|
2320
|
+
const dy = y[i] - my;
|
|
2321
|
+
num += dx * dy;
|
|
2322
|
+
dx2 += dx * dx;
|
|
2323
|
+
dy2 += dy * dy;
|
|
2324
|
+
}
|
|
2325
|
+
const denom = Math.sqrt(dx2 * dy2);
|
|
2326
|
+
if (denom === 0) return 0;
|
|
2327
|
+
return num / denom;
|
|
2328
|
+
}
|
|
2329
|
+
|
|
2330
|
+
// src/detection/detectors/keystroke.ts
|
|
2331
|
+
function analyzeKeystrokeCadence(stats) {
|
|
2332
|
+
const keyCount = stats.keyCount ?? 0;
|
|
2333
|
+
const intervals = stats.intervals ?? [];
|
|
2334
|
+
const dwellTimes = stats.dwellTimes ?? [];
|
|
2335
|
+
const rollovers = stats.rollovers ?? 0;
|
|
2336
|
+
if (keyCount < 20 || intervals.length < 15) return null;
|
|
2337
|
+
const metrics = {};
|
|
2338
|
+
let totalWeight = 0;
|
|
2339
|
+
let weightedSum = 0;
|
|
2340
|
+
let activeMetricCount = 0;
|
|
2341
|
+
if (dwellTimes.length >= 10) {
|
|
2342
|
+
const dSd = stddev(dwellTimes);
|
|
2343
|
+
let score;
|
|
2344
|
+
if (dSd < 3) score = 0;
|
|
2345
|
+
else if (dSd < 10) score = 0.35 * (dSd - 3) / 7;
|
|
2346
|
+
else if (dSd < 20) score = 0.35 + 0.65 * (dSd - 10) / 10;
|
|
2347
|
+
else score = 1;
|
|
2348
|
+
metrics.dwellVariance = score;
|
|
2349
|
+
totalWeight += 0.15;
|
|
2350
|
+
weightedSum += score * 0.15;
|
|
2351
|
+
activeMetricCount++;
|
|
2352
|
+
}
|
|
2353
|
+
if (intervals.length >= 15) {
|
|
2354
|
+
const logIntervals = intervals.filter((v) => v > 0).map((v) => Math.log(v));
|
|
2355
|
+
if (logIntervals.length >= 10) {
|
|
2356
|
+
const mu = mean(logIntervals);
|
|
2357
|
+
const sigma = stddev(logIntervals);
|
|
2358
|
+
const D = ksTestStatistic(logIntervals, (x) => normalCDF(x, mu, sigma));
|
|
2359
|
+
const critical = 1.22 / Math.sqrt(logIntervals.length);
|
|
2360
|
+
let score;
|
|
2361
|
+
if (D <= critical * 0.8) score = 1;
|
|
2362
|
+
else if (D <= critical) score = 0.7;
|
|
2363
|
+
else if (D <= critical * 1.5) score = 0.3;
|
|
2364
|
+
else score = 0;
|
|
2365
|
+
metrics.logNormalFit = score;
|
|
2366
|
+
totalWeight += 0.2;
|
|
2367
|
+
weightedSum += score * 0.2;
|
|
2368
|
+
activeMetricCount++;
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
if (intervals.length >= 15) {
|
|
2372
|
+
const minI = Math.min(...intervals);
|
|
2373
|
+
const maxI = Math.max(...intervals);
|
|
2374
|
+
if (maxI > minI) {
|
|
2375
|
+
const D = ksTestStatistic(intervals, (x) => (x - minI) / (maxI - minI));
|
|
2376
|
+
let score;
|
|
2377
|
+
if (D < 0.05) score = 0;
|
|
2378
|
+
else if (D < 0.1) score = 0.3;
|
|
2379
|
+
else if (D < 0.15) score = 0.6;
|
|
2380
|
+
else score = 1;
|
|
2381
|
+
metrics.uniformity = score;
|
|
2382
|
+
totalWeight += 0.15;
|
|
2383
|
+
weightedSum += score * 0.15;
|
|
2384
|
+
activeMetricCount++;
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
if (intervals.length >= 15) {
|
|
2388
|
+
const r = Math.abs(lag1Autocorrelation(intervals));
|
|
2389
|
+
let score;
|
|
2390
|
+
if (r < 0.02) score = 0.1;
|
|
2391
|
+
else if (r < 0.1) score = 0.1 + 0.4 * (r - 0.02) / 0.08;
|
|
2392
|
+
else if (r < 0.2) score = 0.5 + 0.4 * (r - 0.1) / 0.1;
|
|
2393
|
+
else if (r <= 0.4) score = 0.9;
|
|
2394
|
+
else if (r <= 0.6) score = 0.9 - 0.4 * (r - 0.4) / 0.2;
|
|
2395
|
+
else score = 0.5;
|
|
2396
|
+
metrics.autocorrelation = score;
|
|
2397
|
+
totalWeight += 0.15;
|
|
2398
|
+
weightedSum += score * 0.15;
|
|
2399
|
+
activeMetricCount++;
|
|
2400
|
+
}
|
|
2401
|
+
const burstGaps = [];
|
|
2402
|
+
for (let i = 0; i < intervals.length; i++) {
|
|
2403
|
+
if (intervals[i] > 300) burstGaps.push(intervals[i]);
|
|
2404
|
+
}
|
|
2405
|
+
if (burstGaps.length >= 3) {
|
|
2406
|
+
const burstMean = mean(burstGaps);
|
|
2407
|
+
const burstSd = stddev(burstGaps);
|
|
2408
|
+
const cv = burstMean > 0 ? burstSd / burstMean : 0;
|
|
2409
|
+
let score;
|
|
2410
|
+
if (cv < 0.1) score = 0.1;
|
|
2411
|
+
else if (cv < 0.3) score = 0.1 + 0.9 * (cv - 0.1) / 0.2;
|
|
2412
|
+
else score = 1;
|
|
2413
|
+
metrics.burstRegularity = score;
|
|
2414
|
+
totalWeight += 0.1;
|
|
2415
|
+
weightedSum += score * 0.1;
|
|
2416
|
+
activeMetricCount++;
|
|
2417
|
+
}
|
|
2418
|
+
if (intervals.length >= 15) {
|
|
2419
|
+
const H = shannonEntropy(intervals, 10);
|
|
2420
|
+
let score;
|
|
2421
|
+
if (H < 0.5) score = 0.1;
|
|
2422
|
+
else if (H < 1.5) score = 0.1 + 0.5 * (H - 0.5);
|
|
2423
|
+
else if (H < 2) score = 0.6 + 0.4 * (H - 1.5) / 0.5;
|
|
2424
|
+
else if (H <= 3) score = 1;
|
|
2425
|
+
else if (H <= 3.3) score = 0.7;
|
|
2426
|
+
else score = 0.4;
|
|
2427
|
+
metrics.entropy = score;
|
|
2428
|
+
totalWeight += 0.15;
|
|
2429
|
+
weightedSum += score * 0.15;
|
|
2430
|
+
activeMetricCount++;
|
|
2431
|
+
}
|
|
2432
|
+
if (keyCount >= 30) {
|
|
2433
|
+
const rate = rollovers / keyCount;
|
|
2434
|
+
let score;
|
|
2435
|
+
if (rate === 0) score = 0.5;
|
|
2436
|
+
else if (rate < 0.05) score = 0.5 + 0.3 * (rate / 0.05);
|
|
2437
|
+
else if (rate < 0.15) score = 0.8 + 0.2 * ((rate - 0.05) / 0.1);
|
|
2438
|
+
else score = 1;
|
|
2439
|
+
metrics.rolloverRate = score;
|
|
2440
|
+
totalWeight += 0.1;
|
|
2441
|
+
weightedSum += score * 0.1;
|
|
2442
|
+
activeMetricCount++;
|
|
2443
|
+
}
|
|
2444
|
+
if (totalWeight === 0) return null;
|
|
2445
|
+
const humanScore = weightedSum / totalWeight;
|
|
2446
|
+
const botScore = 1 - humanScore;
|
|
2447
|
+
if (botScore <= 0.55) return null;
|
|
2448
|
+
return {
|
|
2449
|
+
category: "bot",
|
|
2450
|
+
score: botScore * 0.7,
|
|
2451
|
+
confidence: Math.min(0.7, activeMetricCount / 7),
|
|
2452
|
+
reason: "Keystroke cadence analysis indicates non-human typing pattern",
|
|
2453
|
+
details: { metrics, cadenceHumanScore: humanScore }
|
|
2454
|
+
};
|
|
2455
|
+
}
|
|
2456
|
+
|
|
2457
|
+
// src/detection/detectors/form.ts
|
|
2458
|
+
function analyzeFormInteraction(formAnalysis) {
|
|
2459
|
+
if (!formAnalysis) return [];
|
|
2460
|
+
const detections = [];
|
|
2461
|
+
const submit = formAnalysis.submit ?? {};
|
|
2462
|
+
if (submit.method === "programmatic" || submit.method === "programmatic_click") {
|
|
2463
|
+
detections.push({
|
|
2464
|
+
category: "bot",
|
|
2465
|
+
score: 0.8,
|
|
2466
|
+
confidence: 0.85,
|
|
2467
|
+
reason: `Form submitted programmatically (${submit.method})`
|
|
2468
|
+
});
|
|
2469
|
+
}
|
|
2470
|
+
if (submit.timeSincePageLoad !== null && submit.timeSincePageLoad !== void 0 && submit.timeSincePageLoad < 800) {
|
|
2471
|
+
detections.push({
|
|
2472
|
+
category: "bot",
|
|
2473
|
+
score: 0.7,
|
|
2474
|
+
confidence: 0.75,
|
|
2475
|
+
reason: `Form submitted too quickly after page load (${Math.round(submit.timeSincePageLoad)}ms)`
|
|
2476
|
+
});
|
|
2477
|
+
}
|
|
2478
|
+
const pageToFirst = formAnalysis.pageLoadToFirstInteraction;
|
|
2479
|
+
if (pageToFirst !== null && pageToFirst !== void 0 && pageToFirst < 300) {
|
|
2480
|
+
detections.push({
|
|
2481
|
+
category: "bot",
|
|
2482
|
+
score: 0.6,
|
|
2483
|
+
confidence: 0.65,
|
|
2484
|
+
reason: `First interaction too fast after page load (${Math.round(pageToFirst)}ms)`
|
|
2485
|
+
});
|
|
2486
|
+
}
|
|
2487
|
+
if (submit.eventsBeforeSubmit === 0 && submit.method !== "none") {
|
|
2488
|
+
detections.push({
|
|
2489
|
+
category: "bot",
|
|
2490
|
+
score: 0.9,
|
|
2491
|
+
confidence: 0.9,
|
|
2492
|
+
reason: "Form submitted with no user interaction events"
|
|
2493
|
+
});
|
|
2494
|
+
}
|
|
2495
|
+
if (submit.eventsBeforeSubmit !== void 0 && submit.eventsBeforeSubmit > 0 && submit.eventsBeforeSubmit < 3 && submit.method !== "none") {
|
|
2496
|
+
detections.push({
|
|
2497
|
+
category: "bot",
|
|
2498
|
+
score: 0.5,
|
|
2499
|
+
confidence: 0.6,
|
|
2500
|
+
reason: `Very few events before submit (${submit.eventsBeforeSubmit})`
|
|
2501
|
+
});
|
|
2502
|
+
}
|
|
2503
|
+
const textareaData = formAnalysis.textareaKeyboard;
|
|
2504
|
+
if (textareaData) {
|
|
2505
|
+
for (const [fieldId, stats] of Object.entries(textareaData)) {
|
|
2506
|
+
const keyCount = stats.keyCount ?? 0;
|
|
2507
|
+
const pasteCount = stats.pasteCount ?? 0;
|
|
2508
|
+
const avgKeyInterval = stats.avgKeyInterval ?? 0;
|
|
2509
|
+
const keyIntervalVariance = stats.keyIntervalVariance ?? 0;
|
|
2510
|
+
const keydownUpRatio = stats.keydownUpRatio ?? 1;
|
|
2511
|
+
if (pasteCount > 0 && keyCount < 5) {
|
|
2512
|
+
detections.push({
|
|
2513
|
+
category: "bot",
|
|
2514
|
+
score: 0.6,
|
|
2515
|
+
confidence: 0.6,
|
|
2516
|
+
reason: `Textarea "${fieldId}" filled mostly by paste (${pasteCount} pastes, ${keyCount} keystrokes)`
|
|
2517
|
+
});
|
|
2518
|
+
}
|
|
2519
|
+
if (keyCount > 10 && keyIntervalVariance < 100) {
|
|
2520
|
+
detections.push({
|
|
2521
|
+
category: "bot",
|
|
2522
|
+
score: 0.5,
|
|
2523
|
+
confidence: 0.55,
|
|
2524
|
+
reason: `Textarea "${fieldId}" has unnaturally consistent typing rhythm`
|
|
2525
|
+
});
|
|
2526
|
+
}
|
|
2527
|
+
if (keyCount > 10 && avgKeyInterval > 0 && avgKeyInterval < 50) {
|
|
2528
|
+
detections.push({
|
|
2529
|
+
category: "bot",
|
|
2530
|
+
score: 0.7,
|
|
2531
|
+
confidence: 0.7,
|
|
2532
|
+
reason: `Textarea "${fieldId}" typing speed impossibly fast (${Math.round(avgKeyInterval)}ms/key)`
|
|
2533
|
+
});
|
|
2534
|
+
}
|
|
2535
|
+
if (keyCount > 10 && (keydownUpRatio < 0.8 || keydownUpRatio > 1.2)) {
|
|
2536
|
+
detections.push({
|
|
2537
|
+
category: "bot",
|
|
2538
|
+
score: 0.4,
|
|
2539
|
+
confidence: 0.5,
|
|
2540
|
+
reason: `Textarea "${fieldId}" has abnormal keydown/keyup ratio (${keydownUpRatio.toFixed(2)})`
|
|
2541
|
+
});
|
|
2542
|
+
}
|
|
2543
|
+
if (stats.noKeyboardEvents && (stats.contentLength ?? 0) > 0) {
|
|
2544
|
+
detections.push({
|
|
2545
|
+
category: "bot",
|
|
2546
|
+
score: 0.75,
|
|
2547
|
+
confidence: 0.8,
|
|
2548
|
+
reason: `Textarea "${fieldId}" has ${stats.contentLength} chars but no keyboard events (DOM manipulation)`
|
|
2549
|
+
});
|
|
2550
|
+
}
|
|
2551
|
+
const cadenceResult = analyzeKeystrokeCadence(stats);
|
|
2552
|
+
if (cadenceResult) detections.push(cadenceResult);
|
|
2553
|
+
}
|
|
2554
|
+
}
|
|
2555
|
+
return detections;
|
|
2556
|
+
}
|
|
2557
|
+
|
|
2558
|
+
// src/detection/detectors/advanced.ts
|
|
2559
|
+
function analyzeWebRTC(webrtcInfo) {
|
|
2560
|
+
if (!webrtcInfo || !webrtcInfo.supported) return [];
|
|
2561
|
+
const detections = [];
|
|
2562
|
+
const mediaDevices = webrtcInfo.mediaDevices ?? {};
|
|
2563
|
+
if (mediaDevices.supported && mediaDevices.totalDevices === 0) {
|
|
2564
|
+
detections.push({
|
|
2565
|
+
category: "headless",
|
|
2566
|
+
score: 0.7,
|
|
2567
|
+
confidence: 0.75,
|
|
2568
|
+
reason: "No media devices detected (typical of headless browsers)"
|
|
2569
|
+
});
|
|
2570
|
+
}
|
|
2571
|
+
if (mediaDevices.supported && (mediaDevices.videoInputs ?? 0) > 0 && mediaDevices.audioInputs === 0) {
|
|
2572
|
+
detections.push({
|
|
2573
|
+
category: "bot",
|
|
2574
|
+
score: 0.4,
|
|
2575
|
+
confidence: 0.5,
|
|
2576
|
+
reason: "Has video devices but no audio devices (unusual configuration)"
|
|
2577
|
+
});
|
|
2578
|
+
}
|
|
2579
|
+
if (webrtcInfo.hasLocalIP === false && !webrtcInfo.localIPError) {
|
|
2580
|
+
detections.push({
|
|
2581
|
+
category: "headless",
|
|
2582
|
+
score: 0.4,
|
|
2583
|
+
confidence: 0.5,
|
|
2584
|
+
reason: "No local IP addresses detected via WebRTC"
|
|
2585
|
+
});
|
|
2586
|
+
}
|
|
2587
|
+
return detections;
|
|
2588
|
+
}
|
|
2589
|
+
function analyzeSpeechAPI(speechInfo) {
|
|
2590
|
+
if (!speechInfo || !speechInfo.supported) return [];
|
|
2591
|
+
const detections = [];
|
|
2592
|
+
const totalVoices = speechInfo.totalVoices ?? 0;
|
|
2593
|
+
if (totalVoices === 0) {
|
|
2594
|
+
detections.push({
|
|
2595
|
+
category: "headless",
|
|
2596
|
+
score: 0.6,
|
|
2597
|
+
confidence: 0.7,
|
|
2598
|
+
reason: "No speech synthesis voices available"
|
|
2599
|
+
});
|
|
2600
|
+
}
|
|
2601
|
+
if (totalVoices > 0 && totalVoices < 5) {
|
|
2602
|
+
detections.push({
|
|
2603
|
+
category: "headless",
|
|
2604
|
+
score: 0.3,
|
|
2605
|
+
confidence: 0.4,
|
|
2606
|
+
reason: `Very few speech voices available (${totalVoices})`
|
|
2607
|
+
});
|
|
2608
|
+
}
|
|
2609
|
+
if (speechInfo.localVoices === 0 && totalVoices > 0) {
|
|
2610
|
+
detections.push({
|
|
2611
|
+
category: "bot",
|
|
2612
|
+
score: 0.3,
|
|
2613
|
+
confidence: 0.4,
|
|
2614
|
+
reason: "No local speech synthesis voices"
|
|
2615
|
+
});
|
|
2616
|
+
}
|
|
2617
|
+
return detections;
|
|
2618
|
+
}
|
|
2619
|
+
function analyzeWorkerConsistency(workerConsistency) {
|
|
2620
|
+
if (!workerConsistency || !workerConsistency.supported) return [];
|
|
2621
|
+
const detections = [];
|
|
2622
|
+
if (!workerConsistency.consistent && (workerConsistency.mismatchCount ?? 0) > 0) {
|
|
2623
|
+
const score = Math.min(0.9, 0.3 + (workerConsistency.mismatchCount ?? 0) * 0.15);
|
|
2624
|
+
detections.push({
|
|
2625
|
+
category: "bot",
|
|
2626
|
+
score,
|
|
2627
|
+
confidence: 0.85,
|
|
2628
|
+
reason: `Worker/main thread mismatch detected: ${(workerConsistency.mismatches ?? []).join(", ")}`
|
|
2629
|
+
});
|
|
2630
|
+
}
|
|
2631
|
+
return detections;
|
|
2632
|
+
}
|
|
2633
|
+
function analyzeCSSMediaQueries(cssMedia, signals) {
|
|
2634
|
+
if (!cssMedia || !cssMedia.supported) return [];
|
|
2635
|
+
const detections = [];
|
|
2636
|
+
const maxTouch = signals.environmental?.navigator?.maxTouchPoints ?? 0;
|
|
2637
|
+
if (cssMedia.pointer === "coarse" && maxTouch === 0) {
|
|
2638
|
+
detections.push({
|
|
2639
|
+
category: "bot",
|
|
2640
|
+
score: 0.5,
|
|
2641
|
+
confidence: 0.6,
|
|
2642
|
+
reason: "CSS reports coarse pointer but no touch support"
|
|
2643
|
+
});
|
|
2644
|
+
}
|
|
2645
|
+
if (cssMedia.hover === false && cssMedia.pointer === "fine") {
|
|
2646
|
+
detections.push({
|
|
2647
|
+
category: "bot",
|
|
2648
|
+
score: 0.3,
|
|
2649
|
+
confidence: 0.4,
|
|
2650
|
+
reason: "Fine pointer reported but no hover capability"
|
|
2651
|
+
});
|
|
2652
|
+
}
|
|
2653
|
+
return detections;
|
|
2654
|
+
}
|
|
2655
|
+
function analyzeFonts(fontsInfo, userAgent) {
|
|
2656
|
+
if (!fontsInfo || !fontsInfo.supported) return [];
|
|
2657
|
+
const detections = [];
|
|
2658
|
+
const count = fontsInfo.count ?? 0;
|
|
2659
|
+
if (count < 3) {
|
|
2660
|
+
detections.push({
|
|
2661
|
+
category: "headless",
|
|
2662
|
+
score: 0.5,
|
|
2663
|
+
confidence: 0.5,
|
|
2664
|
+
reason: `Very few fonts detected (${count})`
|
|
2665
|
+
});
|
|
2666
|
+
}
|
|
2667
|
+
const ua = (userAgent || "").toLowerCase();
|
|
2668
|
+
if (ua.includes("windows") && fontsInfo.hasSegoeUI === false && count > 5) {
|
|
2669
|
+
detections.push({
|
|
2670
|
+
category: "bot",
|
|
2671
|
+
score: 0.5,
|
|
2672
|
+
confidence: 0.6,
|
|
2673
|
+
reason: "Windows UA but Segoe UI font not detected"
|
|
2674
|
+
});
|
|
2675
|
+
}
|
|
2676
|
+
if ((ua.includes("mac os x") || ua.includes("macintosh")) && fontsInfo.hasSFPro === false && !ua.includes("10_15") && !ua.includes("10_14") && count > 5) {
|
|
2677
|
+
detections.push({
|
|
2678
|
+
category: "bot",
|
|
2679
|
+
score: 0.3,
|
|
2680
|
+
confidence: 0.4,
|
|
2681
|
+
reason: "Modern macOS UA but SF Pro font not detected"
|
|
2682
|
+
});
|
|
2683
|
+
}
|
|
2684
|
+
if (ua.includes("linux") && !ua.includes("android") && fontsInfo.hasDejaVuSans === false && count > 5) {
|
|
2685
|
+
detections.push({
|
|
2686
|
+
category: "bot",
|
|
2687
|
+
score: 0.4,
|
|
2688
|
+
confidence: 0.5,
|
|
2689
|
+
reason: "Linux UA but DejaVu Sans font not detected"
|
|
2690
|
+
});
|
|
2691
|
+
}
|
|
2692
|
+
return detections;
|
|
2693
|
+
}
|
|
2694
|
+
var PERMISSION_API_KEYS = [
|
|
2695
|
+
"hasPermissionsAPI",
|
|
2696
|
+
"hasClipboard",
|
|
2697
|
+
"hasShare",
|
|
2698
|
+
"hasCredentials",
|
|
2699
|
+
"hasBluetooth",
|
|
2700
|
+
"hasUsb",
|
|
2701
|
+
"hasSerial",
|
|
2702
|
+
"hasHid",
|
|
2703
|
+
"hasXR",
|
|
2704
|
+
"hasGeolocation",
|
|
2705
|
+
"hasMIDI"
|
|
2706
|
+
];
|
|
2707
|
+
function analyzePermissions(permissionsInfo) {
|
|
2708
|
+
if (!permissionsInfo || !permissionsInfo.supported) return [];
|
|
2709
|
+
const detections = [];
|
|
2710
|
+
const availableApis = PERMISSION_API_KEYS.filter((key) => permissionsInfo[key] === true).length;
|
|
2711
|
+
if (availableApis < 3) {
|
|
2712
|
+
detections.push({
|
|
2713
|
+
category: "headless",
|
|
2714
|
+
score: 0.4,
|
|
2715
|
+
confidence: 0.5,
|
|
2716
|
+
reason: `Very few navigator APIs available (${availableApis})`
|
|
2717
|
+
});
|
|
2718
|
+
}
|
|
2719
|
+
return detections;
|
|
2720
|
+
}
|
|
2721
|
+
function analyzeDOMRect(domRectInfo) {
|
|
2722
|
+
if (!domRectInfo || !domRectInfo.supported) return [];
|
|
2723
|
+
const detections = [];
|
|
2724
|
+
if (domRectInfo.rectAWidth === 0 || domRectInfo.rectBWidth === 0) {
|
|
2725
|
+
detections.push({
|
|
2726
|
+
category: "headless",
|
|
2727
|
+
score: 0.6,
|
|
2728
|
+
confidence: 0.7,
|
|
2729
|
+
reason: "DOMRect rendering returned zero-width elements"
|
|
2730
|
+
});
|
|
2731
|
+
}
|
|
2732
|
+
if (domRectInfo.rectAWidth !== void 0 && domRectInfo.rectBWidth !== void 0 && domRectInfo.rangeWidth !== void 0 && domRectInfo.rectAWidth === Math.floor(domRectInfo.rectAWidth) && domRectInfo.rectBWidth === Math.floor(domRectInfo.rectBWidth) && domRectInfo.rangeWidth === Math.floor(domRectInfo.rangeWidth)) {
|
|
2733
|
+
detections.push({
|
|
2734
|
+
category: "bot",
|
|
2735
|
+
score: 0.3,
|
|
2736
|
+
confidence: 0.4,
|
|
2737
|
+
reason: "DOMRect measurements are all exact integers (unusual)"
|
|
2738
|
+
});
|
|
2739
|
+
}
|
|
2740
|
+
return detections;
|
|
2741
|
+
}
|
|
2742
|
+
function analyzeAdvancedSignals(signals, userAgent) {
|
|
2743
|
+
const detections = [];
|
|
2744
|
+
const env = signals.environmental ?? {};
|
|
2745
|
+
if (env.webrtcInfo) detections.push(...analyzeWebRTC(env.webrtcInfo));
|
|
2746
|
+
if (env.speechInfo) detections.push(...analyzeSpeechAPI(env.speechInfo));
|
|
2747
|
+
if (env.workerConsistency) detections.push(...analyzeWorkerConsistency(env.workerConsistency));
|
|
2748
|
+
if (env.cssMediaQueries) detections.push(...analyzeCSSMediaQueries(env.cssMediaQueries, signals));
|
|
2749
|
+
if (env.fontsInfo) detections.push(...analyzeFonts(env.fontsInfo, userAgent));
|
|
2750
|
+
if (env.permissionsInfo) detections.push(...analyzePermissions(env.permissionsInfo));
|
|
2751
|
+
if (env.domRectFingerprint) detections.push(...analyzeDOMRect(env.domRectFingerprint));
|
|
2752
|
+
return detections;
|
|
2753
|
+
}
|
|
2754
|
+
|
|
2755
|
+
// src/detection/engine.ts
|
|
2756
|
+
var DetectionEngine = class {
|
|
2757
|
+
constructor(options = {}) {
|
|
2758
|
+
this.weights = options.weights ?? DEFAULT_WEIGHTS;
|
|
2759
|
+
this.requirePoW = options.requirePoW ?? true;
|
|
2760
|
+
this.fingerprintStore = options.fingerprintStore ?? new InMemoryFingerprintStore();
|
|
2761
|
+
this.rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter2();
|
|
2762
|
+
}
|
|
2763
|
+
/** Score `signals` for the given request context and return a verdict. */
|
|
2764
|
+
score(signals, context) {
|
|
2765
|
+
const { ip, siteKey, userAgent } = context;
|
|
2766
|
+
const headers = context.headers ?? {};
|
|
2767
|
+
const detections = [];
|
|
2768
|
+
if (context.extraDetections) detections.push(...context.extraDetections);
|
|
2769
|
+
const pow = context.pow;
|
|
2770
|
+
if (pow && pow.provided) {
|
|
2771
|
+
if (pow.valid === false) {
|
|
2772
|
+
detections.push({
|
|
2773
|
+
category: "bot",
|
|
2774
|
+
score: 0.7,
|
|
2775
|
+
confidence: 0.8,
|
|
2776
|
+
reason: `PoW verification failed: ${pow.reason ?? "unknown"}`
|
|
2777
|
+
});
|
|
2778
|
+
}
|
|
2779
|
+
if (pow.valid && pow.nonce) {
|
|
2780
|
+
const clientNonce = signals.meta?.challengeNonce;
|
|
2781
|
+
if (!clientNonce || clientNonce !== pow.nonce) {
|
|
2782
|
+
detections.push({
|
|
2783
|
+
category: "bot",
|
|
2784
|
+
score: 0.9,
|
|
2785
|
+
confidence: 0.9,
|
|
2786
|
+
reason: "Challenge nonce mismatch (signals not bound to challenge)"
|
|
2787
|
+
});
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2790
|
+
if (pow.valid && pow.serverElapsed !== void 0 && pow.serverElapsed < 1500) {
|
|
2791
|
+
detections.push({
|
|
2792
|
+
category: "bot",
|
|
2793
|
+
score: 0.8,
|
|
2794
|
+
confidence: 0.85,
|
|
2795
|
+
reason: `Challenge solved too fast (${pow.serverElapsed}ms server-side)`
|
|
2796
|
+
});
|
|
2797
|
+
}
|
|
2798
|
+
} else if (this.requirePoW) {
|
|
2799
|
+
detections.push({
|
|
2800
|
+
category: "bot",
|
|
2801
|
+
score: 0.9,
|
|
2802
|
+
confidence: 0.95,
|
|
2803
|
+
reason: "No PoW solution provided"
|
|
2804
|
+
});
|
|
2805
|
+
}
|
|
2806
|
+
detections.push(
|
|
2807
|
+
...detectVisionAI(signals),
|
|
2808
|
+
...detectHeadless(signals, userAgent),
|
|
2809
|
+
...detectAutomation(signals),
|
|
2810
|
+
...detectCDP(signals),
|
|
2811
|
+
...detectBehavioral(signals),
|
|
2812
|
+
...detectTouchAuthenticity(signals, userAgent),
|
|
2813
|
+
...detectSensorEntropy(signals, userAgent),
|
|
2814
|
+
...detectTouchKinematics(signals),
|
|
2815
|
+
...detectFingerprint(signals, ip, siteKey, this.fingerprintStore),
|
|
2816
|
+
...detectRateAbuse(ip, siteKey, this.rateLimiter)
|
|
2817
|
+
);
|
|
2818
|
+
if (isDatacenterIP2(ip)) {
|
|
2819
|
+
detections.push({
|
|
2820
|
+
category: "datacenter",
|
|
2821
|
+
score: 0.6,
|
|
2822
|
+
confidence: 0.8,
|
|
2823
|
+
reason: "Request from known datacenter IP range"
|
|
2824
|
+
});
|
|
2825
|
+
}
|
|
2826
|
+
detections.push(...analyzeHeaders(headers));
|
|
2827
|
+
detections.push(...checkBrowserConsistency(userAgent, signals));
|
|
2828
|
+
if (context.ja3Hash) {
|
|
2829
|
+
detections.push(...checkJA3Fingerprint(context.ja3Hash));
|
|
2830
|
+
}
|
|
2831
|
+
if (context.trustedJA4Headers && context.trustedJA4Headers.length > 0) {
|
|
2832
|
+
const ja4 = readJA4FromHeaders(headers, context.trustedJA4Headers);
|
|
2833
|
+
if (ja4) detections.push(...checkJA4Fingerprint(ja4));
|
|
2834
|
+
}
|
|
2835
|
+
if (signals.formAnalysis) {
|
|
2836
|
+
detections.push(...analyzeFormInteraction(signals.formAnalysis));
|
|
2837
|
+
}
|
|
2838
|
+
detections.push(...analyzeAdvancedSignals(signals, userAgent));
|
|
2839
|
+
const categoryScores = calculateCategoryScores(detections, this.weights);
|
|
2840
|
+
const score = calculateFinalScore(categoryScores, this.weights);
|
|
2841
|
+
return {
|
|
2842
|
+
success: score < 0.5,
|
|
2843
|
+
score,
|
|
2844
|
+
recommendation: recommend(score),
|
|
2845
|
+
categoryScores,
|
|
2846
|
+
detections,
|
|
2847
|
+
timestamp: Math.floor(Date.now() / 1e3)
|
|
2848
|
+
};
|
|
2849
|
+
}
|
|
2850
|
+
};
|
|
2851
|
+
|
|
2852
|
+
// src/captcha/service.ts
|
|
2853
|
+
import { createHash as createHash4 } from "crypto";
|
|
2854
|
+
|
|
2855
|
+
// src/captcha/secret.ts
|
|
2856
|
+
var INSECURE_DEFAULT_SECRET = "dev-secret-change-in-production";
|
|
2857
|
+
function resolveSecret(secret) {
|
|
2858
|
+
const isProd = process.env.NODE_ENV === "production";
|
|
2859
|
+
if (!secret || secret.length === 0) {
|
|
2860
|
+
if (isProd) {
|
|
2861
|
+
throw new Error(
|
|
2862
|
+
"WebDecoy captcha: a `secret` is required in production. Set a strong random value (e.g. `openssl rand -hex 32`)."
|
|
2863
|
+
);
|
|
2864
|
+
}
|
|
2865
|
+
return INSECURE_DEFAULT_SECRET;
|
|
2866
|
+
}
|
|
2867
|
+
if (isProd && secret === INSECURE_DEFAULT_SECRET) {
|
|
2868
|
+
throw new Error(
|
|
2869
|
+
"WebDecoy captcha: the default development secret cannot be used in production. Set a strong random `secret`."
|
|
2870
|
+
);
|
|
2871
|
+
}
|
|
2872
|
+
return secret;
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2875
|
+
// src/captcha/pow.ts
|
|
2876
|
+
import { createHash as createHash2, createHmac, randomBytes } from "crypto";
|
|
2877
|
+
var EXPIRATION_MS = 5 * 60 * 1e3;
|
|
2878
|
+
var InMemoryChallengeStore = class {
|
|
2879
|
+
constructor() {
|
|
2880
|
+
this.challenges = /* @__PURE__ */ new Map();
|
|
2881
|
+
this.usedSolutions = /* @__PURE__ */ new Set();
|
|
2882
|
+
}
|
|
2883
|
+
put(challenge) {
|
|
2884
|
+
this.challenges.set(challenge.id, challenge);
|
|
2885
|
+
if (Math.random() < 0.1) this.cleanup();
|
|
2886
|
+
}
|
|
2887
|
+
get(id) {
|
|
2888
|
+
return this.challenges.get(id);
|
|
2889
|
+
}
|
|
2890
|
+
delete(id) {
|
|
2891
|
+
this.challenges.delete(id);
|
|
2892
|
+
}
|
|
2893
|
+
markSolutionUsed(solutionKey) {
|
|
2894
|
+
if (this.usedSolutions.has(solutionKey)) return false;
|
|
2895
|
+
this.usedSolutions.add(solutionKey);
|
|
2896
|
+
return true;
|
|
2897
|
+
}
|
|
2898
|
+
cleanup() {
|
|
2899
|
+
const now = Date.now();
|
|
2900
|
+
for (const [id, challenge] of this.challenges) {
|
|
2901
|
+
if (now > challenge.expiresAt) this.challenges.delete(id);
|
|
2902
|
+
}
|
|
2903
|
+
if (this.usedSolutions.size > 1e4) this.usedSolutions.clear();
|
|
2904
|
+
}
|
|
2905
|
+
};
|
|
2906
|
+
var PoWManager = class {
|
|
2907
|
+
constructor(options) {
|
|
2908
|
+
this.secret = options.secret;
|
|
2909
|
+
this.store = options.store ?? new InMemoryChallengeStore();
|
|
2910
|
+
this.rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter2();
|
|
2911
|
+
}
|
|
2912
|
+
/** Difficulty scaled by IP reputation and request rate (4..6). */
|
|
2913
|
+
scaleDifficulty(siteKey, ip) {
|
|
2914
|
+
let difficulty = 4;
|
|
2915
|
+
if (isDatacenterIP2(ip)) difficulty = 5;
|
|
2916
|
+
const [exceeded, count] = this.rateLimiter.check(`pow:${siteKey}:${ip}`, 60, 20);
|
|
2917
|
+
if (count > 10) difficulty = Math.min(6, difficulty + 1);
|
|
2918
|
+
if (exceeded) difficulty = 6;
|
|
2919
|
+
return difficulty;
|
|
2920
|
+
}
|
|
2921
|
+
/** Generate and store a signed challenge. */
|
|
2922
|
+
generate(siteKey, ip, difficulty) {
|
|
2923
|
+
const resolvedDifficulty = difficulty ?? this.scaleDifficulty(siteKey, ip);
|
|
2924
|
+
const challengeId = randomBytes(16).toString("hex");
|
|
2925
|
+
const nonce = randomBytes(16).toString("hex");
|
|
2926
|
+
const timestamp = Date.now();
|
|
2927
|
+
const expiresAt = timestamp + EXPIRATION_MS;
|
|
2928
|
+
const challengeData = {
|
|
2929
|
+
id: challengeId,
|
|
2930
|
+
siteKey,
|
|
2931
|
+
timestamp,
|
|
2932
|
+
expiresAt,
|
|
2933
|
+
difficulty: resolvedDifficulty,
|
|
2934
|
+
nonce,
|
|
2935
|
+
prefix: `${challengeId}:${timestamp}:${resolvedDifficulty}`,
|
|
2936
|
+
sig: ""
|
|
2937
|
+
};
|
|
2938
|
+
const { sig: _omit, ...toSign } = challengeData;
|
|
2939
|
+
void _omit;
|
|
2940
|
+
challengeData.sig = createHmac("sha256", this.secret).update(JSON.stringify(toSign)).digest("hex");
|
|
2941
|
+
this.store.put({ ...challengeData, ip, createdAt: timestamp });
|
|
2942
|
+
return challengeData;
|
|
2943
|
+
}
|
|
2944
|
+
/** Verify a submitted solution. `signalsHash` binds it to the signals. */
|
|
2945
|
+
verify(solution, siteKey, signalsHash = null) {
|
|
2946
|
+
const challenge = this.store.get(solution.challengeId);
|
|
2947
|
+
if (!challenge) return { valid: false, reason: "challenge_not_found" };
|
|
2948
|
+
if (Date.now() > challenge.expiresAt) {
|
|
2949
|
+
this.store.delete(solution.challengeId);
|
|
2950
|
+
return { valid: false, reason: "challenge_expired" };
|
|
2951
|
+
}
|
|
2952
|
+
if (challenge.siteKey !== siteKey) {
|
|
2953
|
+
return { valid: false, reason: "site_key_mismatch" };
|
|
2954
|
+
}
|
|
2955
|
+
const solutionKey = `${solution.challengeId}:${solution.nonce}`;
|
|
2956
|
+
const input = signalsHash ? `${challenge.prefix}:${signalsHash}:${solution.nonce}` : `${challenge.prefix}:${solution.nonce}`;
|
|
2957
|
+
const expectedHash = createHash2("sha256").update(input).digest("hex");
|
|
2958
|
+
if (solution.hash !== expectedHash) {
|
|
2959
|
+
return { valid: false, reason: "invalid_hash" };
|
|
2960
|
+
}
|
|
2961
|
+
const target = "0".repeat(challenge.difficulty);
|
|
2962
|
+
if (!solution.hash.startsWith(target)) {
|
|
2963
|
+
return { valid: false, reason: "insufficient_difficulty" };
|
|
2964
|
+
}
|
|
2965
|
+
if (!this.store.markSolutionUsed(solutionKey)) {
|
|
2966
|
+
return { valid: false, reason: "solution_already_used" };
|
|
2967
|
+
}
|
|
2968
|
+
this.store.delete(solution.challengeId);
|
|
2969
|
+
return {
|
|
2970
|
+
valid: true,
|
|
2971
|
+
difficulty: challenge.difficulty,
|
|
2972
|
+
serverElapsed: Date.now() - challenge.createdAt,
|
|
2973
|
+
nonce: challenge.nonce
|
|
2974
|
+
};
|
|
2975
|
+
}
|
|
2976
|
+
};
|
|
2977
|
+
|
|
2978
|
+
// src/captcha/token.ts
|
|
2979
|
+
import { createHash as createHash3, createHmac as createHmac2, timingSafeEqual } from "crypto";
|
|
2980
|
+
var TOKEN_TTL_SECONDS = 300;
|
|
2981
|
+
var InMemoryTokenStore = class {
|
|
2982
|
+
constructor() {
|
|
2983
|
+
this.usedTokens = /* @__PURE__ */ new Set();
|
|
2984
|
+
}
|
|
2985
|
+
markUsed(sig) {
|
|
2986
|
+
if (this.usedTokens.has(sig)) return false;
|
|
2987
|
+
this.usedTokens.add(sig);
|
|
2988
|
+
if (Math.random() < 0.1 && this.usedTokens.size > 5e4) this.usedTokens.clear();
|
|
2989
|
+
return true;
|
|
2990
|
+
}
|
|
2991
|
+
isUsed(sig) {
|
|
2992
|
+
return this.usedTokens.has(sig);
|
|
2993
|
+
}
|
|
2994
|
+
};
|
|
2995
|
+
var TokenManager = class {
|
|
2996
|
+
constructor(options) {
|
|
2997
|
+
this.secret = options.secret;
|
|
2998
|
+
this.store = options.store ?? new InMemoryTokenStore();
|
|
2999
|
+
}
|
|
3000
|
+
/** Issue a signed, IP-bound token for a passing request. */
|
|
3001
|
+
issue(ip, siteKey, score) {
|
|
3002
|
+
const data = {
|
|
3003
|
+
site_key: siteKey,
|
|
3004
|
+
timestamp: Math.floor(Date.now() / 1e3),
|
|
3005
|
+
score: Math.round(score * 1e3) / 1e3,
|
|
3006
|
+
ip_hash: createHash3("sha256").update(ip).digest("hex").slice(0, 8)
|
|
3007
|
+
};
|
|
3008
|
+
const payload = JSON.stringify(data, Object.keys(data).sort());
|
|
3009
|
+
data.sig = createHmac2("sha256", this.secret).update(payload).digest("hex");
|
|
3010
|
+
return Buffer.from(JSON.stringify(data)).toString("base64url");
|
|
3011
|
+
}
|
|
3012
|
+
/** Verify a token: signature, expiry, replay, and optional IP binding. */
|
|
3013
|
+
verify(token, ip = null) {
|
|
3014
|
+
let decoded;
|
|
3015
|
+
try {
|
|
3016
|
+
decoded = JSON.parse(Buffer.from(token, "base64url").toString());
|
|
3017
|
+
} catch (e) {
|
|
3018
|
+
return { valid: false, reason: e instanceof Error ? e.message : "invalid_token" };
|
|
3019
|
+
}
|
|
3020
|
+
if (Date.now() / 1e3 - decoded.timestamp > TOKEN_TTL_SECONDS) {
|
|
3021
|
+
return { valid: false, reason: "expired" };
|
|
3022
|
+
}
|
|
3023
|
+
const sig = decoded.sig;
|
|
3024
|
+
if (!sig) return { valid: false, reason: "invalid_signature" };
|
|
3025
|
+
delete decoded.sig;
|
|
3026
|
+
const payload = JSON.stringify(decoded, Object.keys(decoded).sort());
|
|
3027
|
+
const expectedSig = createHmac2("sha256", this.secret).update(payload).digest("hex");
|
|
3028
|
+
const sigBuf = Buffer.from(sig);
|
|
3029
|
+
const expectedBuf = Buffer.from(expectedSig);
|
|
3030
|
+
if (sigBuf.length !== expectedBuf.length || !timingSafeEqual(sigBuf, expectedBuf)) {
|
|
3031
|
+
return { valid: false, reason: "invalid_signature" };
|
|
3032
|
+
}
|
|
3033
|
+
if (this.store.isUsed(sig)) {
|
|
3034
|
+
return { valid: false, reason: "token_already_used" };
|
|
3035
|
+
}
|
|
3036
|
+
if (ip) {
|
|
3037
|
+
const expectedIpHash = createHash3("sha256").update(ip).digest("hex").slice(0, 8);
|
|
3038
|
+
if (decoded.ip_hash !== expectedIpHash) {
|
|
3039
|
+
return { valid: false, reason: "ip_mismatch" };
|
|
3040
|
+
}
|
|
3041
|
+
}
|
|
3042
|
+
this.store.markUsed(sig);
|
|
3043
|
+
return {
|
|
3044
|
+
valid: true,
|
|
3045
|
+
site_key: decoded.site_key,
|
|
3046
|
+
timestamp: decoded.timestamp,
|
|
3047
|
+
score: decoded.score,
|
|
3048
|
+
ip_hash: decoded.ip_hash
|
|
3049
|
+
};
|
|
3050
|
+
}
|
|
3051
|
+
};
|
|
3052
|
+
|
|
3053
|
+
// src/captcha/service.ts
|
|
3054
|
+
var Captcha = class {
|
|
3055
|
+
constructor(options = {}) {
|
|
3056
|
+
const secret = resolveSecret(options.secret);
|
|
3057
|
+
const rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter2();
|
|
3058
|
+
const fingerprintStore = options.fingerprintStore ?? new InMemoryFingerprintStore();
|
|
3059
|
+
this.engine = new DetectionEngine({
|
|
3060
|
+
weights: options.weights,
|
|
3061
|
+
requirePoW: true,
|
|
3062
|
+
fingerprintStore,
|
|
3063
|
+
rateLimiter
|
|
3064
|
+
});
|
|
3065
|
+
this.pow = new PoWManager({ secret, store: options.challengeStore, rateLimiter });
|
|
3066
|
+
this.tokens = new TokenManager({ secret, store: options.tokenStore });
|
|
3067
|
+
this.trustedJA4Headers = options.trustedJA4Headers ?? [];
|
|
3068
|
+
}
|
|
3069
|
+
/** Issue a PoW challenge for the client to solve (difficulty auto-scaled). */
|
|
3070
|
+
issueChallenge(siteKey, ip, difficulty) {
|
|
3071
|
+
return this.pow.generate(siteKey, ip, difficulty);
|
|
3072
|
+
}
|
|
3073
|
+
/**
|
|
3074
|
+
* Verify a submission: checks the signals commitment, verifies PoW, scores the
|
|
3075
|
+
* signals, and issues a session token on success. Mirrors `runVerification`.
|
|
3076
|
+
*/
|
|
3077
|
+
verify(input) {
|
|
3078
|
+
const { siteKey, ip, userAgent } = input;
|
|
3079
|
+
const headers = input.headers ?? {};
|
|
3080
|
+
let signals = input.signals ?? {};
|
|
3081
|
+
const extraDetections = [];
|
|
3082
|
+
const clientSignalsHash = input.powSolution?.signalsHash ?? null;
|
|
3083
|
+
if (input.signalsJson && clientSignalsHash) {
|
|
3084
|
+
const computed = createHash4("sha256").update(input.signalsJson).digest("hex");
|
|
3085
|
+
if (computed !== clientSignalsHash) {
|
|
3086
|
+
extraDetections.push({
|
|
3087
|
+
category: "bot",
|
|
3088
|
+
score: 0.95,
|
|
3089
|
+
confidence: 0.95,
|
|
3090
|
+
reason: "Signals tampered after PoW (signalsHash mismatch)"
|
|
3091
|
+
});
|
|
3092
|
+
}
|
|
3093
|
+
try {
|
|
3094
|
+
signals = JSON.parse(input.signalsJson);
|
|
3095
|
+
} catch {
|
|
3096
|
+
}
|
|
3097
|
+
}
|
|
3098
|
+
if (input.powTiming) {
|
|
3099
|
+
signals = { ...signals, temporal: { ...signals.temporal ?? {}, pow: input.powTiming } };
|
|
3100
|
+
}
|
|
3101
|
+
let pow;
|
|
3102
|
+
if (input.powSolution && input.powSolution.challengeId) {
|
|
3103
|
+
const result = this.pow.verify(input.powSolution, siteKey, clientSignalsHash);
|
|
3104
|
+
pow = {
|
|
3105
|
+
provided: true,
|
|
3106
|
+
valid: result.valid,
|
|
3107
|
+
reason: result.reason,
|
|
3108
|
+
serverElapsed: result.serverElapsed,
|
|
3109
|
+
nonce: result.nonce
|
|
3110
|
+
};
|
|
3111
|
+
} else {
|
|
3112
|
+
pow = { provided: false };
|
|
3113
|
+
}
|
|
3114
|
+
const verdict = this.engine.score(signals, {
|
|
3115
|
+
ip,
|
|
3116
|
+
siteKey,
|
|
3117
|
+
userAgent,
|
|
3118
|
+
headers,
|
|
3119
|
+
ja3Hash: input.ja3Hash ?? null,
|
|
3120
|
+
trustedJA4Headers: this.trustedJA4Headers,
|
|
3121
|
+
pow,
|
|
3122
|
+
extraDetections
|
|
3123
|
+
});
|
|
3124
|
+
const token = verdict.success ? this.tokens.issue(ip, siteKey, verdict.score) : null;
|
|
3125
|
+
return { ...verdict, token };
|
|
3126
|
+
}
|
|
3127
|
+
/** Invisible-mode scoring — same pipeline, returns a compact result + action. */
|
|
3128
|
+
score(input) {
|
|
3129
|
+
const result = this.verify(input);
|
|
3130
|
+
return {
|
|
3131
|
+
success: result.success,
|
|
3132
|
+
score: result.score,
|
|
3133
|
+
token: result.token,
|
|
3134
|
+
action: input.action ?? "",
|
|
3135
|
+
recommendation: result.recommendation
|
|
3136
|
+
};
|
|
3137
|
+
}
|
|
3138
|
+
/** Verify a previously issued token (single-use, optionally IP-bound). */
|
|
3139
|
+
verifyToken(token, ip = null) {
|
|
3140
|
+
return this.tokens.verify(token, ip);
|
|
3141
|
+
}
|
|
3142
|
+
};
|
|
3143
|
+
|
|
3144
|
+
// src/captcha/http.ts
|
|
3145
|
+
var JSON_HEADERS = { "content-type": "application/json" };
|
|
3146
|
+
function createCaptchaEndpoints(options = {}) {
|
|
3147
|
+
const { basePath = "/__webdecoy", ...captchaOptions } = options;
|
|
3148
|
+
const captcha = new Captcha(captchaOptions);
|
|
3149
|
+
const base = basePath.replace(/\/$/, "");
|
|
3150
|
+
function route(pathname) {
|
|
3151
|
+
if (pathname === base) return "/";
|
|
3152
|
+
if (pathname.startsWith(base + "/")) return pathname.slice(base.length);
|
|
3153
|
+
return null;
|
|
3154
|
+
}
|
|
3155
|
+
function json(status, body) {
|
|
3156
|
+
return { status, headers: { ...JSON_HEADERS }, body };
|
|
3157
|
+
}
|
|
3158
|
+
async function handle(req) {
|
|
3159
|
+
const sub = route(req.pathname);
|
|
3160
|
+
if (sub === null) return null;
|
|
3161
|
+
const method = req.method.toUpperCase();
|
|
3162
|
+
const userAgent = req.headers["user-agent"] ?? "";
|
|
3163
|
+
const ja3Hash = req.headers["x-ja3-hash"] ?? null;
|
|
3164
|
+
if (sub === "/challenge" && method === "GET") {
|
|
3165
|
+
const siteKey = req.query.siteKey ?? "default";
|
|
3166
|
+
return json(200, captcha.issueChallenge(siteKey, req.ip));
|
|
3167
|
+
}
|
|
3168
|
+
if (sub === "/verify" && method === "POST") {
|
|
3169
|
+
const b = req.body ?? {};
|
|
3170
|
+
const result = captcha.verify({
|
|
3171
|
+
siteKey: b.siteKey ?? "default",
|
|
3172
|
+
ip: req.ip,
|
|
3173
|
+
userAgent,
|
|
3174
|
+
headers: req.headers,
|
|
3175
|
+
signals: b.signals,
|
|
3176
|
+
powSolution: b.powSolution ?? null,
|
|
3177
|
+
signalsJson: b.signalsJson ?? null,
|
|
3178
|
+
powTiming: b.powTiming ?? null,
|
|
3179
|
+
ja3Hash
|
|
3180
|
+
});
|
|
3181
|
+
return json(200, result);
|
|
3182
|
+
}
|
|
3183
|
+
if (sub === "/score" && method === "POST") {
|
|
3184
|
+
const b = req.body ?? {};
|
|
3185
|
+
const result = captcha.score({
|
|
3186
|
+
siteKey: b.siteKey ?? "default",
|
|
3187
|
+
ip: req.ip,
|
|
3188
|
+
userAgent,
|
|
3189
|
+
headers: req.headers,
|
|
3190
|
+
signals: b.signals,
|
|
3191
|
+
powSolution: b.powSolution ?? null,
|
|
3192
|
+
signalsJson: b.signalsJson ?? null,
|
|
3193
|
+
powTiming: b.powTiming ?? null,
|
|
3194
|
+
ja3Hash,
|
|
3195
|
+
action: b.action
|
|
3196
|
+
});
|
|
3197
|
+
return json(200, result);
|
|
3198
|
+
}
|
|
3199
|
+
if (sub === "/token/verify" && method === "POST") {
|
|
3200
|
+
const b = req.body ?? {};
|
|
3201
|
+
if (!b.token) return json(400, { valid: false, reason: "missing_token" });
|
|
3202
|
+
return json(200, captcha.verifyToken(b.token, req.ip));
|
|
3203
|
+
}
|
|
3204
|
+
return json(404, { error: "not_found" });
|
|
3205
|
+
}
|
|
3206
|
+
return { captcha, basePath: base, handle };
|
|
3207
|
+
}
|
|
1298
3208
|
export {
|
|
3209
|
+
Captcha,
|
|
3210
|
+
DEFAULT_WEIGHTS,
|
|
3211
|
+
DetectionEngine,
|
|
1299
3212
|
FilterRule,
|
|
3213
|
+
InMemoryChallengeStore,
|
|
3214
|
+
InMemoryFingerprintStore,
|
|
3215
|
+
InMemoryRateLimiter2 as InMemoryRateLimiter,
|
|
3216
|
+
InMemoryTokenStore,
|
|
3217
|
+
PoWManager,
|
|
1300
3218
|
RateLimitRule,
|
|
1301
3219
|
RuleEngine,
|
|
3220
|
+
TokenManager,
|
|
1302
3221
|
WebDecoy,
|
|
3222
|
+
calculateCategoryScores,
|
|
3223
|
+
calculateFinalScore,
|
|
3224
|
+
createCaptchaEndpoints,
|
|
1303
3225
|
filter,
|
|
1304
|
-
|
|
3226
|
+
isDatacenterIP2 as isDatacenterIP,
|
|
3227
|
+
isMobileUA,
|
|
3228
|
+
parseUserAgent,
|
|
3229
|
+
rateLimit,
|
|
3230
|
+
recommend,
|
|
3231
|
+
resolveSecret
|
|
1305
3232
|
};
|