FastAPI/BotProtection/ProofOfWork.pm

filter: Statementstmt 100% 44 / 44 Branchbran 92.8% 13 / 14 Conditioncond 44.4% 12 / 27 MC/DCmcdc 25.0% 3 / 12 Subroutinesub 100% 9 / 9 Podpod 100% 2 / 2 totaltotal 76.8% 83 / 108 CC 18 SCAR 25.8
CC
18
Cov
81%
verify
22.8
__ANON__
3.0
_secure_compare
3.0
CRAP 13.2
« FastAPI.pm ↑ Summary FastAPI/ResponseModel.pm »
1 package PAGI::FastAPI::BotProtection::ProofOfWork;
2  
3 25 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 25 ▶use experimental 'class';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 25 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 25 our $VERSION = qv('v1.7.3');
8 25 our $AUTHORITY = 'cpan:MANWAR';
9  
10 25 ▶use Digest::SHA qw(sha256_hex hmac_sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 25 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 25 class PAGI::FastAPI::BotProtection::ProofOfWork {
14 25 field $difficulty :param = 3; # Number of required leading zeros in SHA-256 hash
15 25 field $ttl :param = 300; # Challenge validity duration in seconds
16 25 field $secret :param;
17  
18 15 ▶ ADJUST {
Subroutine __ANON__: called CC=3 SCAR=11.0
19 15 ▶ die "ProofOfWork: 'secret' parameter must be defined and non-empty in production\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $secret and length $secret > 0 2 13 15
Condition100%3/3
defined $secret and length $secret > 0
!ll&&!rl&&r
1113
MC/DC100%2/2
defined $secret and length $secret > 0
defined $secret length $secret > 0
Truth table100%3/3
A and B
A= defined $secretB= length $secret > 0
ABresult
0X0
100
111
20 unless defined $secret && length($secret) > 0;
21 }
22  
23 # Fields are joined/split on "|" rather than ":" because IPv6 addresses
24 # (e.g. "::1", "2001:db8::1") legitimately contain colons; splitting a
25 # colon-delimited challenge string on ":" silently mis-parses every
26 # IPv6 client and makes verify() always fail for them. "|" never
27 # appears in an IP literal, a decimal timestamp, or a decimal
28 # difficulty, so it's a safe, unambiguous delimiter for this format.
29 14 ▶ method create_challenge ($client_ip) {
Subroutine create_challenge: called CC=1 SCAR=0.0
Pod documented
30 14 my $now = int(time());
31 14 my $expires = $now + $ttl;
32 14 my $payload = "${client_ip}|${expires}|${difficulty}";
33 14 my $signature = substr(hmac_sha256_hex($payload, $secret), 0, 16);
34  
35 return {
36 14 challenge => "${payload}|${signature}",
37 difficulty => $difficulty,
38 expires => $expires,
39 };
40 25 }
41  
42 19 ▶ method verify ($challenge_str, $nonce, $client_ip) {
Subroutine verify: called CC=14 SCAR=31.3
Pod documented
43 19 ▶ return 0 unless defined $challenge_str && defined $nonce;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $challenge_str and defined $nonce 3 16 19
Condition66%2/3
defined $challenge_str and defined $nonce
!ll&&!rl&&r
3016
MC/DC50%1/2
defined $challenge_str and defined $nonce
defined $challenge_str defined $nonce
Truth table66%2/3
A and B
A= defined $challenge_strB= defined $nonce
ABresult
0X0
100
111
44  
45 16 my ($ip, $expires, $diff, $sig) = split(/\|/, $challenge_str, 4);
46 16 ▶ return 0 unless defined $ip && length $ip
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ip and length $ip and defined $expires and length $expires and defined $diff and length $diff and defined $sig and length $sig 0 16 16
Condition33%7/21
defined $ip and length $ip and defined $expires and length $expires and defined $diff and length $diff and defined $sig and length $sig
!ll&&!rl&&r
0016
defined $ip and length $ip and defined $expires and length $expires and defined $diff and length $diff and defined $sig
!ll&&!rl&&r
0016
defined $ip and length $ip and defined $expires and length $expires and defined $diff and length $diff
!ll&&!rl&&r
0016
defined $ip and length $ip and defined $expires and length $expires and defined $diff
!ll&&!rl&&r
0016
defined $ip and length $ip and defined $expires and length $expires
!ll&&!rl&&r
0016
defined $ip and length $ip and defined $expires
!ll&&!rl&&r
0016
defined $ip and length $ip
!ll&&!rl&&r
0016
MC/DC0%0/8
defined $ip and length $ip and defined $expires and length $expires and defined $diff and length $diff and defined $sig and length $sig
defined $ip length $ip defined $expires length $expires defined $diff length $diff defined $sig length $sig
Truth table11%1/9
A and B and C and D and E and F and G and H
A= defined $ipB= length $ipC= defined $expiresD= length $expiresE= defined $diffF= length $diffG= defined $sigH= length $sig
ABCDEFGHresult
0XXXXXXX0
10XXXXXX0
110XXXXX0
1110XXXX0
11110XXX0
111110XX0
1111110X0
111111100
111111111
47 && defined $expires && length $expires
48 && defined $diff && length $diff
49 && defined $sig && length $sig;
50  
51 # 1. IP validation
52 16 ▶ return 0 if $ip ne $client_ip;
Branch: 1 branch
BranchTrueFalseTotal
if $ip ne $client_ip 4 12 16
53  
54 # 2. Expiration validation
55 12 ▶ return 0 if time() > $expires;
Branch: 1 branch
BranchTrueFalseTotal
if &PAGI::FastAPI::BotProtection::ProofOfWork::time() > $expires 1 11 12
56  
57 # 3. HMAC signature integrity check (constant-time comparison to
58 # avoid leaking signature bytes via response-timing side channel)
59 11 my $expected_payload = "${ip}|${expires}|${diff}";
60 11 my $expected_sig = substr(hmac_sha256_hex($expected_payload, $secret), 0, 16);
61 11 ▶ return 0 unless _secure_compare($sig, $expected_sig);
Branch: 1 branch
BranchTrueFalseTotal
unless _secure_compare($sig, $expected_sig) 1 10 11
62  
63 # 4. Hash collision check (Proof-of-Work verification)
64 10 my $hash = sha256_hex("${challenge_str}:${nonce}");
65 10 my $target = '0' x $diff;
66  
67 10 return index($hash, $target) == 0;
68 22 }
69  
70 11 ▶ sub _secure_compare ($a, $b) {
Subroutine _secure_compare: called CC=3 SCAR=11.0
71 11 ▶ return 0 unless length($a) == length($b);
Branch: 1 branch
BranchTrueFalseTotal
unless length $a == length $b 1 10 11
72 10 my $diff = 0;
73 10 $diff |= ord(substr($a, $_, 1)) ^ ord(substr($b, $_, 1)) for 0 .. length($a) - 1;
74 10 return $diff == 0;
75 }
76 }
77  
78 =encoding utf-8
79  
80 =head1 NAME
81  
82 PAGI::FastAPI::BotProtection::ProofOfWork - Stateless Proof-of-Work Bot Mitigation Engine
83  
84 =head1 VERSION
85  
86 Version v1.7.3
87  
88 =head1 SYNOPSIS
89  
90 use PAGI::FastAPI::BotProtection::ProofOfWork;
91  
92 my $pow = PAGI::FastAPI::BotProtection::ProofOfWork->new(
93 difficulty => 4,
94 secret => 'app_secret_key',
95 ttl => 300,
96 );
97  
98 # Generate a signed challenge for an incoming IP
99 my $challenge = $pow->create_challenge('192.168.1.100');
100  
101 # Verify client submission
102 my $is_valid = $pow->verify(
103 $challenge->{challenge},
104 $client_nonce,
105 '192.168.1.100'
106 );
107  
108 =head1 DESCRIPTION
109  
110 C<PAGI::FastAPI::BotProtection::ProofOfWork> provides a stateless,
111 cryptographic Proof-of-Work (PoW) challenge-and-response engine designed to
112 mitigate automated web scraping, credential stuffing, and bot attacks.
113  
114 When a client requests access, the engine generates an HMAC-signed challenge
115 requiring the client's browser to compute a SHA-256 hash collision (finding
116 a nonce that yields a hash beginning with a set number of leading zeros).
117  
118 Because verification relies on HMAC signatures, the engine is entirely
119 stateless and does not require shared memory, database storage, or external
120 caching backends.
121  
122 Challenge strings are safe to use with both IPv4 and IPv6 client addresses;
123 internally, fields are delimited with C<|> rather than C<:>, since IPv6
124 literals (e.g. C<::1>, C<2001:db8::1>) contain colons themselves.
125  
126 =head1 CONSTRUCTOR
127  
128 =head2 C<new(%options)>
129  
130 Instantiates a new Proof-of-Work engine. Accepts the following named parameters:
131  
132 =over 4
133  
134 =item * C<difficulty> (Optional)
135  
136 Integer specifying the number of leading hexadecimal zeros required in the
137 calculated SHA-256 hash collision. Higher values exponentially increase CPU
138 effort for the client while keeping server verification costs near instant.
139 Defaults to C<3>.
140  
141 =item * C<secret> (Required)
142  
143 A secret seed scalar used to generate HMAC signatures for challenges.
144 B<Must be provided and non-empty> to prevent challenge tampering or forgery.
145  
146 =item * C<ttl> (Optional)
147  
148 Integer specifying the validity window of generated challenges in seconds.
149 Defaults to C<300> (5 minutes).
150  
151 =back
152  
153 =head1 METHODS
154  
155 =head2 C<create_challenge($client_ip)>
156  
157 my $data = $pow->create_challenge('10.0.0.1');
158  
159 Generates a signed challenge string bound to the client's IP address,
160 difficulty level, and timestamp.
161  
162 Returns a HashRef containing:
163  
164 =over 4
165  
166 =item * C<challenge>: The signed challenge token string.
167  
168 =item * C<difficulty>: The difficulty integer.
169  
170 =item * C<expires>: The UNIX expiration epoch.
171  
172 =back
173  
174 =head2 C<verify($challenge_str, $nonce, $client_ip)>
175  
176 my $bool = $pow->verify($challenge_str, $nonce, $client_ip);
177  
178 Validates a client's Proof-of-Work solution. Performs signature integrity verification, expiration checking, IP matching, and cryptographic hash collision calculation.
179  
180 Returns C<1> if valid, or C<0> if verification fails.
181  
182 =head1 SEE ALSO
183  
184 L<PAGI::FastAPI::Middleware::BotProtection>, L<PAGI::FastAPI>
185  
186 =head1 AUTHOR
187  
188 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
189  
190 =head1 BUGS
191  
192 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/PAGI-FastAPI/issues>.
193 I will be notified and then you'll automatically be notified of progress on your
194 bug as I make changes.
195  
196 =head1 SUPPORT
197  
198 You can find documentation for this module with the perldoc command.
199  
200 perldoc PAGI::FastAPI::BotProtection::ProofOfWork
201  
202 You can also look for information at:
203  
204 =over 4
205  
206 =item * BUG Report
207  
208 L<https://github.com/manwar/PAGI-FastAPI/issues>
209  
210 =item * Search MetaCPAN
211  
212 L<https://metacpan.org/dist/PAGI-FastAPI/>
213  
214 =back
215  
216 =head1 LICENSE AND COPYRIGHT
217  
218 Copyright (C) 2026 Mohammad Sajid Anwar.
219  
220 This program is free software; you can redistribute it and/or modify it under
221 the terms of the Artistic License (2.0).
222  
223 =cut
224  
225 22 1; # End of PAGI::FastAPI::BotProtection::ProofOfWork
« FastAPI.pm ↑ Summary FastAPI/ResponseModel.pm »