@webdecoy/node 0.2.1 → 0.4.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 +789 -1
- package/dist/index.d.ts +789 -1
- package/dist/index.js +2071 -2
- package/dist/index.mjs +2049 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -73,6 +73,23 @@ interface FilterConfig {
|
|
|
73
73
|
/** Dry run mode: log violations but don't block */
|
|
74
74
|
dryRun?: boolean;
|
|
75
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* Configuration for tripwire (honeypot-path) rules
|
|
78
|
+
*/
|
|
79
|
+
interface TripwireConfig {
|
|
80
|
+
/** Exact hidden honeypot paths (e.g. a honeytoken path or `/admin-backup.zip`). */
|
|
81
|
+
paths?: string[];
|
|
82
|
+
/** Path prefixes treated as tripwires (e.g. `/.git/`). */
|
|
83
|
+
prefixes?: string[];
|
|
84
|
+
/** Regex patterns for tripwire paths. */
|
|
85
|
+
patterns?: RegExp[];
|
|
86
|
+
/** Include the built-in scanner/scraper bait paths. Default `true`. */
|
|
87
|
+
includeDefaults?: boolean;
|
|
88
|
+
/** Action when a tripwire is hit: 'DENY' (default) or 'THROTTLE'. */
|
|
89
|
+
action?: 'DENY' | 'THROTTLE';
|
|
90
|
+
/** Dry run mode: log the violation but don't block. */
|
|
91
|
+
dryRun?: boolean;
|
|
92
|
+
}
|
|
76
93
|
/**
|
|
77
94
|
* A violation event recorded when a rule triggers
|
|
78
95
|
*/
|
|
@@ -447,6 +464,75 @@ declare class FilterRule implements Rule {
|
|
|
447
464
|
evaluate(context: RuleContext): RuleResult;
|
|
448
465
|
}
|
|
449
466
|
|
|
467
|
+
/**
|
|
468
|
+
* Tripwire Rule (F4 — deception layer)
|
|
469
|
+
*
|
|
470
|
+
* Deterministic, zero-false-positive bot detection: a request for a hidden
|
|
471
|
+
* honeypot path (a "tripwire") that a real user can never reach — because it is
|
|
472
|
+
* only exposed as an invisible link, listed in robots.txt `Disallow`, or is a
|
|
473
|
+
* scanner-bait path no human ever types — is, by construction, automated.
|
|
474
|
+
*
|
|
475
|
+
* Unlike fingerprinting (which a stealth tool like botasaurus is purpose-built
|
|
476
|
+
* to defeat), a tripwire detects *intent* — going where a human cannot — which
|
|
477
|
+
* cannot be spoofed away by a better browser fingerprint.
|
|
478
|
+
*
|
|
479
|
+
* Implemented as a {@link Rule} so it flows through the existing
|
|
480
|
+
* DENY -> block -> violation-report pipeline with no middleware changes.
|
|
481
|
+
*/
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Common scanner/scraper bait paths that no legitimate user ever requests.
|
|
485
|
+
* Requesting any of these is a strong automated-intent signal on its own.
|
|
486
|
+
*/
|
|
487
|
+
declare const DEFAULT_TRIPWIRE_PATHS: readonly string[];
|
|
488
|
+
declare class TripwireRule implements Rule {
|
|
489
|
+
readonly name = "tripwire";
|
|
490
|
+
private readonly exact;
|
|
491
|
+
private readonly prefixes;
|
|
492
|
+
private readonly patterns;
|
|
493
|
+
private readonly action;
|
|
494
|
+
private readonly dryRun;
|
|
495
|
+
constructor(config?: TripwireConfig);
|
|
496
|
+
evaluate(context: RuleContext): RuleResult;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Honeytoken generator (F4 — deception layer)
|
|
501
|
+
*
|
|
502
|
+
* Produces a hidden decoy link and the tripwire path it points at. Embed the
|
|
503
|
+
* link in a page (it is visually hidden and marked nofollow/aria-hidden, so a
|
|
504
|
+
* real user never sees or clicks it); register the path with a {@link
|
|
505
|
+
* TripwireRule}. Any client that parses the HTML and follows links — i.e. a
|
|
506
|
+
* scraper/crawler — requests the path and is deterministically flagged, while
|
|
507
|
+
* genuine users are never affected.
|
|
508
|
+
*/
|
|
509
|
+
interface HoneytokenOptions {
|
|
510
|
+
/** Base path under which honeytoken tripwires are generated. Default `/__wd`. */
|
|
511
|
+
basePath?: string;
|
|
512
|
+
/** Fixed token (else a random one is generated). */
|
|
513
|
+
token?: string;
|
|
514
|
+
/** Visually-hidden link text. Default `.`. */
|
|
515
|
+
text?: string;
|
|
516
|
+
}
|
|
517
|
+
interface Honeytoken {
|
|
518
|
+
/** The tripwire path to register with a TripwireRule (`tripwire({ paths: [token.path] })`). */
|
|
519
|
+
path: string;
|
|
520
|
+
/** Invisible `<a>` HTML to embed in a page; only a link-following bot requests `path`. */
|
|
521
|
+
linkHtml: string;
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Generate a honeytoken (hidden link + tripwire path).
|
|
525
|
+
*
|
|
526
|
+
* @example
|
|
527
|
+
* ```typescript
|
|
528
|
+
* import { honeytoken, tripwire, WebDecoy } from '@webdecoy/node';
|
|
529
|
+
* const hp = honeytoken();
|
|
530
|
+
* const sdk = new WebDecoy({ rules: [tripwire({ paths: [hp.path] })] });
|
|
531
|
+
* // ...inject hp.linkHtml into your page's HTML
|
|
532
|
+
* ```
|
|
533
|
+
*/
|
|
534
|
+
declare function honeytoken(options?: HoneytokenOptions): Honeytoken;
|
|
535
|
+
|
|
450
536
|
/**
|
|
451
537
|
* Rules Engine - Barrel exports
|
|
452
538
|
*/
|
|
@@ -483,5 +569,707 @@ declare function rateLimit(config: RateLimitConfig): Rule;
|
|
|
483
569
|
* ```
|
|
484
570
|
*/
|
|
485
571
|
declare function filter(config: FilterConfig): Rule;
|
|
572
|
+
/**
|
|
573
|
+
* Factory function to create a tripwire (honeypot-path) rule.
|
|
574
|
+
*
|
|
575
|
+
* Deterministic, zero-false-positive: any request for a hidden honeypot path is
|
|
576
|
+
* automated by construction. Detects intent (going where a human can't), which
|
|
577
|
+
* stealth fingerprint-spoofing (e.g. botasaurus) cannot evade.
|
|
578
|
+
*
|
|
579
|
+
* @example
|
|
580
|
+
* ```typescript
|
|
581
|
+
* import { WebDecoy, tripwire, honeytoken } from '@webdecoy/node';
|
|
582
|
+
*
|
|
583
|
+
* const hp = honeytoken();
|
|
584
|
+
* const sdk = new WebDecoy({
|
|
585
|
+
* rules: [
|
|
586
|
+
* tripwire({ paths: [hp.path] }), // + built-in scanner-bait paths
|
|
587
|
+
* ],
|
|
588
|
+
* });
|
|
589
|
+
* // inject hp.linkHtml into your pages
|
|
590
|
+
* ```
|
|
591
|
+
*/
|
|
592
|
+
declare function tripwire(config?: TripwireConfig): Rule;
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* Detection engine types.
|
|
596
|
+
*
|
|
597
|
+
* The detection engine scores a set of client-collected `Signals` against ~40
|
|
598
|
+
* behavioral, environmental, and fingerprint heuristics and produces a verdict.
|
|
599
|
+
* Ported from the FCaptcha scoring engine so behavior matches the self-hosted
|
|
600
|
+
* server (server.js `runVerification`).
|
|
601
|
+
*
|
|
602
|
+
* Signals originate from an untrusted client, so every field is optional and the
|
|
603
|
+
* detectors fall back to neutral defaults (mirroring the `?? default` pattern in
|
|
604
|
+
* the reference implementation).
|
|
605
|
+
*/
|
|
606
|
+
/** A single triggered heuristic. */
|
|
607
|
+
interface Detection {
|
|
608
|
+
/** Scoring bucket this detection contributes to (see {@link Weights}). */
|
|
609
|
+
category: string;
|
|
610
|
+
/** Likelihood this signal indicates a bot/attack, 0..1. */
|
|
611
|
+
score: number;
|
|
612
|
+
/** Certainty of the score, 0..1, used to weight the per-category aggregate. */
|
|
613
|
+
confidence: number;
|
|
614
|
+
/** Human-readable explanation. */
|
|
615
|
+
reason: string;
|
|
616
|
+
/** Optional structured detail (e.g. keystroke-cadence metrics). */
|
|
617
|
+
details?: Record<string, unknown>;
|
|
618
|
+
}
|
|
619
|
+
/** Per-category aggregated scores (0..1), keyed by category name. */
|
|
620
|
+
type CategoryScores = Record<string, number>;
|
|
621
|
+
/** Final action recommendation derived from the weighted score. */
|
|
622
|
+
type Recommendation = 'allow' | 'challenge' | 'block';
|
|
623
|
+
/** Behavioral signals: mouse, touch, keyboard, and interaction timing. */
|
|
624
|
+
interface BehavioralSignals {
|
|
625
|
+
totalPoints?: number;
|
|
626
|
+
trajectoryLength?: number;
|
|
627
|
+
approachPoints?: number;
|
|
628
|
+
touchEvents?: number;
|
|
629
|
+
keyEvents?: number;
|
|
630
|
+
microTremorScore?: number;
|
|
631
|
+
approachDirectness?: number;
|
|
632
|
+
clickPrecision?: number;
|
|
633
|
+
explorationRatio?: number;
|
|
634
|
+
velocityVariance?: number;
|
|
635
|
+
overshootCorrections?: number;
|
|
636
|
+
interactionDuration?: number;
|
|
637
|
+
mouseEventRate?: number;
|
|
638
|
+
straightLineRatio?: number;
|
|
639
|
+
directionChanges?: number;
|
|
640
|
+
eventDeltaVariance?: number;
|
|
641
|
+
touchTotalPoints?: number;
|
|
642
|
+
touchForceMin?: number;
|
|
643
|
+
touchForceMax?: number;
|
|
644
|
+
touchForceVariance?: number;
|
|
645
|
+
touchForceAllOne?: boolean;
|
|
646
|
+
touchForceAllZero?: boolean;
|
|
647
|
+
touchRadiusMin?: number;
|
|
648
|
+
touchRadiusMax?: number;
|
|
649
|
+
touchRadiusVariance?: number;
|
|
650
|
+
touchUniqueIdentifiers?: number;
|
|
651
|
+
touchMultiTouchSeen?: boolean;
|
|
652
|
+
touchStraightLineRatio?: number;
|
|
653
|
+
touchMicroTremorScore?: number;
|
|
654
|
+
touchDirectionChanges?: number;
|
|
655
|
+
[key: string]: unknown;
|
|
656
|
+
}
|
|
657
|
+
interface PoWTiming {
|
|
658
|
+
duration?: number;
|
|
659
|
+
iterations?: number;
|
|
660
|
+
[key: string]: unknown;
|
|
661
|
+
}
|
|
662
|
+
interface TemporalSignals {
|
|
663
|
+
pow?: PoWTiming;
|
|
664
|
+
pageLoadToFirstInteraction?: number | null;
|
|
665
|
+
[key: string]: unknown;
|
|
666
|
+
}
|
|
667
|
+
interface EnvironmentalSignals {
|
|
668
|
+
webdriver?: boolean;
|
|
669
|
+
headlessIndicators?: {
|
|
670
|
+
hasOuterDimensions?: boolean;
|
|
671
|
+
innerEqualsOuter?: boolean;
|
|
672
|
+
notificationPermission?: string;
|
|
673
|
+
[key: string]: unknown;
|
|
674
|
+
};
|
|
675
|
+
automationFlags?: {
|
|
676
|
+
plugins?: number;
|
|
677
|
+
languages?: boolean;
|
|
678
|
+
chrome?: boolean;
|
|
679
|
+
platform?: string;
|
|
680
|
+
maxTouchPoints?: number;
|
|
681
|
+
hardwareConcurrency?: number;
|
|
682
|
+
[key: string]: unknown;
|
|
683
|
+
};
|
|
684
|
+
navigator?: {
|
|
685
|
+
platform?: string;
|
|
686
|
+
maxTouchPoints?: number;
|
|
687
|
+
[key: string]: unknown;
|
|
688
|
+
};
|
|
689
|
+
webglInfo?: {
|
|
690
|
+
renderer?: string;
|
|
691
|
+
[key: string]: unknown;
|
|
692
|
+
};
|
|
693
|
+
playwright?: {
|
|
694
|
+
detected?: boolean;
|
|
695
|
+
signals?: string[];
|
|
696
|
+
};
|
|
697
|
+
cdp?: {
|
|
698
|
+
detected?: boolean;
|
|
699
|
+
signals?: string[];
|
|
700
|
+
};
|
|
701
|
+
jsExecutionTime?: {
|
|
702
|
+
mathOps?: number;
|
|
703
|
+
[key: string]: unknown;
|
|
704
|
+
};
|
|
705
|
+
rafConsistency?: {
|
|
706
|
+
frameTimeVariance?: number;
|
|
707
|
+
[key: string]: unknown;
|
|
708
|
+
};
|
|
709
|
+
canvasHash?: {
|
|
710
|
+
hash?: string;
|
|
711
|
+
error?: unknown;
|
|
712
|
+
supported?: boolean;
|
|
713
|
+
[key: string]: unknown;
|
|
714
|
+
};
|
|
715
|
+
sensor?: {
|
|
716
|
+
motionEventCount?: number;
|
|
717
|
+
motionAccelVariance?: number;
|
|
718
|
+
orientationEventCount?: number;
|
|
719
|
+
orientationVariance?: number;
|
|
720
|
+
[key: string]: unknown;
|
|
721
|
+
};
|
|
722
|
+
webrtcInfo?: WebRTCInfo;
|
|
723
|
+
speechInfo?: SpeechInfo;
|
|
724
|
+
workerConsistency?: WorkerConsistencyInfo;
|
|
725
|
+
cssMediaQueries?: CSSMediaQueriesInfo;
|
|
726
|
+
fontsInfo?: FontsInfo;
|
|
727
|
+
permissionsInfo?: PermissionsInfo;
|
|
728
|
+
domRectFingerprint?: DOMRectInfo;
|
|
729
|
+
audioInfo?: AudioContextInfo;
|
|
730
|
+
lieDetection?: LieDetectionInfo;
|
|
731
|
+
[key: string]: unknown;
|
|
732
|
+
}
|
|
733
|
+
interface WebRTCInfo {
|
|
734
|
+
supported?: boolean;
|
|
735
|
+
mediaDevices?: {
|
|
736
|
+
supported?: boolean;
|
|
737
|
+
audioInputs?: number;
|
|
738
|
+
audioOutputs?: number;
|
|
739
|
+
videoInputs?: number;
|
|
740
|
+
totalDevices?: number;
|
|
741
|
+
};
|
|
742
|
+
hasLocalIP?: boolean;
|
|
743
|
+
localIPError?: unknown;
|
|
744
|
+
[key: string]: unknown;
|
|
745
|
+
}
|
|
746
|
+
interface SpeechInfo {
|
|
747
|
+
supported?: boolean;
|
|
748
|
+
totalVoices?: number;
|
|
749
|
+
localVoices?: number;
|
|
750
|
+
[key: string]: unknown;
|
|
751
|
+
}
|
|
752
|
+
interface WorkerConsistencyInfo {
|
|
753
|
+
supported?: boolean;
|
|
754
|
+
consistent?: boolean;
|
|
755
|
+
mismatches?: string[];
|
|
756
|
+
mismatchCount?: number;
|
|
757
|
+
[key: string]: unknown;
|
|
758
|
+
}
|
|
759
|
+
interface CSSMediaQueriesInfo {
|
|
760
|
+
supported?: boolean;
|
|
761
|
+
pointer?: string;
|
|
762
|
+
hover?: boolean;
|
|
763
|
+
[key: string]: unknown;
|
|
764
|
+
}
|
|
765
|
+
interface FontsInfo {
|
|
766
|
+
supported?: boolean;
|
|
767
|
+
count?: number;
|
|
768
|
+
hasSegoeUI?: boolean;
|
|
769
|
+
hasSFPro?: boolean;
|
|
770
|
+
hasDejaVuSans?: boolean;
|
|
771
|
+
[key: string]: unknown;
|
|
772
|
+
}
|
|
773
|
+
interface PermissionsInfo {
|
|
774
|
+
supported?: boolean;
|
|
775
|
+
[key: string]: unknown;
|
|
776
|
+
}
|
|
777
|
+
interface DOMRectInfo {
|
|
778
|
+
supported?: boolean;
|
|
779
|
+
rectAWidth?: number;
|
|
780
|
+
rectBWidth?: number;
|
|
781
|
+
rangeWidth?: number;
|
|
782
|
+
[key: string]: unknown;
|
|
783
|
+
}
|
|
784
|
+
/** AudioContext fingerprint. A real audio stack exposes `baseLatency` and a
|
|
785
|
+
* conventional sample rate; headless/mocked stacks omit or fake these. */
|
|
786
|
+
interface AudioContextInfo {
|
|
787
|
+
supported?: boolean;
|
|
788
|
+
sampleRate?: number;
|
|
789
|
+
state?: string;
|
|
790
|
+
baseLatency?: number | null;
|
|
791
|
+
[key: string]: unknown;
|
|
792
|
+
}
|
|
793
|
+
/** Native-function integrity check. `patched` lists native functions whose
|
|
794
|
+
* `toString()` no longer reports `[native code]` (or whose prototype was
|
|
795
|
+
* tampered with) — the signature of stealth automation hiding itself. A real
|
|
796
|
+
* browser never patches its own natives. */
|
|
797
|
+
interface LieDetectionInfo {
|
|
798
|
+
supported?: boolean;
|
|
799
|
+
patched?: string[];
|
|
800
|
+
patchedCount?: number;
|
|
801
|
+
[key: string]: unknown;
|
|
802
|
+
}
|
|
803
|
+
/** Per-field keystroke statistics for one textarea. */
|
|
804
|
+
interface TextareaKeyboardStats {
|
|
805
|
+
keyCount?: number;
|
|
806
|
+
pasteCount?: number;
|
|
807
|
+
avgKeyInterval?: number;
|
|
808
|
+
keyIntervalVariance?: number;
|
|
809
|
+
keydownUpRatio?: number;
|
|
810
|
+
noKeyboardEvents?: boolean;
|
|
811
|
+
contentLength?: number;
|
|
812
|
+
intervals?: number[];
|
|
813
|
+
dwellTimes?: number[];
|
|
814
|
+
rollovers?: number;
|
|
815
|
+
[key: string]: unknown;
|
|
816
|
+
}
|
|
817
|
+
interface FormSubmitInfo {
|
|
818
|
+
method?: string;
|
|
819
|
+
timeSincePageLoad?: number | null;
|
|
820
|
+
eventsBeforeSubmit?: number;
|
|
821
|
+
hadTriggerEvent?: boolean;
|
|
822
|
+
[key: string]: unknown;
|
|
823
|
+
}
|
|
824
|
+
interface FormAnalysisSignals {
|
|
825
|
+
pageLoadToFirstInteraction?: number | null;
|
|
826
|
+
submit?: FormSubmitInfo;
|
|
827
|
+
textareaKeyboard?: Record<string, TextareaKeyboardStats>;
|
|
828
|
+
[key: string]: unknown;
|
|
829
|
+
}
|
|
830
|
+
/** The full set of signals the client widget reports. */
|
|
831
|
+
interface Signals {
|
|
832
|
+
behavioral?: BehavioralSignals;
|
|
833
|
+
temporal?: TemporalSignals;
|
|
834
|
+
environmental?: EnvironmentalSignals;
|
|
835
|
+
formAnalysis?: FormAnalysisSignals;
|
|
836
|
+
meta?: {
|
|
837
|
+
challengeNonce?: string;
|
|
838
|
+
[key: string]: unknown;
|
|
839
|
+
};
|
|
840
|
+
[key: string]: unknown;
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Outcome of proof-of-work verification, supplied by the caller (the PoW
|
|
844
|
+
* subsystem lands in Phase 2). When omitted and `requirePoW` is enabled the
|
|
845
|
+
* engine emits a hard-fail "No PoW solution provided" detection, matching the
|
|
846
|
+
* reference server.
|
|
847
|
+
*/
|
|
848
|
+
interface PoWOutcome {
|
|
849
|
+
/** Whether a PoW solution was submitted at all. */
|
|
850
|
+
provided: boolean;
|
|
851
|
+
/** Whether the submitted solution verified. */
|
|
852
|
+
valid?: boolean;
|
|
853
|
+
/** Failure reason when `valid` is false. */
|
|
854
|
+
reason?: string;
|
|
855
|
+
/** Server-measured solve time in ms (un-spoofable). */
|
|
856
|
+
serverElapsed?: number;
|
|
857
|
+
/** Nonce bound to the verified challenge. */
|
|
858
|
+
nonce?: string;
|
|
859
|
+
}
|
|
860
|
+
/** Per-request context for scoring. */
|
|
861
|
+
interface DetectionContext {
|
|
862
|
+
ip: string;
|
|
863
|
+
siteKey: string;
|
|
864
|
+
userAgent: string;
|
|
865
|
+
/** Lower-cased request headers. */
|
|
866
|
+
headers?: Record<string, string>;
|
|
867
|
+
/** Client-supplied JA3 hash (spoofable). */
|
|
868
|
+
ja3Hash?: string | null;
|
|
869
|
+
/** Trusted reverse-proxy header names carrying a JA4 fingerprint. */
|
|
870
|
+
trustedJA4Headers?: string[];
|
|
871
|
+
/** Proof-of-work verification outcome (supplied by the PoW subsystem). */
|
|
872
|
+
pow?: PoWOutcome;
|
|
873
|
+
/**
|
|
874
|
+
* Additional detections to fold into scoring, produced by an outer
|
|
875
|
+
* orchestrator (e.g. the signals-tampering check in the Captcha service).
|
|
876
|
+
*/
|
|
877
|
+
extraDetections?: Detection[];
|
|
878
|
+
}
|
|
879
|
+
/** Final verdict returned by {@link DetectionEngine.score}. */
|
|
880
|
+
interface Verdict {
|
|
881
|
+
/** True when the weighted score is below the success threshold (< 0.5). */
|
|
882
|
+
success: boolean;
|
|
883
|
+
/** Weighted final score, 0..1. */
|
|
884
|
+
score: number;
|
|
885
|
+
/** Recommended action. */
|
|
886
|
+
recommendation: Recommendation;
|
|
887
|
+
/** Per-category aggregated scores. */
|
|
888
|
+
categoryScores: CategoryScores;
|
|
889
|
+
/** Every triggered detection. */
|
|
890
|
+
detections: Detection[];
|
|
891
|
+
/** Unix seconds at evaluation time. */
|
|
892
|
+
timestamp: number;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* In-memory stores backing the stateful detectors (fingerprint correlation and
|
|
897
|
+
* rate abuse). Ported from FCaptcha index.js.
|
|
898
|
+
*
|
|
899
|
+
* These are defined behind interfaces so Phase 2 can swap in a shared/Redis
|
|
900
|
+
* backend for serverless and multi-instance deployments.
|
|
901
|
+
*/
|
|
902
|
+
/** Tracks fingerprint ↔ IP relationships to spot distributed attacks. */
|
|
903
|
+
interface FingerprintStore {
|
|
904
|
+
record(fp: string, ip: string, siteKey: string): void;
|
|
905
|
+
/** Number of distinct fingerprints seen from `ip`. */
|
|
906
|
+
getIpFpCount(ip: string): number;
|
|
907
|
+
/** Number of distinct IPs that produced fingerprint `fp` for `siteKey`. */
|
|
908
|
+
getFpIpCount(fp: string, siteKey: string): number;
|
|
909
|
+
}
|
|
910
|
+
/** Sliding-window request counter. */
|
|
911
|
+
interface RateLimiter {
|
|
912
|
+
/** Returns `[exceeded, count]` for the window, recording this hit. */
|
|
913
|
+
check(key: string, windowSeconds?: number, maxRequests?: number): [boolean, number];
|
|
914
|
+
}
|
|
915
|
+
declare class InMemoryFingerprintStore implements FingerprintStore {
|
|
916
|
+
private fingerprints;
|
|
917
|
+
private ipFingerprints;
|
|
918
|
+
record(fp: string, ip: string, siteKey: string): void;
|
|
919
|
+
getIpFpCount(ip: string): number;
|
|
920
|
+
getFpIpCount(fp: string, siteKey: string): number;
|
|
921
|
+
}
|
|
922
|
+
declare class InMemoryRateLimiter implements RateLimiter {
|
|
923
|
+
private requests;
|
|
924
|
+
check(key: string, windowSeconds?: number, maxRequests?: number): [boolean, number];
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
/**
|
|
928
|
+
* Detection engine.
|
|
929
|
+
*
|
|
930
|
+
* Runs the full FCaptcha detector suite in-process and produces a {@link Verdict}.
|
|
931
|
+
* Mirrors the reference server's `runVerification` orchestration. The actual
|
|
932
|
+
* proof-of-work crypto and token issuance land in Phase 2 — for now the caller
|
|
933
|
+
* supplies a {@link PoWOutcome} and the engine emits the matching detections.
|
|
934
|
+
*/
|
|
935
|
+
|
|
936
|
+
interface DetectionEngineOptions {
|
|
937
|
+
/** Override the per-category weights (defaults to {@link DEFAULT_WEIGHTS}). */
|
|
938
|
+
weights?: Record<string, number>;
|
|
939
|
+
/**
|
|
940
|
+
* When true (default), a request with no PoW outcome emits a hard-fail "No PoW
|
|
941
|
+
* solution provided" detection — matching the reference server. Set false to
|
|
942
|
+
* score raw signals without requiring proof-of-work.
|
|
943
|
+
*/
|
|
944
|
+
requirePoW?: boolean;
|
|
945
|
+
/** Fingerprint-correlation store (defaults to an in-memory store). */
|
|
946
|
+
fingerprintStore?: FingerprintStore;
|
|
947
|
+
/** Rate limiter for rate-abuse detection (defaults to in-memory). */
|
|
948
|
+
rateLimiter?: RateLimiter;
|
|
949
|
+
}
|
|
950
|
+
declare class DetectionEngine {
|
|
951
|
+
private readonly weights;
|
|
952
|
+
private readonly requirePoW;
|
|
953
|
+
private readonly fingerprintStore;
|
|
954
|
+
private readonly rateLimiter;
|
|
955
|
+
constructor(options?: DetectionEngineOptions);
|
|
956
|
+
/** Score `signals` for the given request context and return a verdict. */
|
|
957
|
+
score(signals: Signals, context: DetectionContext): Verdict;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
/** Score aggregation: per-category confidence-weighted means → weighted total. */
|
|
961
|
+
|
|
962
|
+
/**
|
|
963
|
+
* Aggregate detections into per-category scores. Each category's score is the
|
|
964
|
+
* confidence-weighted mean of its detections' scores, capped at 1.0. Categories
|
|
965
|
+
* present in `weights` but with no detections are filled with 0.
|
|
966
|
+
*/
|
|
967
|
+
declare function calculateCategoryScores(detections: Detection[], weights: Record<string, number>): CategoryScores;
|
|
968
|
+
/** Combine category scores into the final weighted score (capped at 1.0). */
|
|
969
|
+
declare function calculateFinalScore(categoryScores: CategoryScores, weights: Record<string, number>): number;
|
|
970
|
+
/** Map a final score to an action recommendation. */
|
|
971
|
+
declare function recommend(finalScore: number): Recommendation;
|
|
972
|
+
|
|
973
|
+
/**
|
|
974
|
+
* Category weights and automation UA patterns.
|
|
975
|
+
*
|
|
976
|
+
* Values match the FCaptcha standalone server (server.js), which is the most
|
|
977
|
+
* complete variant of the engine and the one the reference test suite exercises.
|
|
978
|
+
*/
|
|
979
|
+
/**
|
|
980
|
+
* Default per-category weights used to compute the final score.
|
|
981
|
+
*
|
|
982
|
+
* `stealth` carries deliberate anti-detection tampering (native functions
|
|
983
|
+
* patched to hide automation). This is the least-ambiguous evidence of a bot —
|
|
984
|
+
* a genuine browser never patches its own natives — so it is weighted highest.
|
|
985
|
+
* Because weights are a simple weighted sum (not required to total 1.0), and
|
|
986
|
+
* `stealth` is 0 for any clean browser, this raises stealth-bot scores without
|
|
987
|
+
* affecting legitimate traffic.
|
|
988
|
+
*/
|
|
989
|
+
declare const DEFAULT_WEIGHTS: Record<string, number>;
|
|
990
|
+
|
|
991
|
+
/** True when `ip` falls inside a known datacenter CIDR block (IPv4 only). */
|
|
992
|
+
declare function isDatacenterIP(ip: string): boolean;
|
|
993
|
+
|
|
994
|
+
/**
|
|
995
|
+
* User-Agent parsing and bot-pattern matching. Ported from FCaptcha detection.js.
|
|
996
|
+
*/
|
|
997
|
+
interface UserAgentInfo {
|
|
998
|
+
browser: string | null;
|
|
999
|
+
os: string | null;
|
|
1000
|
+
isMobile: boolean;
|
|
1001
|
+
isBot: boolean;
|
|
1002
|
+
botName: string | null;
|
|
1003
|
+
}
|
|
1004
|
+
/** True when the UA looks like a mobile device. */
|
|
1005
|
+
declare function isMobileUA(userAgent: string): boolean;
|
|
1006
|
+
/** Extract browser/OS/bot info from a User-Agent string. */
|
|
1007
|
+
declare function parseUserAgent(ua: string): UserAgentInfo;
|
|
1008
|
+
|
|
1009
|
+
/** Types for the self-hosted captcha service (PoW + scoring + tokens). */
|
|
1010
|
+
|
|
1011
|
+
/** Signed challenge returned to the client to solve. */
|
|
1012
|
+
interface ChallengeData {
|
|
1013
|
+
/** Challenge id (hex). */
|
|
1014
|
+
id: string;
|
|
1015
|
+
siteKey: string;
|
|
1016
|
+
/** Generation time, ms epoch. */
|
|
1017
|
+
timestamp: number;
|
|
1018
|
+
/** Expiry time, ms epoch. */
|
|
1019
|
+
expiresAt: number;
|
|
1020
|
+
/** Leading-zero difficulty the solution hash must satisfy. */
|
|
1021
|
+
difficulty: number;
|
|
1022
|
+
/** Random nonce bound to the challenge (echoed back in signals). */
|
|
1023
|
+
nonce: string;
|
|
1024
|
+
/** Hash prefix the client iterates over: `${id}:${timestamp}:${difficulty}`. */
|
|
1025
|
+
prefix: string;
|
|
1026
|
+
/** HMAC signature over the challenge. */
|
|
1027
|
+
sig: string;
|
|
1028
|
+
}
|
|
1029
|
+
/** Stored challenge record (server-side only — never sent to the client). */
|
|
1030
|
+
interface StoredChallenge extends ChallengeData {
|
|
1031
|
+
ip: string;
|
|
1032
|
+
createdAt: number;
|
|
1033
|
+
}
|
|
1034
|
+
/** A client's proof-of-work solution. */
|
|
1035
|
+
interface PoWSolution {
|
|
1036
|
+
challengeId: string;
|
|
1037
|
+
nonce: number | string;
|
|
1038
|
+
hash: string;
|
|
1039
|
+
/** Optional commitment binding the solution to the submitted signals. */
|
|
1040
|
+
signalsHash?: string;
|
|
1041
|
+
}
|
|
1042
|
+
/** Result of verifying a PoW solution. */
|
|
1043
|
+
interface PoWVerification {
|
|
1044
|
+
valid: boolean;
|
|
1045
|
+
reason?: string;
|
|
1046
|
+
difficulty?: number;
|
|
1047
|
+
/** Server-measured solve time in ms (un-spoofable). */
|
|
1048
|
+
serverElapsed?: number;
|
|
1049
|
+
/** The challenge's bound nonce. */
|
|
1050
|
+
nonce?: string;
|
|
1051
|
+
}
|
|
1052
|
+
/** Result of verifying an issued token. */
|
|
1053
|
+
interface TokenVerification {
|
|
1054
|
+
valid: boolean;
|
|
1055
|
+
reason?: string;
|
|
1056
|
+
site_key?: string;
|
|
1057
|
+
timestamp?: number;
|
|
1058
|
+
score?: number;
|
|
1059
|
+
ip_hash?: string;
|
|
1060
|
+
}
|
|
1061
|
+
/** Input to {@link Captcha.verify} / {@link Captcha.score}. */
|
|
1062
|
+
interface VerifyInput {
|
|
1063
|
+
siteKey: string;
|
|
1064
|
+
ip: string;
|
|
1065
|
+
userAgent: string;
|
|
1066
|
+
/** Lower-cased request headers. */
|
|
1067
|
+
headers?: Record<string, string>;
|
|
1068
|
+
/** Parsed client signals. */
|
|
1069
|
+
signals?: Signals;
|
|
1070
|
+
/** Client PoW solution. */
|
|
1071
|
+
powSolution?: PoWSolution | null;
|
|
1072
|
+
/** Raw signals JSON used for the commitment check (overrides `signals`). */
|
|
1073
|
+
signalsJson?: string | null;
|
|
1074
|
+
/** Client-reported PoW timing, injected into `signals.temporal.pow`. */
|
|
1075
|
+
powTiming?: {
|
|
1076
|
+
duration?: number;
|
|
1077
|
+
iterations?: number;
|
|
1078
|
+
} | null;
|
|
1079
|
+
/** Client-supplied JA3 hash (spoofable). */
|
|
1080
|
+
ja3Hash?: string | null;
|
|
1081
|
+
}
|
|
1082
|
+
/** A verdict plus an issued token (present only on success). */
|
|
1083
|
+
interface VerifyResult extends Verdict {
|
|
1084
|
+
/** base64url session token, or null when the request did not pass. */
|
|
1085
|
+
token: string | null;
|
|
1086
|
+
}
|
|
1087
|
+
/** Invisible-mode (`score`) result. */
|
|
1088
|
+
interface ScoreResult {
|
|
1089
|
+
success: boolean;
|
|
1090
|
+
score: number;
|
|
1091
|
+
token: string | null;
|
|
1092
|
+
action: string;
|
|
1093
|
+
recommendation: Recommendation;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
/**
|
|
1097
|
+
* Proof-of-work challenge issuance and verification.
|
|
1098
|
+
*
|
|
1099
|
+
* Ported from FCaptcha server.js `powChallengeStore`. HMAC-signed challenges,
|
|
1100
|
+
* SHA-256 leading-zero difficulty, one-time-use replay protection, 5-minute
|
|
1101
|
+
* expiry, optional signals-commitment binding, and un-spoofable server-side
|
|
1102
|
+
* timing. The challenge store is pluggable so Phase-later work can back it with
|
|
1103
|
+
* Redis for serverless / multi-instance deployments.
|
|
1104
|
+
*/
|
|
1105
|
+
|
|
1106
|
+
/** Persistence for in-flight challenges and consumed solutions. */
|
|
1107
|
+
interface ChallengeStore {
|
|
1108
|
+
put(challenge: StoredChallenge): void;
|
|
1109
|
+
get(id: string): StoredChallenge | undefined;
|
|
1110
|
+
delete(id: string): void;
|
|
1111
|
+
/** Returns false if the solution key was already consumed (replay). */
|
|
1112
|
+
markSolutionUsed(solutionKey: string): boolean;
|
|
1113
|
+
}
|
|
1114
|
+
declare class InMemoryChallengeStore implements ChallengeStore {
|
|
1115
|
+
private challenges;
|
|
1116
|
+
private usedSolutions;
|
|
1117
|
+
put(challenge: StoredChallenge): void;
|
|
1118
|
+
get(id: string): StoredChallenge | undefined;
|
|
1119
|
+
delete(id: string): void;
|
|
1120
|
+
markSolutionUsed(solutionKey: string): boolean;
|
|
1121
|
+
private cleanup;
|
|
1122
|
+
}
|
|
1123
|
+
interface PoWManagerOptions {
|
|
1124
|
+
secret: string;
|
|
1125
|
+
store?: ChallengeStore;
|
|
1126
|
+
/** Shared rate limiter used for difficulty scaling. */
|
|
1127
|
+
rateLimiter?: RateLimiter;
|
|
1128
|
+
}
|
|
1129
|
+
declare class PoWManager {
|
|
1130
|
+
private readonly secret;
|
|
1131
|
+
private readonly store;
|
|
1132
|
+
private readonly rateLimiter;
|
|
1133
|
+
constructor(options: PoWManagerOptions);
|
|
1134
|
+
/** Difficulty scaled by IP reputation and request rate (4..6). */
|
|
1135
|
+
scaleDifficulty(siteKey: string, ip: string): number;
|
|
1136
|
+
/** Generate and store a signed challenge. */
|
|
1137
|
+
generate(siteKey: string, ip: string, difficulty?: number): ChallengeData;
|
|
1138
|
+
/** Verify a submitted solution. `signalsHash` binds it to the signals. */
|
|
1139
|
+
verify(solution: PoWSolution, siteKey: string, signalsHash?: string | null): PoWVerification;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
/**
|
|
1143
|
+
* Session token issuance and verification.
|
|
1144
|
+
*
|
|
1145
|
+
* Ported from FCaptcha server.js `generateToken`/`verifyToken` + `tokenStore`.
|
|
1146
|
+
* Tokens are base64url-encoded JSON with an HMAC signature, a 5-minute expiry,
|
|
1147
|
+
* an IP-hash binding, and single-use replay protection.
|
|
1148
|
+
*/
|
|
1149
|
+
|
|
1150
|
+
/** Tracks consumed token signatures to prevent replay. */
|
|
1151
|
+
interface TokenStore {
|
|
1152
|
+
/** Returns false if the signature was already consumed. */
|
|
1153
|
+
markUsed(sig: string): boolean;
|
|
1154
|
+
isUsed(sig: string): boolean;
|
|
1155
|
+
}
|
|
1156
|
+
declare class InMemoryTokenStore implements TokenStore {
|
|
1157
|
+
private usedTokens;
|
|
1158
|
+
markUsed(sig: string): boolean;
|
|
1159
|
+
isUsed(sig: string): boolean;
|
|
1160
|
+
}
|
|
1161
|
+
interface TokenManagerOptions {
|
|
1162
|
+
secret: string;
|
|
1163
|
+
store?: TokenStore;
|
|
1164
|
+
}
|
|
1165
|
+
declare class TokenManager {
|
|
1166
|
+
private readonly secret;
|
|
1167
|
+
private readonly store;
|
|
1168
|
+
constructor(options: TokenManagerOptions);
|
|
1169
|
+
/** Issue a signed, IP-bound token for a passing request. */
|
|
1170
|
+
issue(ip: string, siteKey: string, score: number): string;
|
|
1171
|
+
/** Verify a token: signature, expiry, replay, and optional IP binding. */
|
|
1172
|
+
verify(token: string, ip?: string | null): TokenVerification;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
/**
|
|
1176
|
+
* Self-hosted captcha service.
|
|
1177
|
+
*
|
|
1178
|
+
* Composes the in-process {@link DetectionEngine} with proof-of-work and token
|
|
1179
|
+
* issuance to reproduce the FCaptcha server's `runVerification` flow end-to-end:
|
|
1180
|
+
* issue challenge → verify PoW → score signals → issue session token. Runs
|
|
1181
|
+
* entirely in-process; only IP enrichment remains a remote call elsewhere in
|
|
1182
|
+
* the SDK.
|
|
1183
|
+
*/
|
|
1184
|
+
|
|
1185
|
+
interface CaptchaOptions {
|
|
1186
|
+
/** HMAC secret for signing challenges and tokens. Required in production. */
|
|
1187
|
+
secret?: string;
|
|
1188
|
+
/** Override per-category detection weights. */
|
|
1189
|
+
weights?: Record<string, number>;
|
|
1190
|
+
/** Trusted reverse-proxy header names carrying a JA4 fingerprint. */
|
|
1191
|
+
trustedJA4Headers?: string[];
|
|
1192
|
+
/** Pluggable stores (default to in-memory; swap for Redis in production). */
|
|
1193
|
+
challengeStore?: ChallengeStore;
|
|
1194
|
+
tokenStore?: TokenStore;
|
|
1195
|
+
fingerprintStore?: FingerprintStore;
|
|
1196
|
+
rateLimiter?: RateLimiter;
|
|
1197
|
+
}
|
|
1198
|
+
declare class Captcha {
|
|
1199
|
+
private readonly engine;
|
|
1200
|
+
private readonly pow;
|
|
1201
|
+
private readonly tokens;
|
|
1202
|
+
private readonly trustedJA4Headers;
|
|
1203
|
+
constructor(options?: CaptchaOptions);
|
|
1204
|
+
/** Issue a PoW challenge for the client to solve (difficulty auto-scaled). */
|
|
1205
|
+
issueChallenge(siteKey: string, ip: string, difficulty?: number): ChallengeData;
|
|
1206
|
+
/**
|
|
1207
|
+
* Verify a submission: checks the signals commitment, verifies PoW, scores the
|
|
1208
|
+
* signals, and issues a session token on success. Mirrors `runVerification`.
|
|
1209
|
+
*/
|
|
1210
|
+
verify(input: VerifyInput): VerifyResult;
|
|
1211
|
+
/** Invisible-mode scoring — same pipeline, returns a compact result + action. */
|
|
1212
|
+
score(input: VerifyInput & {
|
|
1213
|
+
action?: string;
|
|
1214
|
+
}): ScoreResult;
|
|
1215
|
+
/** Verify a previously issued token (single-use, optionally IP-bound). */
|
|
1216
|
+
verifyToken(token: string, ip?: string | null): TokenVerification;
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
/**
|
|
1220
|
+
* Validate an HMAC signing secret. Throws when the secret is missing/empty, or
|
|
1221
|
+
* when it is the insecure default while `NODE_ENV === 'production'`. In
|
|
1222
|
+
* non-production environments a missing secret falls back to the insecure
|
|
1223
|
+
* default (with the returned flag set) so local development works out of the box.
|
|
1224
|
+
*/
|
|
1225
|
+
declare function resolveSecret(secret?: string): string;
|
|
1226
|
+
|
|
1227
|
+
/**
|
|
1228
|
+
* Framework-agnostic HTTP handler for the captcha endpoints.
|
|
1229
|
+
*
|
|
1230
|
+
* Maps normalized requests to the {@link Captcha} service so each framework
|
|
1231
|
+
* adapter (Express/Fastify/Next.js) only has to translate its own req/res into
|
|
1232
|
+
* this shape. Routes (under a configurable base path, default `/__webdecoy`):
|
|
1233
|
+
*
|
|
1234
|
+
* GET {base}/challenge?siteKey= → issue a PoW challenge
|
|
1235
|
+
* POST {base}/verify → verify a checkbox submission
|
|
1236
|
+
* POST {base}/score → invisible-mode score
|
|
1237
|
+
* POST {base}/token/verify → verify an issued token
|
|
1238
|
+
*/
|
|
1239
|
+
|
|
1240
|
+
/** Normalized inbound request the adapters construct. */
|
|
1241
|
+
interface CaptchaRequest {
|
|
1242
|
+
method: string;
|
|
1243
|
+
/** URL pathname (no query string). */
|
|
1244
|
+
pathname: string;
|
|
1245
|
+
query: Record<string, string | undefined>;
|
|
1246
|
+
/** Lower-cased headers. */
|
|
1247
|
+
headers: Record<string, string>;
|
|
1248
|
+
/** Parsed JSON body (for POST routes). */
|
|
1249
|
+
body?: unknown;
|
|
1250
|
+
/** Resolved client IP. */
|
|
1251
|
+
ip: string;
|
|
1252
|
+
}
|
|
1253
|
+
/** Normalized response the adapters write back. */
|
|
1254
|
+
interface CaptchaHttpResponse {
|
|
1255
|
+
status: number;
|
|
1256
|
+
headers: Record<string, string>;
|
|
1257
|
+
body: unknown;
|
|
1258
|
+
}
|
|
1259
|
+
interface CaptchaEndpointsOptions extends CaptchaOptions {
|
|
1260
|
+
/** Base path the routes are mounted under (default `/__webdecoy`). */
|
|
1261
|
+
basePath?: string;
|
|
1262
|
+
}
|
|
1263
|
+
/**
|
|
1264
|
+
* Build a captcha request handler. The returned function resolves to a response
|
|
1265
|
+
* for a matching route, or `null` when the request is not a captcha route (so
|
|
1266
|
+
* middleware can fall through to the next handler).
|
|
1267
|
+
*/
|
|
1268
|
+
declare function createCaptchaEndpoints(options?: CaptchaEndpointsOptions): {
|
|
1269
|
+
captcha: Captcha;
|
|
1270
|
+
basePath: string;
|
|
1271
|
+
handle: (req: CaptchaRequest) => Promise<CaptchaHttpResponse | null>;
|
|
1272
|
+
};
|
|
1273
|
+
type CaptchaEndpoints = ReturnType<typeof createCaptchaEndpoints>;
|
|
486
1274
|
|
|
487
|
-
export { type FilterConfig, FilterRule, type IPEnrichmentData, type LocalAnalysis, type ProtectOptions, type ProtectResult, type RateLimitConfig, RateLimitRule, type RequestMetadata, type Rule, type RuleContext, RuleEngine, type RuleEngineResult, type RuleResult, type SDKDetectionRequest, type SDKDetectionResponse, type TLSInfo, type ViolationEvent, WebDecoy, type WebDecoyConfig, filter, rateLimit };
|
|
1275
|
+
export { type BehavioralSignals, Captcha, type CaptchaEndpoints, type CaptchaEndpointsOptions, type CaptchaHttpResponse, type CaptchaOptions, type CaptchaRequest, type CategoryScores, type ChallengeData, type ChallengeStore, DEFAULT_TRIPWIRE_PATHS, DEFAULT_WEIGHTS, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, type EnvironmentalSignals, type FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, type Honeytoken, type HoneytokenOptions, type IPEnrichmentData, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, type LocalAnalysis, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, type ProtectOptions, type ProtectResult, type RateLimitConfig, RateLimitRule, type RateLimiter, type Recommendation, type RequestMetadata, type Rule, type RuleContext, RuleEngine, type RuleEngineResult, type RuleResult, type SDKDetectionRequest, type SDKDetectionResponse, type ScoreResult, type Signals, type StoredChallenge, type TLSInfo, type TemporalSignals, type TextareaKeyboardStats, TokenManager, type TokenManagerOptions, type TokenStore, type TokenVerification, type TripwireConfig, TripwireRule, type Verdict, type VerifyInput, type VerifyResult, type ViolationEvent, WebDecoy, type WebDecoyConfig, calculateCategoryScores, calculateFinalScore, createCaptchaEndpoints, filter, honeytoken, isDatacenterIP, isMobileUA, parseUserAgent, rateLimit, recommend, resolveSecret, tripwire };
|