Plugin/WebPush.pm

filter: Statementstmt 96.4% 108 / 112 Branchbran 62.5% 15 / 24 Conditioncond 46.6% 7 / 15 MC/DCmcdc 11.1% 1 / 9 Subroutinesub 85.7% 24 / 28 Podpod 50.0% 1 / 2 totaltotal 82.1% 156 / 190 CC 19 SCAR 8.5
CC
19
Cov
86%
register
4.1
__ANON__
4.1
_encrypt_helper
3.3
CRAP 2.3
« Command/webpush.pm ↑ Summary
1 package Mojolicious::Plugin::WebPush;
2 4 ▶use Mojo::Base 'Mojolicious::Plugin';
Subroutine BEGIN: called CC=1 SCAR=0.0
3 4 ▶use Mojo::JSON qw(decode_json encode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use Mojo::URL;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use Crypt::PK::ECC;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use MIME::Base64 qw(encode_base64url decode_base64url);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use Crypt::JWT qw(encode_jwt decode_jwt);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use Crypt::RFC8188 qw(ece_encrypt_aes128gcm);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 4 our $VERSION = '0.05';
11  
12 4 my @MANDATORY_CONF = qw(
13 subs_session2user_p
14 save_endpoint
15 subs_create_p
16 subs_read_p
17 subs_delete_p
18 );
19 4 my @AUTH_CONF = qw(claim_sub ecc_private_key);
20 4 my $DEFAULT_PUSH_HANDLER = <<'EOF';
21 event => {
22 var msg = event.data.json();
23 var title = msg.title;
24 delete msg.title;
25 event.waitUntil(self.registration.showNotification(title, msg));
26 }
27 EOF
28  
29 2 ▶sub _decode {
Subroutine _decode: called CC=2 SCAR=7.0
30 2 my ($bytes) = @_;
31 2 my $body = eval { decode_json($bytes) };
32 # conceal error info like versions from attackers
33 2 ▶ return (0, "Malformed request") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 2 2
34 2 (1, $body);
35 }
36  
37 1 ▶sub _error {
Subroutine _error: called CC=1 SCAR=0.0
38 1 my ($c, $error) = @_;
39 1 $c->render(status => 500, json => { errors => [ { message => $error } ] });
40 }
41  
42 4 ▶sub _make_route_handler {
Subroutine _make_route_handler: called CC=1 SCAR=0.0
43 4 my ($subs_session2user_p, $subs_create_p) = @_;
44 2 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
45 2 my ($c) = @_;
46 2 my ($decode_ok, $body) = _decode($c->req->body);
47 2 ▶ return _error($c, $body) if !$decode_ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $decode_ok 0 2 2
48 2 eval { validate_subs_info($body) };
49 2 ▶ return _error($c, $@) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 1 2
50 return $subs_session2user_p->($c, $c->session)->then(
51 1 ▶ sub { $subs_create_p->($c, $_[0], $body) },
Subroutine __ANON__: called CC=1 SCAR=0.0
52 )->then(
53 1 ▶ sub { $c->render(json => { data => { success => \1 } }) },
Subroutine __ANON__: called CC=1 SCAR=0.0
54 0 ▶ sub { _error($c, @_) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
55 1 );
56 4 };
57 }
58  
59 4 ▶sub _make_auth_helper {
Subroutine _make_auth_helper: called CC=2 SCAR=7.0
60 4 my ($app, $conf) = @_;
61 4 ▶ my $exp_offset = $conf->{claim_exp_offset} || 86400;
Condition50%1/2
$conf->{'claim_exp_offset'} || 86400
l!l
04
MC/DC0%0/1
$conf->{'claim_exp_offset'} || 86400
$conf->{'claim_exp_offset'}
Truth table50%1/2
A
A= $conf->{'claim_exp_offset'}
Aresult
11
00
62 4 my $key = Crypt::PK::ECC->new($conf->{ecc_private_key});
63 4 my $claims_start = { sub => $conf->{claim_sub} };
64 4 my $pkey = encode_base64url $key->export_key_raw('public');
65 0 ▶ $app->helper('webpush.public_key' => sub { $pkey });
Subroutine __ANON__: not called CC=1 SCAR=1.2
66 3 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
67 3 my ($c, $subs_info) = @_;
68 3 my $aud = Mojo::URL->new($subs_info->{endpoint})->path(Mojo::Path->new->trailing_slash(0)).'';
69 3 my $claims = { aud => $aud, exp => time + $exp_offset, %$claims_start };
70 3 my $token = encode_jwt key => $key, alg => 'ES256', payload => $claims;
71 3 "vapid t=$token,k=$pkey";
72 4 };
73 }
74  
75 3 ▶sub _verify_helper {
Subroutine _verify_helper: called CC=2 SCAR=7.0
76 3 my ($app, $auth_header_value) = @_;
77 3 (my $schema, $auth_header_value) = split ' ', $auth_header_value;
78 3 ▶ return if $schema ne 'vapid';
Branch: 1 branch
BranchTrueFalseTotal
if $schema ne "vapid" 0 3 3
79 3 my %k2v = map split('=', $_), split ',', $auth_header_value;
80 3 eval {
81 3 my $key = Crypt::PK::ECC->new;
82 3 $key->import_key_raw(decode_base64url($k2v{k}), 'P-256');
83 3 decode_jwt token => $k2v{t}, key => $key, alg => 'ES256', verify_exp => 0;
84 };
85 }
86  
87 3 ▶sub _encrypt_helper {
Subroutine _encrypt_helper: called CC=3 SCAR=12.0
88 3 my ($c, $plaintext, $receiver_key, $auth_key) = @_;
89 3 ▶ die "Invalid p256dh key specified\n"
Branch: 1 branch
BranchTrueFalseTotal
if length $receiver_key != 65 or not $receiver_key =~ /^\x04/u 0 3 3
Condition33%1/3
length $receiver_key != 65 or not $receiver_key =~ /^\x04/u
l!l&&r!l&&!r
003
MC/DC0%0/2
length $receiver_key != 65 or not $receiver_key =~ /^\x04/u
length $receiver_key != 65 not $receiver_key =~ /^\x04/u
Truth table33%1/3
A or not(B)
A= length $receiver_key != 65B= not $receiver_key =~ /^\x04/u
ABresult
1X1
011
000
90 if length($receiver_key) != 65 or $receiver_key !~ /^\x04/;
91 3 my $onetime_key = Crypt::PK::ECC->new->generate_key('prime256v1');
92 3 ece_encrypt_aes128gcm(
93 $plaintext, (undef) x 2, $onetime_key, $receiver_key, $auth_key,
94 );
95 }
96  
97 2 ▶sub _send_helper {
Subroutine _send_helper: called CC=3 SCAR=11.2
98 2 my ($c, $message, $user_id, $ttl, $urgency) = @_;
99 2 ▶ $ttl ||= 30;
Condition50%1/2
$ttl ||= 30
l!l
20
MC/DC0%0/1
$ttl ||= 30
$ttl
Truth table50%1/2
A
A= $ttl
Aresult
11
00
100 2 ▶ $urgency ||= 'normal';
Condition50%1/2
$urgency ||= "normal"
l!l
20
MC/DC0%0/1
$urgency ||= "normal"
$urgency
Truth table50%1/2
A
A= $urgency
Aresult
11
00
101 2 ▶ $c->webpush->read_p($user_id)->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
102 2 my ($subs_info) = @_;
103 my $body = $c->webpush->encrypt(
104 encode_json($message),
105 2 map decode_base64url($_), @{$subs_info->{keys}}{qw(p256dh auth)}
106 );
107 2 my $headers = {
108 Authorization => $c->webpush->authorization($subs_info),
109 'Content-Length' => length($body),
110 'Content-Encoding' => 'aes128gcm',
111 TTL => $ttl,
112 Urgency => $urgency,
113 };
114 2 $c->app->ua->post_p($subs_info->{endpoint}, $headers, $body);
115 2 ▶ })->then(sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
116 2 my ($tx) = @_;
117 1 ▶ return $c->webpush->delete_p($user_id)->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
118 1 { data => { success => \1 } }
119 2 ▶ }) if $tx->res->code == 404 or $tx->res->code == 410;
Branch: 1 branch
BranchTrueFalseTotal
if $tx->res->code == 404 or $tx->res->code == 410 1 1 2
Condition66%2/3
$tx->res->code == 404 or $tx->res->code == 410
l!l&&r!l&&!r
101
MC/DC50%1/2
$tx->res->code == 404 or $tx->res->code == 410
$tx->res->code == 404 $tx->res->code == 410
Truth table66%2/3
A or B
A= $tx->res->code == 404B= $tx->res->code == 410
ABresult
1X1
011
000
120 1 ▶ return { errors => [ { message => $tx->res->body } ] }
Branch: 1 branch
BranchTrueFalseTotal
if $tx->res->code > 399 0 1 1
121 if $tx->res->code > 399;
122 1 { data => { success => \1 } };
123 0 ▶ }, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
124 0 { errors => [ { message => $_[0] } ] }
125 2 });
126 }
127  
128 4 ▶sub register {
Subroutine register: called CC=4 SCAR=14.1
Pod documented
129 4 my ($self, $app, $conf) = @_;
130 4 my @config_errors = grep !exists $conf->{$_}, @MANDATORY_CONF;
131 4 ▶ die "Missing config keys @config_errors\n" if @config_errors;
Branch: 1 branch
BranchTrueFalseTotal
if @config_errors 0 4 4
132 4 ▶ $app->helper('webpush.create_p' => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
133 4 eval { validate_subs_info($_[2]) };
134 4 ▶ return Mojo::Promise->reject($@) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4 4
135 4 goto &{ $conf->{subs_create_p} };
136 4 });
137 4 $app->helper('webpush.read_p' => $conf->{subs_read_p});
138 4 $app->helper('webpush.delete_p' => $conf->{subs_delete_p});
139 $app->helper('webpush.authorization' => (grep !$conf->{$_}, @AUTH_CONF)
140 0 ▶ ? sub { die "Must provide @AUTH_CONF\n" }
Subroutine __ANON__: not called CC=1 SCAR=6.9
141 4 ▶ : _make_auth_helper($app, $conf)
Branch: 1 branch
BranchTrueFalseTotal
grep((!$conf->{$_}), @AUTH_CONF) ? : 0 4 4
142 );
143 4 $app->helper('webpush.verify_token' => \&_verify_helper);
144 4 $app->helper('webpush.encrypt' => \&_encrypt_helper);
145 4 $app->helper('webpush.send_p' => \&_send_helper);
146 4 my $r = $app->routes;
147 $r->post($conf->{save_endpoint} => _make_route_handler(
148 4 @$conf{qw(subs_session2user_p subs_create_p)},
149 ), 'webpush.save');
150 4 push @{ $app->renderer->classes }, __PACKAGE__;
151 $app->serviceworker->add_event_listener(
152 4 ▶ push => $conf->{push_handler} || $DEFAULT_PUSH_HANDLER
Condition33%1/3
$conf->{'push_handler'} || $DEFAULT_PUSH_HANDLER
l!l&&r!l&&!r
040
MC/DC0%0/2
$conf->{'push_handler'} || $DEFAULT_PUSH_HANDLER
$conf->{'push_handler'} $DEFAULT_PUSH_HANDLER
Truth table33%1/3
A || B
A= $conf->{'push_handler'}B= $DEFAULT_PUSH_HANDLER
ABresult
1X1
011
000
153 );
154 4 $self;
155 }
156  
157 11 ▶sub validate_subs_info {
Subroutine validate_subs_info: called CC=3 SCAR=11.0
Pod undocumented
158 11 my ($info) = @_;
159 11 ▶ die "Expected object\n" if ref $info ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $info ne "HASH" 0 11 11
160 11 my @errors = map "no $_", grep !exists $info->{$_}, qw(keys endpoint);
161 11 push @errors, map "no $_", grep !exists $info->{keys}{$_}, qw(auth p256dh);
162 11 ▶ die "Errors found in subscription info: " . join(", ", @errors) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if @errors 5 6 11
163 if @errors;
164 }
165  
166 4 1;
167  
168 =encoding utf8
169  
170 =head1 NAME
171  
172 Mojolicious::Plugin::WebPush - plugin to aid real-time web push
173  
174 =head1 SYNOPSIS
175  
176 # Mojolicious::Lite
177 my $sw = plugin 'ServiceWorker' => { debug => 1 };
178 my $webpush = plugin 'WebPush' => {
179 save_endpoint => '/api/savesubs',
180 subs_session2user_p => \&subs_session2user_p,
181 subs_create_p => \&subs_create_p,
182 subs_read_p => \&subs_read_p,
183 subs_delete_p => \&subs_delete_p,
184 ecc_private_key => 'vapid_private_key.pem',
185 claim_sub => "mailto:admin@example.com",
186 };
187  
188 sub subs_session2user_p {
189 my ($c, $session) = @_;
190 return Mojo::Promise->reject("Session not logged in") if !$session->{user_id};
191 Mojo::Promise->resolve($session->{user_id});
192 }
193  
194 sub subs_create_p {
195 my ($c, $session, $subs_info) = @_;
196 app->db->save_subs_p($session->{user_id}, $subs_info);
197 }
198  
199 sub subs_read_p {
200 my ($c, $user_id) = @_;
201 app->db->lookup_subs_p($user_id);
202 }
203  
204 sub subs_delete_p {
205 my ($c, $user_id) = @_;
206 app->db->delete_subs_p($user_id);
207 }
208  
209 =head1 DESCRIPTION
210  
211 L<Mojolicious::Plugin::WebPush> is a L<Mojolicious> plugin. In
212 order to function, your app needs to have first installed
213 L<Mojolicious::Plugin::ServiceWorker> as shown in the synopsis above.
214  
215 =head1 METHODS
216  
217 L<Mojolicious::Plugin::WebPush> inherits all methods from
218 L<Mojolicious::Plugin> and implements the following new ones.
219  
220 =head2 register
221  
222 my $p = $plugin->register(Mojolicious->new, \%conf);
223  
224 Register plugin in L<Mojolicious> application, returning the plugin
225 object. Takes a hash-ref as configuration, see L</OPTIONS> for keys.
226  
227 =head1 OPTIONS
228  
229 =head2 save_endpoint
230  
231 Required. The route to be added to the app for the service worker to
232 register users for push notification. The handler for that will call
233 the L</subs_create_p>. If success is indicated, it will return JSON:
234  
235 { "data": { "success": true } }
236  
237 If failure:
238  
239 { "errors": [ { "message": "The exception reason" } ] }
240  
241 This will be handled by the provided service worker. In case it is
242 required by the app itself, the added route is named C<webpush.save>.
243  
244 =head2 subs_session2user_p
245  
246 Required. The code to be called to look up the user currently identified
247 by this session, which returns a promise of the user ID. Must reject
248 if no user logged in and that matters. It will be passed parameters:
249  
250 =over
251  
252 =item *
253  
254 The L<Mojolicious::Controller/session> object, to correctly identify
255 the user.
256  
257 =back
258  
259 =head2 subs_create_p
260  
261 Required. The code to be called to store users registered for push
262 notifications, which must return a promise of a true value if the
263 operation succeeds, or reject with a reason. It will be passed parameters:
264  
265 =over
266  
267 =item *
268  
269 The ID to correctly identify the user. Please note that you ought to
270 allow one person to have several devices with web-push enabled, and to
271 design accordingly.
272  
273 =item *
274  
275 The C<subscription_info> hash-ref, needed to push actual messages.
276  
277 =back
278  
279 =head2 subs_read_p
280  
281 Required. The code to be called to look up a user registered for push
282 notifications. It will be passed parameters:
283  
284 =over
285  
286 =item *
287  
288 The opaque information your app uses to identify the user.
289  
290 =back
291  
292 Returns a promise of the C<subscription_info> hash-ref. Must reject if
293 not found.
294  
295 =head2 subs_delete_p
296  
297 Required. The code to be called to delete up a user registered for push
298 notifications. It will be passed parameters:
299  
300 =over
301  
302 =item *
303  
304 The opaque information your app uses to identify the user.
305  
306 =back
307  
308 Returns a promise of the deletion result. Must reject if not found.
309  
310 =head2 ecc_private_key
311  
312 A value to be passed to L<Crypt::PK::ECC/new>: a simple scalar is a
313 filename, a scalar-ref is the actual key. If not provided,
314 L</webpush.authorization> will (obviously) not be able to function.
315  
316 =head2 claim_sub
317  
318 A value to be used as the C<sub> claim by the L</webpush.authorization>,
319 which needs it. Must be either an HTTPS or C<mailto:> URL.
320  
321 =head2 claim_exp_offset
322  
323 A value to be added to current time, in seconds, in the C<exp> claim
324 for L</webpush.authorization>. Defaults to 86400 (24 hours). The maximum
325 valid value in RFC 8292 is 86400.
326  
327 =head2 push_handler
328  
329 Override the default push-event handler supplied to
330 L<Mojolicious::Plugin::ServiceWorker/add_event_listener>. The default
331 will interpret the message as a JSON object. The key C<title> will be
332 the notification title, deleted from that object, then the object will be
333 the options passed to C<< <ServiceWorkerRegistration>.showNotification >>.
334  
335 See
336 L<https://developers.google.com/web/fundamentals/push-notifications/handling-messages>
337 for possibilities.
338  
339 =head1 HELPERS
340  
341 =head2 webpush.create_p
342  
343 $c->webpush->create_p($user_id, $subs_info)->then(sub {
344 $c->render(json => { data => { success => \1 } });
345 });
346  
347 =head2 webpush.read_p
348  
349 $c->webpush->read_p($user_id)->then(sub {
350 $c->render(text => 'Info: ' . to_json(shift));
351 });
352  
353 =head2 webpush.delete_p
354  
355 $c->webpush->delete_p($user_id)->then(sub {
356 $c->render(json => { data => { success => \1 } });
357 });
358  
359 =head2 webpush.authorization
360  
361 my $header_value = $c->webpush->authorization($subs_info);
362  
363 Won't function without L</claim_sub> and L</ecc_private_key>, or
364 C<$subs_info> having a valid URL to get the base of as the C<aud>
365 claim. Returns a suitable C<Authorization> header value to send to
366 a push service. Valid for a period defined by L</claim_exp_offset>.
367 but could become so to avoid unnecessary computation.
368  
369 =head2 webpush.public_key
370  
371 my $pkey = $c->webpush->public_key;
372  
373 Gives the app's public VAPID key, calculated from the private key.
374  
375 =head2 webpush.verify_token
376  
377 my $bool = $c->webpush->verify_token($authorization_header_value);
378  
379 Cryptographically verifies a JSON Web Token (JWT), such as generated
380 by L</webpush.authorization>.
381  
382 =head2 webpush.encrypt
383  
384 use MIME::Base64 qw(decode_base64url);
385 my $ciphertext = $c->webpush->encrypt($data_bytes,
386 map decode_base64url($_), @{$subscription_info->{keys}}{qw(p256dh auth)}
387 );
388  
389 Returns the data encrypted according to RFC 8188, for the relevant
390 subscriber.
391  
392 =head2 webpush.send_p
393  
394 my $result_p = $c->webpush->send_p($jsonable_data, $user_id, $ttl, $urgency);
395  
396 JSON-encodes the given value, encrypts it according to the given user's
397 subscription data, adds a VAPID C<Authorization> header, then sends it
398 to the relevant web-push endpoint.
399  
400 Returns a promise of the result, which will be a hash-ref with either a
401 C<data> key indicating success, or an C<errors> key for an array-ref of
402 hash-refs with a C<message> giving reasons.
403  
404 If the sending gets a status code of 404 or 410, this indicates the
405 subscriber has unsubscribed, and L</webpush.delete_p> will be used to
406 remove the registration. This is considered success.
407  
408 The C<urgency> must be one of C<very-low>, C<low>, C<normal> (the default)
409 or C<high>. The C<ttl> defaults to 30 seconds.
410  
411 =head1 TEMPLATES
412  
413 Various templates are available for including in the app's templates:
414  
415 =head2 webpush-askPermission.html.ep
416  
417 JavaScript functions, also for putting inside a C<script> element:
418  
419 =over
420  
421 =item *
422  
423 askPermission
424  
425 =item *
426  
427 subscribeUserToPush
428  
429 =item *
430  
431 sendSubscriptionToBackEnd
432  
433 =back
434  
435 These each return a promise, and should be chained together:
436  
437 <button onclick="
438 askPermission().then(subscribeUserToPush).then(sendSubscriptionToBackEnd)
439 ">
440 Ask permission
441 </button>
442 <script>
443 %= include 'serviceworker-install'
444 %= include 'webpush-askPermission'
445 </script>
446  
447 Each application must decide when to ask such permission, bearing in
448 mind that once permission is refused, it is very difficult for the user
449 to change such a refusal.
450  
451 When it is granted, the JavaScript code will communicate with the
452 application, registering the needed information needed to web-push.
453  
454 =head1 SEE ALSO
455  
456 L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
457  
458 L<Mojolicious::Command::webpush> - command-line control of web-push.
459  
460 RFC 8292 - Voluntary Application Server Identification (for web push).
461  
462 L<Crypt::RFC8188> - Encrypted Content-Encoding for HTTP (using C<aes128gcm>).
463  
464 L<https://developers.google.com/web/fundamentals/push-notifications>
465  
466 =head1 ACKNOWLEDGEMENTS
467  
468 Part of this code is ported from
469 L<https://github.com/web-push-libs/pywebpush>.
470  
471 =cut
472  
473 __DATA__
« Command/webpush.pm ↑ Summary