repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

150 lines · 11.0 KB · download this file

package BlowfishCMS;
# Payments, for add-ons that take them (Store, Services): money as people
# read and type it, and Stripe Checkout. Moved into the core in 0.40.3 from
# the copies each add-on kept, so a fix reaches every one of them.
#
# Each add-on keeps its own Stripe keys, in its own secrets folder
# (addon_secret_dir: stripe.key and webhook.key, 0400, its account's), its own
# webhook endpoint and its own records; these functions take the add-on's
# name. Card details never reach the site: buyers pay on Stripe's page.
#
#   money, parse_money, money_input, currencies   amounts in minor units (cents)
#   stripe_request(NAME, VERB, PATH, PAIRS, %o)    Stripe's API, with NAME's key
#   stripe_problem, stripe_live                    its errors in words; live or test key
#   stripe_secret(NAME, FILE), stripe_secret_save  the key files
#   stripe_webhook_event(NAME)                     a webhook's event, its signature checked
#   stripe_panel_action(NAME, ACTION)              the key forms' actions
#   stripe_panel_html(NAME, ADDRESS, %o)           those forms and how things stand
use v5.36;
use utf8;
use Fcntl qw(O_WRONLY O_CREAT O_TRUNC);
use Digest::SHA qw(hmac_sha256_hex);

# ---- Money ---------------------------------------------------------------------------------------
my %zero_decimal=map {$_=>1} qw(bif clp djf gnf jpy kmf krw mga pyg rwf ugx vnd vuv xaf xof xpf);
my %symbol=(usd=>'$',cad=>'CA$',aud=>'A$',nzd=>'NZ$',eur=>'€',gbp=>'£',jpy=>'¥',chf=>'CHF ',sek=>'SEK ',nok=>'NOK ',dkk=>'DKK ',mxn=>'MX$');
# The currencies the payment screens offer.
sub currencies { return qw(usd cad aud nzd eur gbp chf sek nok dkk jpy mxn) }
# An amount in minor units as people read it: "$1,250.00" (whole=>1: "$1,250"
# when there are no cents).
sub money ($amount,$cur,%o) {
    my $n=$zero_decimal{$cur} ? sprintf('%d',$amount) : sprintf('%.2f',$amount/100);
    $n =~ s/\.00\z// if $o{whole} && !$zero_decimal{$cur};
    1 while $n =~ s/^(\d+)(\d{3})/$1,$2/;
    return exists $symbol{$cur} ? $symbol{$cur}.$n : $n.' '.uc $cur;
}
# "12.50" (or "$12.50", "1,200") -> 1250 minor units (12 for zero-decimal
# currencies); dies with a message naming $what on anything else.
sub parse_money ($text,$what,$cur) {
    $text //= '';$text =~ s/^\s+|\s+$//g;$text =~ s/^[^\d]+//;$text =~ s/,(?=\d{3}\b)//g;
    if ($zero_decimal{$cur}) {die "$what: a whole number such as 1200.\n" unless $text =~ /\A\d{1,9}\z/;return 0+$text}
    die "$what: an amount such as 12 or 12.50.\n" unless $text =~ /\A(\d{1,7})(?:[.,](\d{1,2}))?\z/;
    my ($whole,$cents)=($1,$2);
    return $whole*100+(defined $cents ? (length $cents==1 ? $cents*10 : $cents) : 0);
}
# An amount for a form's field: "12.50" (or "1200").
sub money_input ($amount,$cur) { return $zero_decimal{$cur} ? $amount : sprintf('%.2f',$amount/100) }

# ---- Stripe --------------------------------------------------------------------------------------
# Stripe's address, read when the code loads; the tests point it at a stand-in.
my $stripe_api;
sub stripe_api { return $stripe_api //= $BlowfishCMS::startup_env{BLOWFISH_STRIPE_API} // 'https://api.stripe.com' }
# One of NAME's key files (stripe.key, webhook.key): its value, or ''.
sub stripe_secret ($name,$file) {
    open my $fh,'<',addon_secret_dir($name)."/$file" or return '';
    my $v=do {local $/;<$fh>};close $fh;$v//='';$v =~ s/\s+//g;return $v;
}
# Saves one, readable by NAME's account alone (0400).
sub stripe_secret_save ($name,$file,$value) {
    my $path=addon_secret_dir($name)."/$file";
    sysopen(my $fh,"$path.tmp",O_WRONLY|O_CREAT|O_TRUNC,0400) or die "Can’t save the key: the add-on’s private folder isn’t set up (doas blowfishctl addon enable $name).\n";
    print {$fh} "$value\n";close $fh or die "Can’t save the key.\n";
    rename "$path.tmp",$path or do {unlink "$path.tmp";die "Can’t save the key.\n"};
}
sub stripe_live ($key) { return $key =~ /\A(?:sk|rk)_live_/ ? 1 : 0 }
# Calls Stripe's API with NAME's key (or %o's key): (status, reply).
sub stripe_request ($name,$verb,$path,$pairs=[],%o) {
    my $key=$o{key} // stripe_secret($name,'stripe.key');
    die "This isn’t connected to Stripe yet.\n" unless length $key;
    require HTTP::Tiny;
    my $http=HTTP::Tiny->new(timeout=>25,verify_SSL=>1);
    my %h=(Authorization=>"Bearer $key",Accept=>'application/json',($o{idempotency} ? ('Idempotency-Key'=>$o{idempotency}) : ()));
    my $r=$verb eq 'GET'
        ? $http->get(stripe_api().$path.(@$pairs ? '?'.$http->www_form_urlencode($pairs) : ''),{headers=>\%h})
        : $http->request($verb,stripe_api().$path,{headers=>{%h,'Content-Type'=>'application/x-www-form-urlencoded'},content=>$http->www_form_urlencode($pairs)});
    my $reply=(attempt {JSON::PP->new->decode($r->{content}//'')}) // {};
    return ($r->{status},ref $reply eq 'HASH' ? $reply : {});
}
# What went wrong, in words for the owner.
sub stripe_problem ($status,$reply) {
    return 'Stripe couldn’t be reached. Try again in a minute.' if $status==599 || !$status;
    my $m=$reply->{error}{message}//'';
    return 'Stripe refused the key: '.($m||'check it in the Stripe Dashboard → Developers → API keys.') if $status==401;
    return 'The key isn’t allowed to create Checkout Sessions. Give the restricted key “Checkout Sessions: Write”.' if $status==403;
    return 'Stripe: '.($m||"error $status");
}
# A webhook delivery to NAME: (event, '') when its Stripe-Signature matches
# NAME's signing secret and is from the last five minutes; (undef, why) when
# not, in words Stripe shows beside the delivery (no secrets).
sub stripe_webhook_event ($name) {
    my $raw=$BlowfishCMS::q->param('POSTDATA') // '';
    my $secret=stripe_secret($name,'webhook.key');
    my %sig;for (split /,/,$ENV{HTTP_STRIPE_SIGNATURE}//'') {my ($k,$v)=split /=/,$_,2;push @{$sig{$k}},$v if defined $v}
    my $t=($sig{t}//[])->[0]//0;
    my $problem=!length $secret ? 'no webhook signing secret is saved'
        : !@{$sig{v1}//[]} || $t !~ /\A\d+\z/ ? 'the request has no Stripe-Signature header'
        : abs(time-$t)>300 ? 'the timestamp is '.abs(time-$t).' seconds away from this server’s clock (check that ntpd is running)'
        : !(grep {eq_safe($_,hmac_sha256_hex("$t.$raw",$secret))} @{$sig{v1}}) ? 'the signature doesn’t match the saved signing secret (copy it again from this endpoint; test and live mode have different secrets)'
        : '';
    return (undef,$problem) if $problem;
    my $event=(attempt {JSON::PP->new->decode($raw)}) // {};
    return (ref $event eq 'HASH' ? $event : {},'');
}
# The panel's actions (stripe_key, webhook_key, keys_remove) for NAME: the
# message to show once done, or undef for any other action. Dies with what's
# wrong. A key is checked with Stripe before it's saved.
sub stripe_panel_action ($name,$action) {
    if ($action eq 'stripe_key') {
        my $key=param('key',300);$key =~ s/\s+//g;
        die "Paste a secret key (sk_…) or restricted key (rk_…) from Stripe → Developers → API keys.\n" unless $key =~ /\A(?:sk|rk)_(?:test|live)_[A-Za-z0-9]{10,250}\z/;
        my ($status,$reply)=stripe_request($name,'GET','/v1/checkout/sessions',[limit=>1],key=>$key);
        die stripe_problem($status,$reply)."\n" unless $status==200;
        stripe_secret_save($name,'stripe.key',$key);
        return 'Stripe key saved ('.(stripe_live($key) ? 'live: real payments' : 'test mode: no real money').').';
    }
    if ($action eq 'webhook_key') {
        my $key=param('key',300);$key =~ s/\s+//g;
        die "Paste the signing secret (whsec_…) from the webhook endpoint in Stripe.\n" unless $key =~ /\Awhsec_[A-Za-z0-9+\/=]{10,250}\z/;
        stripe_secret_save($name,'webhook.key',$key);
        return 'Webhook signing secret saved.';
    }
    if ($action eq 'keys_remove') {
        unlink addon_secret_dir($name).'/stripe.key',addon_secret_dir($name).'/webhook.key';
        return 'Stripe keys removed. Online payment is off until they’re saved again.';
    }
    return undef;
}
# The Stripe panel for NAME's screen at ADDRESS (where its forms post): how
# things stand (the key, the signing secret, the webhook's address, the last
# delivery) and the forms. %o: webhook (the endpoint's path, such as
# /x/store/webhook), last ({ok, text, at}, the last delivery), unset (what's
# missing without a key, in words), kind (the forms' kind, x-NAME).
sub stripe_panel_html ($name,$address,%o) {
    my $key=stripe_secret($name,'stripe.key');my $hook=stripe_secret($name,'webhook.key');my $kind=$o{kind}//"x-$name";
    my $w=$o{last};my $url=site_url().$o{webhook};
    my @rows=(['Stripe key',length $key ? ['ok',stripe_live($key) ? 'saved: live (real payments)' : 'saved: test mode (no real money)'] : ['warn','not set'.(length($o{unset}//'') ? ": $o{unset}" : '')]],
        ['Webhook signing secret',length $hook ? ['ok','saved'] : ['warn','not set: payments stay waiting until it is']],
        ['Webhook address',['ok',$url]],
        $w ? ['Last webhook',[$w->{ok} ? 'ok' : 'warn',($w->{ok} ? 'received '.$w->{text} : 'refused: '.$w->{text}).' ('.($w->{at} =~ s/T/ /r =~ s/Z$/ UTC/r).')']] : ['Last webhook',['warn','none received yet']]);
    my $html='<table class="seo-table mail-status"><tbody>'.join('',map {'<tr><th>'.h($_->[0]).'</th><td class="is-'.$_->[1][0].'">'.h($_->[1][1]).'</td></tr>'} @rows).'</tbody></table>';
    $html.='<div class="box-part"><h3>Keys</h3><form method="post" action="'.h($address).'" class="admin-form">'.fields('stripe_key',$kind)
        .'<label>Stripe secret key<input name="key" type="password" autocomplete="off" spellcheck="false" maxlength="300" required placeholder="'.(length $key ? 'saved; paste a new one to replace it' : 'sk_test_… or rk_live_…').'"><span class="optional">Stripe → Developers → API keys. Best: a <em>restricted key</em> with only “Checkout Sessions: Write”. Start with a test key (sk_test_…) and switch to live when you’re ready. It’s checked with Stripe before saving and never shown again.</span></label>'
        .'<button class="buttonlike" type="submit">save</button></form>'
        .'<form method="post" action="'.h($address).'" class="admin-form">'.fields('webhook_key',$kind)
        .'<label>Webhook signing secret<input name="key" type="password" autocomplete="off" spellcheck="false" maxlength="300" required placeholder="'.(length $hook ? 'saved; paste a new one to replace it' : 'whsec_…').'"><span class="optional">Stripe → Developers → Webhooks → Add endpoint: address <code>'.h($url).'</code>, events <code>checkout.session.completed</code>, <code>checkout.session.async_payment_succeeded</code>, <code>checkout.session.async_payment_failed</code> and <code>checkout.session.expired</code>. Then copy its signing secret here. Test and live mode each have their own endpoint and secret.</span></label>'
        .'<button class="buttonlike" type="submit">save</button></form>';
    $html.='<form method="post" action="'.h($address).'" class="delete-form" data-confirm="Remove both Stripe keys? Online payment stops.">'.fields('keys_remove',$kind).'<button class="text-button danger">remove the Stripe keys</button></form>' if length $key || length $hook;
    return $html.'</div>';
}

1;