lib/Captcha/Stateless/Text.pm

filter: Statementstmt 50.0% 69 / 138 Branchbran 33.3% 10 / 30 Conditioncond 21.0% 4 / 19 MC/DCmcdc 18.1% 2 / 11 Subroutinesub 65.6% 21 / 32 Podpod 0.0% 0 / 14 totaltotal 43.4% 106 / 244 CC 27 SCAR 35.5
CC
27
Cov
44%
__ANON__
110.0
__ANON__
90.0
validate
8.2
CRAP 34.9
↑ Summary
1 ###############################################################################
2 # Captcha::Stateless::Text module for Perl.
3 # Copyright (C) 2024, Lester Hightower <hightowe@cpan.org>
4 ###############################################################################
5  
6 package Captcha::Stateless::Text;
7  
8 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use v5.20; # Version needed for feature signatures
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use feature qw(signatures);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶no warnings qw(experimental::signatures);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Sub::Util qw(set_subname); # core
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use MIME::Base64 qw(); # core
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use Digest::MD5 qw(md5_hex); # core
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use Data::Dumper; # core
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use Try::Tiny; # libtry-tiny-perl
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use Crypt::Mode::CBC; # libcryptx-perl
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use JSON qw(to_json from_json); # libjson-perl
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use Lingua::EN::Nums2Words; # From CPAN (cpanm Lingua::EN::Nums2Words)
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 $Data::Dumper::Sortkeys = 1;
21 1 Lingua::EN::Nums2Words::set_case('lower');
22  
23 1 our $VERSION = "0.5";
24 0 ▶sub Version { $VERSION; }
Subroutine Version: not called CC=1 SCAR=6.9
Pod undocumented
25  
26 1 my %QAfuncs = {}; # Holds our private __ANON__ subroutines
27  
28 1 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod undocumented
29 1 my $class = shift;
30 1 my $self = {
31 cipher => 'AES',
32 iv => 'gkbx5g9hsvhqrosg', # Must be 16 bytes / 128 bits
33 key => 'tyDjb39dQ20pdva0lTpyuiowWfxSSwa9', # 32 bytes / 256 bits (AES256)
34 ep_pre => 'captcha'.lc(substr(md5_hex(__PACKAGE__), 0, 6)).'.',
35 };
36 1 bless $self, $class;
37 1 return $self;
38 }
39  
40 #############################################################################
41 # Object parameter get/set functions ########################################
42 #############################################################################
43 1 ▶sub get_ep_pre($self) { return $self->{ep_pre}; }
Subroutine get_ep_pre: called CC=1 SCAR=0.0
Pod undocumented
44 2 ▶sub set_self_val($self, $k, $v) { $self->{$k} = $v; }
Subroutine set_self_val: called CC=1 SCAR=0.0
Pod undocumented
45 0 ▶sub set_cipher($self, $v) { set_self_val($self, 'cipher', $v); }
Subroutine set_cipher: not called CC=1 SCAR=6.9
Pod undocumented
46 1 ▶sub set_iv($self, $v) { set_self_val($self, 'iv', $v); }
Subroutine set_iv: called CC=1 SCAR=0.0
Pod undocumented
47 1 ▶sub set_key($self, $v) { set_self_val($self, 'key', $v); }
Subroutine set_key: called CC=1 SCAR=0.0
Pod undocumented
48  
49 #############################################################################
50 # Crypto functions ##########################################################
51 #############################################################################
52 0 ▶sub encrypt_b64($self, $data) {
Subroutine encrypt_b64: not called CC=1 SCAR=6.9
Pod undocumented
53 0 my $d = my_crypt_cbc($self, 'encrypt', $self->{cipher}, $self->{key}, $self->{iv}, $data);
54 0 return MIME::Base64::encode_base64url($d, ''); # '' for no line breaks
55 }
56 4 ▶sub decrypt_b64($self, $data) {
Subroutine decrypt_b64: called CC=1 SCAR=0.0
Pod undocumented
57 4 my $d = MIME::Base64::decode_base64url($data);
58 4 return my_crypt_cbc($self, 'decrypt', $self->{cipher}, $self->{key}, $self->{iv}, $d);
59 }
60 # Helper function to centralize and reduce code duplication
61 4 ▶sub my_crypt_cbc($self, $mode, $cipher, $key, $iv, $data) {
Subroutine my_crypt_cbc: called CC=3 SCAR=15.0
Pod undocumented
62 4 my $pkg = __PACKAGE__;
63  
64 4 my $cbc = Crypt::Mode::CBC->new($cipher, 1);
65 4 ▶ if ($mode eq 'encrypt') {
Branch: 2 branches
BranchTrueFalseTotal
if ($mode eq 'encrypt') { } 0 4 4
elsif ($mode eq 'decrypt') { } 4 0 4
66 0 my $payload = undef;
67 0 ▶ try {
Subroutine __ANON__: not called CC=1 SCAR=6.9
68 0 $payload = $cbc->encrypt($data, $key, $iv); # ENCRYPT
69 0 ▶ } catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
70 0 warn("$pkg my_crypt_cbc() failed to $mode with error: $_");
71 0 $payload = undef;
72 0 };
73 0 return $payload;
74 } elsif ($mode eq 'decrypt') {
75 4 my $payload = undef;
76 4 ▶ try {
Subroutine __ANON__: called CC=1 SCAR=0.0
77 4 $payload = $cbc->decrypt($data, $key, $iv); # DECRYPT
78 0 ▶ } catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
79 0 warn("$pkg my_crypt_cbc() failed to $mode with error: $_");
80 0 $payload = undef;
81 4 };
82 4 return $payload;
83 }
84 0 return undef;
85 }
86 #############################################################################
87 #############################################################################
88  
89 #############################################################################
90 # Captcha creation functions ################################################
91 #############################################################################
92 0 ▶sub getQA_chars {
Subroutine getQA_chars: not called CC=1 SCAR=6.9
Pod undocumented
93 0 my $qa = $QAfuncs{chars}(@_);
94 0 $_[0]->add_enc_payload($qa);
95 0 return $qa;
96 }
97 0 ▶sub getQA_math {
Subroutine getQA_math: not called CC=1 SCAR=6.9
Pod undocumented
98 0 my $qa = $QAfuncs{math}(@_);
99 0 $_[0]->add_enc_payload($qa);
100 0 return $qa;
101 }
102 0 ▶sub add_enc_payload($self, $qa) {
Subroutine add_enc_payload: not called CC=1 SCAR=6.9
Pod undocumented
103 # Make and add the enc_payload
104 0 my $payload_json = to_json($qa);
105 0 my $enc_payload = $self->encrypt_b64($payload_json);
106 0 $qa->{enc_payload} = $self->{ep_pre} . $enc_payload;
107 }
108 5 ▶sub validate($self, $answer, $enc_payload) {
Subroutine validate: called CC=8 SCAR=21.1
Pod undocumented
109 5 my $ep_pre = $self->{ep_pre};
110 5 ▶ return 0 if (!(defined($enc_payload) && length($enc_payload)));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $enc_payload and length $enc_payload 0 5 5
Condition33%1/3
defined $enc_payload and length $enc_payload
!ll&&!rl&&r
005
MC/DC0%0/2
defined $enc_payload and length $enc_payload
defined $enc_payload length $enc_payload
Truth table33%1/3
A and B
A= defined $enc_payloadB= length $enc_payload
ABresult
0X0
100
111
111 5 ▶ return 0 if ($enc_payload !~ m/^\Q$ep_pre\E/); # Invalid payload
Branch: 1 branch
BranchTrueFalseTotal
unless $enc_payload =~ /^\Q$ep_pre\E/u 1 4 5
112 4 $enc_payload =~ s/^\Q$ep_pre\E//; # Trim the prefix
113 4 my $payload = $self->decrypt_b64($enc_payload);
114 4 ▶ return 0 if (!defined($payload));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $payload 0 4 4
115 4 my $qa = from_json($payload);
116 4 ▶ return 1 if ($qa->{a} =~ m/^\d+$/ && $answer == $qa->{a});
Branch: 1 branch
BranchTrueFalseTotal
if $qa->{"a"} =~ /^\d+$/u and $answer == $qa->{"a"} 1 3 4
Condition100%3/3
$qa->{"a"} =~ /^\d+$/u and $answer == $qa->{"a"}
!ll&&!rl&&r
211
MC/DC100%2/2
$qa->{"a"} =~ /^\d+$/u and $answer == $qa->{"a"}
$qa->{"a"} =~ /^\d+$/u $answer == $qa->{"a"}
Truth table100%3/3
A and B
A= $qa->{"a"} =~ /^\d+$/uB= $answer == $qa->{"a"}
ABresult
0X0
100
111
117 3 ▶ return 1 if ($answer eq $qa->{a});
Branch: 1 branch
BranchTrueFalseTotal
if $answer eq $qa->{"a"} 1 2 3
118 2 return 0;
119 }
120  
121 #############################################################################
122 # The subs in %QAfuncs are not callable by the outside world because they are
123 # __ANON__ and not in the Perl sumbol table.
124 #############################################################################
125 0 ▶$QAfuncs{chars} = set_subname(__PACKAGE__."-private:getQA_chars", sub {
Subroutine __ANON__: not called CC=10 SCAR=47.0
126 0 my $self = shift @_;
127 0 ▶ my $q_len = shift @_ // 6;
Condition0%0/2
shift @_ // 6
l!l
00
MC/DC0%0/1
shift @_ // 6
shift @_
Truth table0%0/2
A
A= shift @_
Aresult
11
00
128 0 ▶ my $a_len = shift @_ // 3;
Condition0%0/2
shift @_ // 3
l!l
00
MC/DC0%0/1
shift @_ // 3
shift @_
Truth table0%0/2
A
A= shift @_
Aresult
11
00
129 0 ▶ my $q_sort = shift @_ // 1;
Condition0%0/2
shift @_ // 1
l!l
00
MC/DC0%0/1
shift @_ // 1
shift @_
Truth table0%0/2
A
A= shift @_
Aresult
11
00
130 # Protects again non-sense that will cause an infinite loop.
131 0 ▶ if ($a_len > $q_len) { $q_len = $a_len + 4; }
Branch: 1 branch
BranchTrueFalseTotal
if ($a_len > $q_len) 0 0 0
132 # Build up the question characters
133 0 my @q_chars = ();
134 0 my @src_chars = ('A'..'Z');
135 0 ▶ while (scalar(@q_chars) < $q_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @q_chars < $q_len) 0 0 0
136 0 my $char = $src_chars[int(rand(scalar(@src_chars)))];
137 0 push @q_chars, $char;
138 }
139 # Build the list of "indexes" of answers in the question
140 0 my @a_idxes = ();
141 0 ▶ while (scalar(@a_idxes) < $a_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @a_idxes < $a_len) 0 0 0
142 0 my $indx = int(rand(scalar(@q_chars)));
143 0 my $indx_plus_1 = $indx + 1; # Humans start with 1s not 0s
144 0 ▶ next if (grep(/^\Q$indx_plus_1\E$/, @a_idxes)); # No duplicates
Branch: 1 branch
BranchTrueFalseTotal
if grep /^\Q$indx_plus_1\E$/u, @a_idxes 0 0 0
145 0 push @a_idxes, $indx_plus_1;
146 }
147 0 ▶ my @a_idxes = sort @a_idxes if ($q_sort); # Sort for user convenience
Branch: 1 branch
BranchTrueFalseTotal
if $q_sort 0 0 0
148 0 my @a_chars = map { $q_chars[($_-1)] } @a_idxes; # The answer chars
149 0 my @a_idxws = map { num2word_ordinal($_) } @a_idxes; # num2word them
150  
151 0 my $q_prompt = join(', ', @a_idxws);
152 0 $q_prompt =~ s/, (\w+)$/, and $1/; # Place the word and
153 0 ▶ $q_prompt =~ s/,// if ($#a_idxws < 2); # Kill an unneeded comma
Branch: 1 branch
BranchTrueFalseTotal
if $#a_idxws < 2 0 0 0
154 0 my $q_str = "Provide the $q_prompt characters from ".
155 join('-', @q_chars); # The question
156 #my $q_str = join(',', @a_idxes) . " from ".join('-', @q_chars); # The question
157 0 my $a_str = join('', @a_chars); # The answer
158 0 my $qa = {
159 q => $q_str,
160 a => $a_str,
161 };
162 0 return $qa;
163 1 });
164  
165 0 ▶$QAfuncs{math} = set_subname(__PACKAGE__."-private:getQA_math", sub {
Subroutine __ANON__: not called CC=9 SCAR=45.0
166 0 my $self = shift @_;
167 0 ▶ my $ANSWER_MAX = shift @_ // 11;
Condition0%0/2
shift @_ // 11
l!l
00
MC/DC0%0/1
shift @_ // 11
shift @_
Truth table0%0/2
A
A= shift @_
Aresult
11
00
168 0 ▶ my $ANSWER_MIN = shift @_ // 2;
Condition0%0/2
shift @_ // 2
l!l
00
MC/DC0%0/1
shift @_ // 2
shift @_
Truth table0%0/2
A
A= shift @_
Aresult
11
00
169 0 my @a = (1..15);
170 0 my @b = @a;
171 0 my @QA = ();
172 # Build additions then subtractions
173 0 for my $neg (qw(0 1)) {
174 0 foreach my $a (@a) {
175 0 foreach my $b (@b) {
176 0 my $que = undef;
177 0 ▶ if ($neg) {
Branch: 1 branch
BranchTrueFalseTotal
if ($neg) { } 0 0 0
178 0 $que = "$a - $b";
179 } else {
180 0 $que = "$a + $b";
181 }
182 0 my $ans = eval " $que ";
183 0 ▶ if ($ans <= $ANSWER_MAX && $ans >= $ANSWER_MIN) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ans <= $ANSWER_MAX and $ans >= $ANSWER_MIN) 0 0 0
Condition0%0/3
$ans <= $ANSWER_MAX and $ans >= $ANSWER_MIN
!ll&&!rl&&r
000
MC/DC0%0/2
$ans <= $ANSWER_MAX and $ans >= $ANSWER_MIN
$ans <= $ANSWER_MAX $ans >= $ANSWER_MIN
Truth table0%0/3
A and B
A= $ans <= $ANSWER_MAXB= $ans >= $ANSWER_MIN
ABresult
0X0
100
111
184 0 push @QA, { q => $que, a => $ans };
185 }
186 }
187 }
188 }
189 # Choose a random one to return
190 0 my $qa = $QA[int(rand(scalar(@QA)))];
191 0 return $qa;
192 1 });
193  
194 1 1;
195  
196 ###############################################################################
197 # PERL POD ####################################################################
198 ###############################################################################
199  
200 =head1 NAME
201  
202 Captcha::Stateless::Text - stateless, text-based CAPTCHAs
203  
204 =head1 DESCRIPTION
205  
206 A module to make stateless, text-based CAPTCHAs easy to implement.
207 It supports:
208  
209 * Simple math:
210 "7 + 3 = ?"
211 answer = 10
212 * Character selection:
213 "Provide the second, third, and sixth characters from B-G-Q-E-O-S"
214 answer = GQS
215  
216 =head1 SYNOPSIS
217  
218 use Captcha::Stateless::Text;
219  
220 my $captcha = Captcha::Stateless::Text->new();
221  
222 # Recommend setting these to values that *you* derive
223 # Must be 16 bytes / 128 bits
224 $captcha->set_iv('gkbx5g9hsvhqrosg');
225 # 32 bytes / 256 bits for AES256
226 $captcha->set_key('tyDjb39dQ20pdva0lTpyuiowWfxSSwa9');
227  
228 # Grab a question/answer data structure
229 my $qa = $captcha->getQA_chars();
230 # __or__
231 my $qa = $captcha->getQA_math();
232  
233 # For getQA_chars(), $qa will look similar to this:
234 my $qa_chars = {
235 'q' => 'Provide the first and fifth characters from A-W-N-Z-L-X'
236 'a' => 'AL',
237 'enc_payload' => <<base-64 and url-encoded encrypted data>>,
238 },
239 # For getQA_math(), $qa will look similar to this:
240 my $qa_math = {
241 'q' => '7 + 3',
242 'a' => '10',
243 'enc_payload' => <<base-64 and url-encoded encrypted data>>,
244 };
245  
246 # Your job now is to present the user with the question ($qa->{q}), to
247 # not lose the enc_payload (use a HTML <input type="hidden"> field), to
248 # collect the user's answer, and then validate it, like this:
249 my $is_valid = $captcha->validate($user_answer, $enc_payload_from_qa);
250 if ($is_valid) {
251 print "You win!\n";
252 } else {
253 print "You lose!\n";
254 }
255  
256 =head1 SUBROUTINES
257  
258 The two subroutines that generate the questions and answers have a few
259 options that can be specified to control their behavior.
260  
261 my $qa = $captcha->getQA_chars($q_len, $a_len, $q_sort);
262  
263 OPT DEFAULT DESCRIPTION
264 --------------------------------------------------------------------
265 $q_len 6 The character length of the question string.
266 $a_len 3 The number of characters in the answer.
267 $q_sort 1 Sort the answer characters, so that users will always
268 be asked for characters flowing left-to-right, or
269 require them to "jump around" in the question string.
270  
271 my $qa = $captcha->getQA_math($a_max, $a_min);
272  
273 OPT DEFAULT DESCRIPTION
274 --------------------------------------------------------------------
275 $a_max 11 The maximum value of the answer.
276 $a_min 2 The minimum value of the answer.
277  
278 =head1 COPYRIGHT
279  
280 Copyright (C) 2024, Lester Hightower <hightowe@cpan.org>
281  
282 =head1 LICENSE
283  
284 This software is licensed under the OSI certified Artistic License,
285 one of the licenses of Perl itself.
286  
287 L<http://en.wikipedia.org/wiki/Artistic_License>
288  
289 =cut
290  
291 ###############################################################################
292  
↑ Summary