view release on metacpan or search on metacpan
example/Notify/lib/Notify.pm view on Meta::CPAN
# config/punk.yml.
auth model => 'User';
# The keys are configuration and are never generated: a pair minted at boot
# would differ per worker and per restart, and every subscription made against
# the old one would be undeliverable in silence. `punk push keys` prints a
# pair; bin/seed.pl puts one in var/ for the demo.
plugin 'Push' => {
subject => $ENV{PUSH_SUBJECT} || 'mailto:demo@example.com',
public_key => $ENV{VAPID_PUBLIC} || '',
private_key => $ENV{VAPID_PRIVATE} || '',
};
get '/' => 'Web::Root#index', { name => 'home' };
get '/login' => 'Web::Root#login_form', { name => 'login' };
post '/login' => 'Web::Root#login';
post '/logout' => 'Web::Root#logout';
# The one route that actually sends. In a real application this would be
# something that happened - a report finished, an order shipped - rather than
# a button.
lib/Punk/Plugin/Push.pm view on Meta::CPAN
use VAPID ();
use File::Raw::JSON qw(file_json_encode);
use Punk::Push ();
use Punk::Push::Subscription ();
use Punk::Push::Result ();
our $VERSION = '0.03';
our @OPTIONS = qw(
subject public_key private_key
prefix guard assets model table
ttl urgency queue sqitch timeout
);
our %URGENCY = map { $_ => 1 } qw(very-low low normal high);
sub register {
my ($self, $app, $opts) = @_;
$opts ||= {};
lib/Punk/Plugin/Push.pm view on Meta::CPAN
sub _options {
my ($opts) = @_;
my %known = map { $_ => 1 } @OPTIONS;
for my $k (sort keys %$opts) {
next if $known{$k};
Carp::croak("Punk::Plugin::Push: unknown option '$k' (known: "
. join(', ', @OPTIONS) . ')');
}
for my $k (qw(subject public_key private_key)) {
next if defined $opts->{$k} && length $opts->{$k};
Carp::croak("Punk::Plugin::Push: `$k` is required"
. ($k eq 'subject'
? " - RFC 8292 demands it, and a push service rejects a JWT\n"
. " without one with a 403 that explains nothing"
: " - generate a pair with `punk push keys`.\n"
. " A key minted at boot would differ per worker and per\n"
. " restart, and every subscription made against the old one\n"
. " would be undeliverable in silence"));
}
lib/Punk/Plugin/Push.pm view on Meta::CPAN
unless ($opts->{subject} =~ m{\A mailto: \S+ \@ \S+ \z}x
|| $opts->{subject} =~ m{\A https?:// [^/?\#\s]+ }x) {
Carp::croak("Punk::Plugin::Push: `subject` is not a url or mailto:"
. " address - RFC 8292 wants a mailto: or https: URI the push\n"
. " service can reach you at when it drops your traffic");
}
my %cfg = (
subject => VAPID::validate_subject($opts->{subject}),
public_key => $opts->{public_key},
private_key => $opts->{private_key},
prefix => defined $opts->{prefix} ? $opts->{prefix} : '/push',
guard => $opts->{guard},
assets => exists $opts->{assets} ? ($opts->{assets} ? 1 : 0) : 1,
model => defined $opts->{model} ? $opts->{model} : 'PushSubscription',
table => $opts->{table},
ttl => defined $opts->{ttl} ? $opts->{ttl} : 2419200,
urgency => defined $opts->{urgency} ? $opts->{urgency} : 'normal',
queue => $opts->{queue} ? 1 : 0,
sqitch => $opts->{sqitch} ? 1 : 0,
timeout => defined $opts->{timeout} ? $opts->{timeout} : 10,
);
VAPID::validate_public_key($cfg{public_key});
VAPID::validate_private_key($cfg{private_key});
Carp::croak("Punk::Plugin::Push: `prefix` must be a rooted path, not "
. "'$cfg{prefix}'")
unless $cfg{prefix} =~ m{\A/} && $cfg{prefix} !~ m{//|[:*]};
Carp::croak("Punk::Plugin::Push: `urgency` must be one of "
. join(', ', sort keys %URGENCY) . ", not '$cfg{urgency}'")
unless $URGENCY{ $cfg{urgency} };
Carp::croak('Punk::Plugin::Push: `ttl` must not be negative')
lib/Punk/Plugin/Push.pm view on Meta::CPAN
sub _vapid_header {
my ($class, $app, $audience) = @_;
my $cfg = $class->config_for($app);
my $cached = $cfg->{jwt}{$audience};
return $cached->{header} if $cached && $cached->{exp} > time + 300;
my $exp = time + 12 * 60 * 60;
my $h = VAPID::generate_vapid_header(
$audience, $cfg->{subject},
$cfg->{public_key}, $cfg->{private_key},
$exp, 1,
);
$cfg->{jwt}{$audience} = { header => $h->{Authorization}, exp => $exp };
return $h->{Authorization};
}
sub _keys_of {
my ($sub) = @_;
return ($sub->{endpoint}, $sub->{keys}{p256dh}, $sub->{keys}{auth})
if ref $sub->{keys} eq 'HASH';
lib/Punk/Plugin/Push.pm view on Meta::CPAN
package MyApp;
use Punk;
use Punk::Plugin::Push;
host 'https://example.com';
auth ...; # subscribe and unsubscribe are guarded
plugin 'Push' => {
subject => 'mailto:ops@example.com',
public_key => { '$env' => 'VAPID_PUBLIC' },
private_key => { '$env' => 'VAPID_PRIVATE' },
};
post '/reports' => sub {
my ($c) = @_;
$c->push_send($c->auth_id, {
title => 'Your report is ready',
body => 'Three pages, as usual.',
url => '/reports/2026-09',
});
return $c->json({ ok => 1 });
lib/Punk/Plugin/Push.pm view on Meta::CPAN
C<to_app> rather than served unguarded. C<GET /push/key> is not guarded; it is
a public key.
Unsubscribe removes a row only when it belongs to the authenticated user.
Deleting by endpoint alone would let any authenticated user unsubscribe any
other, and an endpoint is not a secret: it is sent to a third party on every
delivery.
=head2 The keys are configuration and are never generated for you
C<subject>, C<public_key> and C<private_key> croak at the C<plugin> line,
because nothing declared later can supply them.
The tempting convenience is to mint a keypair when none is configured. It is
wrong in a way that takes weeks to notice: Hyperman runs a pool, so each worker
would generate a different key, a subscription created against one worker would
be undeliverable from every other, and a restart would invalidate the lot.
Every failure would look like an intermittent push service.
C<subject> is required by RFC 8292 and push services reject a JWT without one,
so leaving it out produces a C<403> whose body explains nothing. It must be a
lib/Punk/Plugin/Push.pm view on Meta::CPAN
There is also only B<one> service worker per scope. If you already register one
for offline support, merge the two handlers into it rather than registering a
second, or whichever registered last wins and the other quietly stops working.
=head1 OPTIONS
plugin 'Push' => {
subject => 'mailto:ops@example.com', # REQUIRED
public_key => '...', # REQUIRED
private_key => '...', # REQUIRED
prefix => '/push',
guard => undef, # default: the application's auth
assets => 1, # serve push.js and push-sw.js
model => 'PushSubscription',
ttl => 2419200, # seconds a push service may hold it
urgency => 'normal', # very-low | low | normal | high
queue => 0, # deliver through Punk::Queue
sqitch => 0, # ship the DDL as a Sqitch project
timeout => 10,
};
lib/Punk/Push.pm view on Meta::CPAN
package MyApp;
use Punk;
use Punk::Plugin::Push;
host 'https://example.com';
plugin 'Push' => {
subject => 'mailto:ops@example.com',
public_key => { '$env' => 'VAPID_PUBLIC' },
private_key => { '$env' => 'VAPID_PRIVATE' },
};
post '/reports' => sub {
my ($c) = @_;
$c->push_send($c->auth_id, {
title => 'Your report is ready',
body => 'Three pages, as usual.',
url => '/reports/2026-09',
});
return $c->json({ ok => 1 });
t/01-options.t view on Meta::CPAN
our %OPTS;
my $N = 0;
# Real Punk classes: register installs helpers through $app->helper, and a
# hand-rolled Punk::App gets as far as the option check and then croaks for a
# reason that has nothing to do with the options.
sub build {
my (%o) = @_;
local %OPTS = (subject => 'mailto:ops@example.com',
public_key => $PUB, private_key => $PRIV, %o);
delete $OPTS{$_} for grep { !defined $OPTS{$_} && !exists $o{$_} } ();
for my $k (keys %o) { delete $OPTS{$k} unless defined $o{$k} or exists $o{$k} }
my $pkg = 'PushOpt' . ++$N;
local $@;
my $ok = eval "package $pkg; use Punk; plugin 'Push' => { \%main::OPTS }; 1";
return $ok ? ($pkg->punk_app, undef) : (undef, $@);
}
sub cfg { $_[0] && $_[0]->{push_config} }
# ---- the three that are required ------------------------------------------
for my $missing (qw(subject public_key private_key)) {
my %o = (subject => 'mailto:ops@example.com',
public_key => $PUB, private_key => $PRIV);
delete $o{$missing};
local %OPTS = %o;
my $pkg = 'PushMiss' . ++$N;
local $@;
eval "package $pkg; use Punk; plugin 'Push' => { \%main::OPTS }; 1";
like($@, qr/`\Q$missing\E` is required/, "$missing is required");
}
{
my (undef, $err) = build(public_key => '');
like($err, qr/`public_key` is required/, 'an empty key is no key');
}
# The croak has to say where a keypair comes from, or the reader is left
# searching for how to make a P-256 pair.
{
my %o = (subject => 'mailto:ops@example.com', private_key => $PRIV);
local %OPTS = %o;
my $pkg = 'PushHint' . ++$N;
local $@;
eval "package $pkg; use Punk; plugin 'Push' => { \%main::OPTS }; 1";
like($@, qr/punk push keys/, 'the key croak names the command that makes one');
like($@, qr/differ per worker/, ' and says why one is not invented');
}
{
my %o = (public_key => $PUB, private_key => $PRIV);
local %OPTS = %o;
my $pkg = 'PushSubj' . ++$N;
local $@;
eval "package $pkg; use Punk; plugin 'Push' => { \%main::OPTS }; 1";
like($@, qr/RFC 8292/, 'the subject croak says which RFC demands it');
}
# ---- a typo must not pass silently ----------------------------------------
{
t/01-options.t view on Meta::CPAN
}
# ---- keys are validated, not just present ---------------------------------
{
my (undef, $err) = build(public_key => 'dG9vLXNob3J0');
like($err, qr/65 bytes/, 'a short public key is refused at the plugin line');
}
{
my (undef, $err) = build(private_key => 'dG9vLXNob3J0');
like($err, qr/32 bytes/, 'and a short private key');
}
{
my (undef, $err) = build(subject => 'not-a-url-or-mailto');
like($err, qr/not a url or mailto/, 'the subject must be a mailto: or a URL');
}
# ---- defaults --------------------------------------------------------------
t/01-options.t view on Meta::CPAN
my ($app) = build(model => 'Punk::Model::PushSubscription');
is(cfg($app)->{model}, 'Punk::Model::PushSubscription',
'a name with :: is taken as a class and left alone');
}
# ---- the helper that needs nothing else -----------------------------------
{
my $pkg = 'PushKeyHelper';
local %OPTS = (subject => 'mailto:ops@example.com',
public_key => $PUB, private_key => $PRIV,
guard => sub { 1 });
eval "package $pkg; use Punk;
host 'https://example.com';
plugin 'Push' => { \%main::OPTS };
get '/k' => sub { \$_[0]->text(\$_[0]->push_key) };
1" or die $@;
require Punk::Test;
my $t = Punk::Test->new($pkg);
$t->get_ok('/k')->status_is(200)->content_is($PUB);
}
t/03-vapid.t view on Meta::CPAN
# where the arithmetic belongs. What is checked here is that this plugin drives
# it correctly: the right audience, the right claims, a signature that verifies
# against the configured key, and one token per push service.
#
# VAPID's own suite once asserted only that a header was truthy, which is how
# the "vapit" scheme name survived into a release. Nothing here is satisfied by
# a header merely existing.
our ($PUB, $PRIV) = VAPID::generate_vapid_keys();
our %OPTS = (subject => 'mailto:ops@example.com',
public_key => $PUB, private_key => $PRIV,
guard => sub { 1 });
eval <<'PERL' or die $@;
package PushVapid;
use Punk;
host 'https://example.com';
plugin 'Push' => { %main::OPTS };
1;
PERL
PushVapid->to_app;
t/04-encrypt.t view on Meta::CPAN
# VAPID the right subscription keys and puts the resulting record on the wire
# unaltered.
#
# So the test plays the receiver. It generates a subscription whose private key
# it keeps, takes the body the plugin produced, and decrypts it the way a
# browser would. If the plugin passed the wrong key, swapped the two public
# keys in the context, or touched the bytes afterwards, this cannot pass.
our ($PUB, $PRIV) = VAPID::generate_vapid_keys();
our %OPTS = (subject => 'mailto:ops@example.com',
public_key => $PUB, private_key => $PRIV,
guard => sub { 1 });
{
package TFake::Res; sub new { bless { %{$_[1]} }, $_[0] } sub status { 201 }
package TFake::Future; sub new { bless {}, shift } sub get { TFake::Res->new({}) }
package TFake::UA;
sub new { bless { calls => [] }, shift }
sub post { my ($s,$u,%o)=@_; push @{$s->{calls}}, {url=>$u,%o}; TFake::Future->new }
sub last_body { $_[0]{calls}[-1]{body} }
}
t/10-storage.t view on Meta::CPAN
$stmt =~ s/\A\s+|\s+\z//g;
next unless length $stmt;
next if $stmt =~ /\A(?:BEGIN|COMMIT)\z/i; # AutoCommit owns those
$dbh->do($stmt);
}
$dbh->disconnect;
}
our $DSN = "dbi:SQLite:dbname=$db";
our %OPTS = (subject => 'mailto:ops@example.com',
public_key => $PUB, private_key => $PRIV,
guard => sub { 1 });
eval <<'PERL' or die $@;
package PushStore;
use Punk;
host 'https://example.com';
database dsn => $main::DSN;
plugin 'Push' => { %main::OPTS };
1;
PERL
t/11-delivery.t view on Meta::CPAN
for my $stmt (split /;/, $sql) {
$stmt =~ s/\A\s+|\s+\z//g;
next unless length $stmt;
next if $stmt =~ /\A(?:BEGIN|COMMIT)\z/i;
$dbh->do($stmt);
}
$dbh->disconnect;
}
our %OPTS = (subject => 'mailto:ops@example.com',
public_key => $PUB, private_key => $PRIV,
guard => sub { 1 });
eval <<'PERL' or die $@;
package PushSend;
use Punk;
host 'https://example.com';
database dsn => $main::DSN;
plugin 'Push' => { %main::OPTS };
1;
PERL
t/12-routes.t view on Meta::CPAN
$dbh->do($stmt);
}
$dbh->disconnect;
}
# A guard standing in for the application's auth: $main::WHO is the logged-in
# user, undef when nobody is.
our $WHO;
our %OPTS = (
subject => 'mailto:ops@example.com',
public_key => $PUB, private_key => $PRIV,
guard => sub {
my ($c) = @_;
return 1 if defined $main::WHO;
return $c->json({ errors => [ { message => 'Unauthorized' } ] }, 401);
},
);
eval <<'PERL' or die $@;
package PushRoutes;
use Punk;
t/12-routes.t view on Meta::CPAN
# ---- no auth, no unguarded write route -------------------------------------
{
local $@;
eval <<'PERL';
package PushNoAuth;
use Punk;
host 'https://example.com';
plugin 'Push' => { subject => 'mailto:o@e.com',
public_key => $main::PUB, private_key => $main::PRIV };
1;
PERL
my $compiled = eval { PushNoAuth->to_app; 1 };
ok(!$compiled, 'an application with no auth and no guard refuses to compile');
like($@, qr/open relay/, ' saying what the risk is');
like($@, qr/Declare auth, or pass an explicit `guard`/, ' and what to do');
}
done_testing;