@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/dist/index.d.ts CHANGED
@@ -484,4 +484,655 @@ declare function rateLimit(config: RateLimitConfig): Rule;
484
484
  */
485
485
  declare function filter(config: FilterConfig): Rule;
486
486
 
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 };
487
+ /**
488
+ * Detection engine types.
489
+ *
490
+ * The detection engine scores a set of client-collected `Signals` against ~40
491
+ * behavioral, environmental, and fingerprint heuristics and produces a verdict.
492
+ * Ported from the FCaptcha scoring engine so behavior matches the self-hosted
493
+ * server (server.js `runVerification`).
494
+ *
495
+ * Signals originate from an untrusted client, so every field is optional and the
496
+ * detectors fall back to neutral defaults (mirroring the `?? default` pattern in
497
+ * the reference implementation).
498
+ */
499
+ /** A single triggered heuristic. */
500
+ interface Detection {
501
+ /** Scoring bucket this detection contributes to (see {@link Weights}). */
502
+ category: string;
503
+ /** Likelihood this signal indicates a bot/attack, 0..1. */
504
+ score: number;
505
+ /** Certainty of the score, 0..1, used to weight the per-category aggregate. */
506
+ confidence: number;
507
+ /** Human-readable explanation. */
508
+ reason: string;
509
+ /** Optional structured detail (e.g. keystroke-cadence metrics). */
510
+ details?: Record<string, unknown>;
511
+ }
512
+ /** Per-category aggregated scores (0..1), keyed by category name. */
513
+ type CategoryScores = Record<string, number>;
514
+ /** Final action recommendation derived from the weighted score. */
515
+ type Recommendation = 'allow' | 'challenge' | 'block';
516
+ /** Behavioral signals: mouse, touch, keyboard, and interaction timing. */
517
+ interface BehavioralSignals {
518
+ totalPoints?: number;
519
+ trajectoryLength?: number;
520
+ approachPoints?: number;
521
+ touchEvents?: number;
522
+ keyEvents?: number;
523
+ microTremorScore?: number;
524
+ approachDirectness?: number;
525
+ clickPrecision?: number;
526
+ explorationRatio?: number;
527
+ velocityVariance?: number;
528
+ overshootCorrections?: number;
529
+ interactionDuration?: number;
530
+ mouseEventRate?: number;
531
+ straightLineRatio?: number;
532
+ directionChanges?: number;
533
+ eventDeltaVariance?: number;
534
+ touchTotalPoints?: number;
535
+ touchForceMin?: number;
536
+ touchForceMax?: number;
537
+ touchForceVariance?: number;
538
+ touchForceAllOne?: boolean;
539
+ touchForceAllZero?: boolean;
540
+ touchRadiusMin?: number;
541
+ touchRadiusMax?: number;
542
+ touchRadiusVariance?: number;
543
+ touchUniqueIdentifiers?: number;
544
+ touchMultiTouchSeen?: boolean;
545
+ touchStraightLineRatio?: number;
546
+ touchMicroTremorScore?: number;
547
+ touchDirectionChanges?: number;
548
+ [key: string]: unknown;
549
+ }
550
+ interface PoWTiming {
551
+ duration?: number;
552
+ iterations?: number;
553
+ [key: string]: unknown;
554
+ }
555
+ interface TemporalSignals {
556
+ pow?: PoWTiming;
557
+ pageLoadToFirstInteraction?: number | null;
558
+ [key: string]: unknown;
559
+ }
560
+ interface EnvironmentalSignals {
561
+ webdriver?: boolean;
562
+ headlessIndicators?: {
563
+ hasOuterDimensions?: boolean;
564
+ innerEqualsOuter?: boolean;
565
+ notificationPermission?: string;
566
+ [key: string]: unknown;
567
+ };
568
+ automationFlags?: {
569
+ plugins?: number;
570
+ languages?: boolean;
571
+ chrome?: boolean;
572
+ platform?: string;
573
+ maxTouchPoints?: number;
574
+ hardwareConcurrency?: number;
575
+ [key: string]: unknown;
576
+ };
577
+ navigator?: {
578
+ platform?: string;
579
+ maxTouchPoints?: number;
580
+ [key: string]: unknown;
581
+ };
582
+ webglInfo?: {
583
+ renderer?: string;
584
+ [key: string]: unknown;
585
+ };
586
+ playwright?: {
587
+ detected?: boolean;
588
+ signals?: string[];
589
+ };
590
+ cdp?: {
591
+ detected?: boolean;
592
+ signals?: string[];
593
+ };
594
+ jsExecutionTime?: {
595
+ mathOps?: number;
596
+ [key: string]: unknown;
597
+ };
598
+ rafConsistency?: {
599
+ frameTimeVariance?: number;
600
+ [key: string]: unknown;
601
+ };
602
+ canvasHash?: {
603
+ hash?: string;
604
+ error?: unknown;
605
+ supported?: boolean;
606
+ [key: string]: unknown;
607
+ };
608
+ sensor?: {
609
+ motionEventCount?: number;
610
+ motionAccelVariance?: number;
611
+ orientationEventCount?: number;
612
+ orientationVariance?: number;
613
+ [key: string]: unknown;
614
+ };
615
+ webrtcInfo?: WebRTCInfo;
616
+ speechInfo?: SpeechInfo;
617
+ workerConsistency?: WorkerConsistencyInfo;
618
+ cssMediaQueries?: CSSMediaQueriesInfo;
619
+ fontsInfo?: FontsInfo;
620
+ permissionsInfo?: PermissionsInfo;
621
+ domRectFingerprint?: DOMRectInfo;
622
+ [key: string]: unknown;
623
+ }
624
+ interface WebRTCInfo {
625
+ supported?: boolean;
626
+ mediaDevices?: {
627
+ supported?: boolean;
628
+ audioInputs?: number;
629
+ audioOutputs?: number;
630
+ videoInputs?: number;
631
+ totalDevices?: number;
632
+ };
633
+ hasLocalIP?: boolean;
634
+ localIPError?: unknown;
635
+ [key: string]: unknown;
636
+ }
637
+ interface SpeechInfo {
638
+ supported?: boolean;
639
+ totalVoices?: number;
640
+ localVoices?: number;
641
+ [key: string]: unknown;
642
+ }
643
+ interface WorkerConsistencyInfo {
644
+ supported?: boolean;
645
+ consistent?: boolean;
646
+ mismatches?: string[];
647
+ mismatchCount?: number;
648
+ [key: string]: unknown;
649
+ }
650
+ interface CSSMediaQueriesInfo {
651
+ supported?: boolean;
652
+ pointer?: string;
653
+ hover?: boolean;
654
+ [key: string]: unknown;
655
+ }
656
+ interface FontsInfo {
657
+ supported?: boolean;
658
+ count?: number;
659
+ hasSegoeUI?: boolean;
660
+ hasSFPro?: boolean;
661
+ hasDejaVuSans?: boolean;
662
+ [key: string]: unknown;
663
+ }
664
+ interface PermissionsInfo {
665
+ supported?: boolean;
666
+ [key: string]: unknown;
667
+ }
668
+ interface DOMRectInfo {
669
+ supported?: boolean;
670
+ rectAWidth?: number;
671
+ rectBWidth?: number;
672
+ rangeWidth?: number;
673
+ [key: string]: unknown;
674
+ }
675
+ /** Per-field keystroke statistics for one textarea. */
676
+ interface TextareaKeyboardStats {
677
+ keyCount?: number;
678
+ pasteCount?: number;
679
+ avgKeyInterval?: number;
680
+ keyIntervalVariance?: number;
681
+ keydownUpRatio?: number;
682
+ noKeyboardEvents?: boolean;
683
+ contentLength?: number;
684
+ intervals?: number[];
685
+ dwellTimes?: number[];
686
+ rollovers?: number;
687
+ [key: string]: unknown;
688
+ }
689
+ interface FormSubmitInfo {
690
+ method?: string;
691
+ timeSincePageLoad?: number | null;
692
+ eventsBeforeSubmit?: number;
693
+ hadTriggerEvent?: boolean;
694
+ [key: string]: unknown;
695
+ }
696
+ interface FormAnalysisSignals {
697
+ pageLoadToFirstInteraction?: number | null;
698
+ submit?: FormSubmitInfo;
699
+ textareaKeyboard?: Record<string, TextareaKeyboardStats>;
700
+ [key: string]: unknown;
701
+ }
702
+ /** The full set of signals the client widget reports. */
703
+ interface Signals {
704
+ behavioral?: BehavioralSignals;
705
+ temporal?: TemporalSignals;
706
+ environmental?: EnvironmentalSignals;
707
+ formAnalysis?: FormAnalysisSignals;
708
+ meta?: {
709
+ challengeNonce?: string;
710
+ [key: string]: unknown;
711
+ };
712
+ [key: string]: unknown;
713
+ }
714
+ /**
715
+ * Outcome of proof-of-work verification, supplied by the caller (the PoW
716
+ * subsystem lands in Phase 2). When omitted and `requirePoW` is enabled the
717
+ * engine emits a hard-fail "No PoW solution provided" detection, matching the
718
+ * reference server.
719
+ */
720
+ interface PoWOutcome {
721
+ /** Whether a PoW solution was submitted at all. */
722
+ provided: boolean;
723
+ /** Whether the submitted solution verified. */
724
+ valid?: boolean;
725
+ /** Failure reason when `valid` is false. */
726
+ reason?: string;
727
+ /** Server-measured solve time in ms (un-spoofable). */
728
+ serverElapsed?: number;
729
+ /** Nonce bound to the verified challenge. */
730
+ nonce?: string;
731
+ }
732
+ /** Per-request context for scoring. */
733
+ interface DetectionContext {
734
+ ip: string;
735
+ siteKey: string;
736
+ userAgent: string;
737
+ /** Lower-cased request headers. */
738
+ headers?: Record<string, string>;
739
+ /** Client-supplied JA3 hash (spoofable). */
740
+ ja3Hash?: string | null;
741
+ /** Trusted reverse-proxy header names carrying a JA4 fingerprint. */
742
+ trustedJA4Headers?: string[];
743
+ /** Proof-of-work verification outcome (supplied by the PoW subsystem). */
744
+ pow?: PoWOutcome;
745
+ /**
746
+ * Additional detections to fold into scoring, produced by an outer
747
+ * orchestrator (e.g. the signals-tampering check in the Captcha service).
748
+ */
749
+ extraDetections?: Detection[];
750
+ }
751
+ /** Final verdict returned by {@link DetectionEngine.score}. */
752
+ interface Verdict {
753
+ /** True when the weighted score is below the success threshold (< 0.5). */
754
+ success: boolean;
755
+ /** Weighted final score, 0..1. */
756
+ score: number;
757
+ /** Recommended action. */
758
+ recommendation: Recommendation;
759
+ /** Per-category aggregated scores. */
760
+ categoryScores: CategoryScores;
761
+ /** Every triggered detection. */
762
+ detections: Detection[];
763
+ /** Unix seconds at evaluation time. */
764
+ timestamp: number;
765
+ }
766
+
767
+ /**
768
+ * In-memory stores backing the stateful detectors (fingerprint correlation and
769
+ * rate abuse). Ported from FCaptcha index.js.
770
+ *
771
+ * These are defined behind interfaces so Phase 2 can swap in a shared/Redis
772
+ * backend for serverless and multi-instance deployments.
773
+ */
774
+ /** Tracks fingerprint ↔ IP relationships to spot distributed attacks. */
775
+ interface FingerprintStore {
776
+ record(fp: string, ip: string, siteKey: string): void;
777
+ /** Number of distinct fingerprints seen from `ip`. */
778
+ getIpFpCount(ip: string): number;
779
+ /** Number of distinct IPs that produced fingerprint `fp` for `siteKey`. */
780
+ getFpIpCount(fp: string, siteKey: string): number;
781
+ }
782
+ /** Sliding-window request counter. */
783
+ interface RateLimiter {
784
+ /** Returns `[exceeded, count]` for the window, recording this hit. */
785
+ check(key: string, windowSeconds?: number, maxRequests?: number): [boolean, number];
786
+ }
787
+ declare class InMemoryFingerprintStore implements FingerprintStore {
788
+ private fingerprints;
789
+ private ipFingerprints;
790
+ record(fp: string, ip: string, siteKey: string): void;
791
+ getIpFpCount(ip: string): number;
792
+ getFpIpCount(fp: string, siteKey: string): number;
793
+ }
794
+ declare class InMemoryRateLimiter implements RateLimiter {
795
+ private requests;
796
+ check(key: string, windowSeconds?: number, maxRequests?: number): [boolean, number];
797
+ }
798
+
799
+ /**
800
+ * Detection engine.
801
+ *
802
+ * Runs the full FCaptcha detector suite in-process and produces a {@link Verdict}.
803
+ * Mirrors the reference server's `runVerification` orchestration. The actual
804
+ * proof-of-work crypto and token issuance land in Phase 2 — for now the caller
805
+ * supplies a {@link PoWOutcome} and the engine emits the matching detections.
806
+ */
807
+
808
+ interface DetectionEngineOptions {
809
+ /** Override the per-category weights (defaults to {@link DEFAULT_WEIGHTS}). */
810
+ weights?: Record<string, number>;
811
+ /**
812
+ * When true (default), a request with no PoW outcome emits a hard-fail "No PoW
813
+ * solution provided" detection — matching the reference server. Set false to
814
+ * score raw signals without requiring proof-of-work.
815
+ */
816
+ requirePoW?: boolean;
817
+ /** Fingerprint-correlation store (defaults to an in-memory store). */
818
+ fingerprintStore?: FingerprintStore;
819
+ /** Rate limiter for rate-abuse detection (defaults to in-memory). */
820
+ rateLimiter?: RateLimiter;
821
+ }
822
+ declare class DetectionEngine {
823
+ private readonly weights;
824
+ private readonly requirePoW;
825
+ private readonly fingerprintStore;
826
+ private readonly rateLimiter;
827
+ constructor(options?: DetectionEngineOptions);
828
+ /** Score `signals` for the given request context and return a verdict. */
829
+ score(signals: Signals, context: DetectionContext): Verdict;
830
+ }
831
+
832
+ /** Score aggregation: per-category confidence-weighted means → weighted total. */
833
+
834
+ /**
835
+ * Aggregate detections into per-category scores. Each category's score is the
836
+ * confidence-weighted mean of its detections' scores, capped at 1.0. Categories
837
+ * present in `weights` but with no detections are filled with 0.
838
+ */
839
+ declare function calculateCategoryScores(detections: Detection[], weights: Record<string, number>): CategoryScores;
840
+ /** Combine category scores into the final weighted score (capped at 1.0). */
841
+ declare function calculateFinalScore(categoryScores: CategoryScores, weights: Record<string, number>): number;
842
+ /** Map a final score to an action recommendation. */
843
+ declare function recommend(finalScore: number): Recommendation;
844
+
845
+ /**
846
+ * Category weights and automation UA patterns.
847
+ *
848
+ * Values match the FCaptcha standalone server (server.js), which is the most
849
+ * complete variant of the engine and the one the reference test suite exercises.
850
+ */
851
+ /** Default per-category weights used to compute the final score. */
852
+ declare const DEFAULT_WEIGHTS: Record<string, number>;
853
+
854
+ /** True when `ip` falls inside a known datacenter CIDR block (IPv4 only). */
855
+ declare function isDatacenterIP(ip: string): boolean;
856
+
857
+ /**
858
+ * User-Agent parsing and bot-pattern matching. Ported from FCaptcha detection.js.
859
+ */
860
+ interface UserAgentInfo {
861
+ browser: string | null;
862
+ os: string | null;
863
+ isMobile: boolean;
864
+ isBot: boolean;
865
+ botName: string | null;
866
+ }
867
+ /** True when the UA looks like a mobile device. */
868
+ declare function isMobileUA(userAgent: string): boolean;
869
+ /** Extract browser/OS/bot info from a User-Agent string. */
870
+ declare function parseUserAgent(ua: string): UserAgentInfo;
871
+
872
+ /** Types for the self-hosted captcha service (PoW + scoring + tokens). */
873
+
874
+ /** Signed challenge returned to the client to solve. */
875
+ interface ChallengeData {
876
+ /** Challenge id (hex). */
877
+ id: string;
878
+ siteKey: string;
879
+ /** Generation time, ms epoch. */
880
+ timestamp: number;
881
+ /** Expiry time, ms epoch. */
882
+ expiresAt: number;
883
+ /** Leading-zero difficulty the solution hash must satisfy. */
884
+ difficulty: number;
885
+ /** Random nonce bound to the challenge (echoed back in signals). */
886
+ nonce: string;
887
+ /** Hash prefix the client iterates over: `${id}:${timestamp}:${difficulty}`. */
888
+ prefix: string;
889
+ /** HMAC signature over the challenge. */
890
+ sig: string;
891
+ }
892
+ /** Stored challenge record (server-side only — never sent to the client). */
893
+ interface StoredChallenge extends ChallengeData {
894
+ ip: string;
895
+ createdAt: number;
896
+ }
897
+ /** A client's proof-of-work solution. */
898
+ interface PoWSolution {
899
+ challengeId: string;
900
+ nonce: number | string;
901
+ hash: string;
902
+ /** Optional commitment binding the solution to the submitted signals. */
903
+ signalsHash?: string;
904
+ }
905
+ /** Result of verifying a PoW solution. */
906
+ interface PoWVerification {
907
+ valid: boolean;
908
+ reason?: string;
909
+ difficulty?: number;
910
+ /** Server-measured solve time in ms (un-spoofable). */
911
+ serverElapsed?: number;
912
+ /** The challenge's bound nonce. */
913
+ nonce?: string;
914
+ }
915
+ /** Result of verifying an issued token. */
916
+ interface TokenVerification {
917
+ valid: boolean;
918
+ reason?: string;
919
+ site_key?: string;
920
+ timestamp?: number;
921
+ score?: number;
922
+ ip_hash?: string;
923
+ }
924
+ /** Input to {@link Captcha.verify} / {@link Captcha.score}. */
925
+ interface VerifyInput {
926
+ siteKey: string;
927
+ ip: string;
928
+ userAgent: string;
929
+ /** Lower-cased request headers. */
930
+ headers?: Record<string, string>;
931
+ /** Parsed client signals. */
932
+ signals?: Signals;
933
+ /** Client PoW solution. */
934
+ powSolution?: PoWSolution | null;
935
+ /** Raw signals JSON used for the commitment check (overrides `signals`). */
936
+ signalsJson?: string | null;
937
+ /** Client-reported PoW timing, injected into `signals.temporal.pow`. */
938
+ powTiming?: {
939
+ duration?: number;
940
+ iterations?: number;
941
+ } | null;
942
+ /** Client-supplied JA3 hash (spoofable). */
943
+ ja3Hash?: string | null;
944
+ }
945
+ /** A verdict plus an issued token (present only on success). */
946
+ interface VerifyResult extends Verdict {
947
+ /** base64url session token, or null when the request did not pass. */
948
+ token: string | null;
949
+ }
950
+ /** Invisible-mode (`score`) result. */
951
+ interface ScoreResult {
952
+ success: boolean;
953
+ score: number;
954
+ token: string | null;
955
+ action: string;
956
+ recommendation: Recommendation;
957
+ }
958
+
959
+ /**
960
+ * Proof-of-work challenge issuance and verification.
961
+ *
962
+ * Ported from FCaptcha server.js `powChallengeStore`. HMAC-signed challenges,
963
+ * SHA-256 leading-zero difficulty, one-time-use replay protection, 5-minute
964
+ * expiry, optional signals-commitment binding, and un-spoofable server-side
965
+ * timing. The challenge store is pluggable so Phase-later work can back it with
966
+ * Redis for serverless / multi-instance deployments.
967
+ */
968
+
969
+ /** Persistence for in-flight challenges and consumed solutions. */
970
+ interface ChallengeStore {
971
+ put(challenge: StoredChallenge): void;
972
+ get(id: string): StoredChallenge | undefined;
973
+ delete(id: string): void;
974
+ /** Returns false if the solution key was already consumed (replay). */
975
+ markSolutionUsed(solutionKey: string): boolean;
976
+ }
977
+ declare class InMemoryChallengeStore implements ChallengeStore {
978
+ private challenges;
979
+ private usedSolutions;
980
+ put(challenge: StoredChallenge): void;
981
+ get(id: string): StoredChallenge | undefined;
982
+ delete(id: string): void;
983
+ markSolutionUsed(solutionKey: string): boolean;
984
+ private cleanup;
985
+ }
986
+ interface PoWManagerOptions {
987
+ secret: string;
988
+ store?: ChallengeStore;
989
+ /** Shared rate limiter used for difficulty scaling. */
990
+ rateLimiter?: RateLimiter;
991
+ }
992
+ declare class PoWManager {
993
+ private readonly secret;
994
+ private readonly store;
995
+ private readonly rateLimiter;
996
+ constructor(options: PoWManagerOptions);
997
+ /** Difficulty scaled by IP reputation and request rate (4..6). */
998
+ scaleDifficulty(siteKey: string, ip: string): number;
999
+ /** Generate and store a signed challenge. */
1000
+ generate(siteKey: string, ip: string, difficulty?: number): ChallengeData;
1001
+ /** Verify a submitted solution. `signalsHash` binds it to the signals. */
1002
+ verify(solution: PoWSolution, siteKey: string, signalsHash?: string | null): PoWVerification;
1003
+ }
1004
+
1005
+ /**
1006
+ * Session token issuance and verification.
1007
+ *
1008
+ * Ported from FCaptcha server.js `generateToken`/`verifyToken` + `tokenStore`.
1009
+ * Tokens are base64url-encoded JSON with an HMAC signature, a 5-minute expiry,
1010
+ * an IP-hash binding, and single-use replay protection.
1011
+ */
1012
+
1013
+ /** Tracks consumed token signatures to prevent replay. */
1014
+ interface TokenStore {
1015
+ /** Returns false if the signature was already consumed. */
1016
+ markUsed(sig: string): boolean;
1017
+ isUsed(sig: string): boolean;
1018
+ }
1019
+ declare class InMemoryTokenStore implements TokenStore {
1020
+ private usedTokens;
1021
+ markUsed(sig: string): boolean;
1022
+ isUsed(sig: string): boolean;
1023
+ }
1024
+ interface TokenManagerOptions {
1025
+ secret: string;
1026
+ store?: TokenStore;
1027
+ }
1028
+ declare class TokenManager {
1029
+ private readonly secret;
1030
+ private readonly store;
1031
+ constructor(options: TokenManagerOptions);
1032
+ /** Issue a signed, IP-bound token for a passing request. */
1033
+ issue(ip: string, siteKey: string, score: number): string;
1034
+ /** Verify a token: signature, expiry, replay, and optional IP binding. */
1035
+ verify(token: string, ip?: string | null): TokenVerification;
1036
+ }
1037
+
1038
+ /**
1039
+ * Self-hosted captcha service.
1040
+ *
1041
+ * Composes the in-process {@link DetectionEngine} with proof-of-work and token
1042
+ * issuance to reproduce the FCaptcha server's `runVerification` flow end-to-end:
1043
+ * issue challenge → verify PoW → score signals → issue session token. Runs
1044
+ * entirely in-process; only IP enrichment remains a remote call elsewhere in
1045
+ * the SDK.
1046
+ */
1047
+
1048
+ interface CaptchaOptions {
1049
+ /** HMAC secret for signing challenges and tokens. Required in production. */
1050
+ secret?: string;
1051
+ /** Override per-category detection weights. */
1052
+ weights?: Record<string, number>;
1053
+ /** Trusted reverse-proxy header names carrying a JA4 fingerprint. */
1054
+ trustedJA4Headers?: string[];
1055
+ /** Pluggable stores (default to in-memory; swap for Redis in production). */
1056
+ challengeStore?: ChallengeStore;
1057
+ tokenStore?: TokenStore;
1058
+ fingerprintStore?: FingerprintStore;
1059
+ rateLimiter?: RateLimiter;
1060
+ }
1061
+ declare class Captcha {
1062
+ private readonly engine;
1063
+ private readonly pow;
1064
+ private readonly tokens;
1065
+ private readonly trustedJA4Headers;
1066
+ constructor(options?: CaptchaOptions);
1067
+ /** Issue a PoW challenge for the client to solve (difficulty auto-scaled). */
1068
+ issueChallenge(siteKey: string, ip: string, difficulty?: number): ChallengeData;
1069
+ /**
1070
+ * Verify a submission: checks the signals commitment, verifies PoW, scores the
1071
+ * signals, and issues a session token on success. Mirrors `runVerification`.
1072
+ */
1073
+ verify(input: VerifyInput): VerifyResult;
1074
+ /** Invisible-mode scoring — same pipeline, returns a compact result + action. */
1075
+ score(input: VerifyInput & {
1076
+ action?: string;
1077
+ }): ScoreResult;
1078
+ /** Verify a previously issued token (single-use, optionally IP-bound). */
1079
+ verifyToken(token: string, ip?: string | null): TokenVerification;
1080
+ }
1081
+
1082
+ /**
1083
+ * Validate an HMAC signing secret. Throws when the secret is missing/empty, or
1084
+ * when it is the insecure default while `NODE_ENV === 'production'`. In
1085
+ * non-production environments a missing secret falls back to the insecure
1086
+ * default (with the returned flag set) so local development works out of the box.
1087
+ */
1088
+ declare function resolveSecret(secret?: string): string;
1089
+
1090
+ /**
1091
+ * Framework-agnostic HTTP handler for the captcha endpoints.
1092
+ *
1093
+ * Maps normalized requests to the {@link Captcha} service so each framework
1094
+ * adapter (Express/Fastify/Next.js) only has to translate its own req/res into
1095
+ * this shape. Routes (under a configurable base path, default `/__webdecoy`):
1096
+ *
1097
+ * GET {base}/challenge?siteKey= → issue a PoW challenge
1098
+ * POST {base}/verify → verify a checkbox submission
1099
+ * POST {base}/score → invisible-mode score
1100
+ * POST {base}/token/verify → verify an issued token
1101
+ */
1102
+
1103
+ /** Normalized inbound request the adapters construct. */
1104
+ interface CaptchaRequest {
1105
+ method: string;
1106
+ /** URL pathname (no query string). */
1107
+ pathname: string;
1108
+ query: Record<string, string | undefined>;
1109
+ /** Lower-cased headers. */
1110
+ headers: Record<string, string>;
1111
+ /** Parsed JSON body (for POST routes). */
1112
+ body?: unknown;
1113
+ /** Resolved client IP. */
1114
+ ip: string;
1115
+ }
1116
+ /** Normalized response the adapters write back. */
1117
+ interface CaptchaHttpResponse {
1118
+ status: number;
1119
+ headers: Record<string, string>;
1120
+ body: unknown;
1121
+ }
1122
+ interface CaptchaEndpointsOptions extends CaptchaOptions {
1123
+ /** Base path the routes are mounted under (default `/__webdecoy`). */
1124
+ basePath?: string;
1125
+ }
1126
+ /**
1127
+ * Build a captcha request handler. The returned function resolves to a response
1128
+ * for a matching route, or `null` when the request is not a captcha route (so
1129
+ * middleware can fall through to the next handler).
1130
+ */
1131
+ declare function createCaptchaEndpoints(options?: CaptchaEndpointsOptions): {
1132
+ captcha: Captcha;
1133
+ basePath: string;
1134
+ handle: (req: CaptchaRequest) => Promise<CaptchaHttpResponse | null>;
1135
+ };
1136
+ type CaptchaEndpoints = ReturnType<typeof createCaptchaEndpoints>;
1137
+
1138
+ export { type BehavioralSignals, Captcha, type CaptchaEndpoints, type CaptchaEndpointsOptions, type CaptchaHttpResponse, type CaptchaOptions, type CaptchaRequest, type CategoryScores, type ChallengeData, type ChallengeStore, DEFAULT_WEIGHTS, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, type EnvironmentalSignals, type FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, 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 Verdict, type VerifyInput, type VerifyResult, type ViolationEvent, WebDecoy, type WebDecoyConfig, calculateCategoryScores, calculateFinalScore, createCaptchaEndpoints, filter, isDatacenterIP, isMobileUA, parseUserAgent, rateLimit, recommend, resolveSecret };