repository

BlowfishCMS

A small content management system for OpenBSD

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

195 lines · 13.7 KB · download this file

package BlowfishCMS;
# Comments: anonymous comments, likes and comment moderation.
# Every BlowfishCMS/*.pm file adds subs to the one BlowfishCMS package; request state
# is shared through the package variables below and reset by BlowfishCMS::handle_request.
use v5.36;
use utf8;
use JSON::PP qw(encode_json decode_json);
use Digest::SHA qw(hmac_sha256_hex sha256_hex);
use Encode qw(decode encode FB_CROAK);
use Fcntl qw(:flock :DEFAULT);
use Unicode::Normalize qw(NFKC);
use POSIX qw(strftime);
use File::Basename qw(basename);
our %instance;
our ($base,$data,$store,$cdata,$root,$db,$q,$route,$admin,$contact,$comments_route,$method,$cookie_header,$csrf);

# Visitors are anonymous. A random key in a long-lived cookie identifies the
# browser; only its SHA-256 is stored. The first browser to use a username
# owns it. The comments database is world-readable (it holds only public text
# and hashes) so the read-only public service can show it.
# Comments exist only where the comments service's folder does (blowfishctl
# makes it).
sub comments_enabled { return -d $cdata }
# Opens the comments database. Reading is open to every service; with
# $write (only the comments service can) it also creates the tables:
#   names      usernames, and which browser owns each (owner = hashed key)
#   comments   every comment, with the item it's on (post_id), its name, text,
#              a hash of the sender's address, and whether it's hidden
#   likes      one row per item per browser
#   events     recent likes and comments by actor, for rate limits
#   downloads  file downloads per file per day
# Returns undef when there's no database to read yet.
sub comments_db ($write=0) {
    my $file="$cdata/comments.sqlite";
    return undef unless -d $cdata && ($write || -r $file);
    my $c=DBI->connect("dbi:SQLite:dbname=$file",'','',{RaiseError=>1,PrintError=>0,AutoCommit=>1,sqlite_unicode=>1});
    $c->do('PRAGMA busy_timeout=5000');
    if ($write) {
        $c->do('CREATE TABLE IF NOT EXISTS names (name_key TEXT PRIMARY KEY, display TEXT NOT NULL, owner TEXT NOT NULL, created_at TEXT NOT NULL)');
        $c->do('CREATE TABLE IF NOT EXISTS comments (id TEXT PRIMARY KEY, post_id TEXT NOT NULL, name_key TEXT NOT NULL, display TEXT NOT NULL, owner TEXT NOT NULL, body TEXT NOT NULL, ip TEXT NOT NULL, hidden INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL)');
        $c->do('CREATE INDEX IF NOT EXISTS comments_by_post ON comments(post_id, created_at)');
        $c->do('CREATE TABLE IF NOT EXISTS likes (post_id TEXT NOT NULL, owner TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY(post_id, owner))');
        $c->do('CREATE TABLE IF NOT EXISTS events (kind TEXT NOT NULL, actor TEXT NOT NULL, at INTEGER NOT NULL)');
        $c->do('CREATE TABLE IF NOT EXISTS downloads (item TEXT NOT NULL, day TEXT NOT NULL, n INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(item, day))');
        $c->do('CREATE INDEX IF NOT EXISTS events_lookup ON events(kind, actor, at)');
    } else {$c->do('PRAGMA query_only=ON')}
    return $c;
}
# A secret key kept in the comments service's private folder, made the
# first time it's needed (O_EXCL makes sure two processes can't both make
# one). Used to hash addresses and to sign the Comments screen's forms.
sub comments_secret ($name) {
    my $dir="$cdata/private";my $file="$dir/$name.key";
    mkdir $dir,0700 unless -d $dir;
    if (!-e $file && sysopen(my $out,$file,O_WRONLY|O_CREAT|O_EXCL,0600)) {print {$out} random_id().random_id();close $out}
    open my $fh,'<',$file or die "Comment key unavailable\n";local $/;my $secret=<$fh>;close $fh;$secret =~ s/\s+//g;
    die "Comment key unavailable\n" unless length $secret;
    return $secret;
}
# The visitor's random key from their bf_visitor cookie, if it looks right.
sub visitor_key { my $k=$q->cookie('bf_visitor')//''; return $k =~ /\A[a-f0-9]{32}\z/ ? $k : '' }
# What's stored for a visitor: a hash of their key, never the key itself, so
# the database can't be used to pretend to be someone.
sub visitor_owner ($key) { return $key ? sha256_hex("visitor:$key") : '' }
# The visitor's key, giving them one (a cookie for ten years) on their first
# like or comment.
sub ensure_visitor {
    my $key=visitor_key();return $key if $key;
    $key=random_id();
    $cookie_header="bf_visitor=$key; Path=/; Max-Age=315360000; Secure; HttpOnly; SameSite=Lax";
    return $key;
}
# A visitor's address for rate limits, as a keyed hash: the same address
# gives the same value, but the address can't be read back.
sub ip_actor { return 'ip:'.hmac_sha256_hex($ENV{REMOTE_ADDR}//'unknown',comments_secret('salt')) }
# Each limit is [actor, maximum, seconds]. Records one event per distinct actor.
# Checks rate limits: each limit is [who, at most how many, in how many
# seconds]. If any is reached, returns 0. Otherwise records the event for
# each "who" and returns 1. Now and then (1 in 20 calls) events older than
# two days are cleared.
sub rate_ok ($c, $kind, @limits) {
    my $now=time;
    $c->do('DELETE FROM events WHERE at<?',undef,$now-2*86400) if rand()<0.05;
    for my $l (@limits) {
        my ($actor,$max,$secs)=@$l;
        return 0 if $c->selectrow_array('SELECT count(*) FROM events WHERE kind=? AND actor=? AND at>?',undef,$kind,$actor,$now-$secs) >= $max;
    }
    my %seen;$c->do('INSERT INTO events(kind,actor,at) VALUES (?,?,?)',undef,$kind,$_,$now) for grep {!$seen{$_}++} map {$_->[0]} @limits;
    return 1;
}
# Names nobody else may comment under: the admin account, the author's names
# and the site's own, plus any listed in the settings.
# Words a username may not contain: the admin users' names, the author's
# name, the site's title and any reserved in the settings (3 letters or more).
sub reserved_words {
    my %w=map {(lc($_)=>1)} grep {length >= 3} split /[^\pL\pN]+/,join ' ',$instance{admin_user},(map {$_->{name}} @{(attempt {all_admin_users()}) // []}),setting('author'),setting('site_title'),setting('reserved_names');
    return keys %w;
}
my %reserved_exact=map {$_=>1} qw(mod mods owner staff system anonymous anon root);
# Checks a username and returns (the name as shown, its key), or
# (undef, a reason). The key is the name folded to lowercase without spaces
# or punctuation, so "Ann Lee" and "annlee" are the same username. Names like
# admin, moderator or the site's own are refused.
sub comment_name ($raw) {
    my $name=NFKC($raw);$name =~ s/\s+/ /g;$name =~ s/\A | \z//g;
    return (undef,'name') unless length($name)>=2 && length($name)<=32 && $name =~ /\A[\pL\pN][\pL\pN _.'\-]*\z/;
    my $key=fc $name;$key =~ s/[^\pL\pN]//g;
    return (undef,'name') unless length($key)>=2;
    return (undef,'reserved') if $reserved_exact{$key} || $key =~ /admin|moderator|webmaster/ || grep {index($key,$_)>=0} reserved_words();
    return ($name,$key);
}
# Cleans a comment's text: control characters removed, line endings and
# blank lines tidied, up to 2,000 characters and at most two links (to keep
# spam out). Returns (text, '') or (undef, reason).
sub comment_body ($raw) {
    my $b=NFKC($raw);$b =~ s/\r\n?/\n/g;$b =~ s/[^\P{Cc}\n\t]//g;$b =~ s/\t/ /g;$b =~ s/[ ]+\n/\n/g;$b =~ s/\n{3,}/\n\n/g;$b =~ s/\A\s+|\s+\z//g;
    return (undef,'body') unless length($b) && length($b)<=2000;
    my $links=()=$b =~ m{(?:https?://|www\.)}gi;
    return (undef,'links') if $links>2;
    return ($b,'');
}
# The message shown for each outcome of posting.
sub comment_message ($code) {
    my %m=(ok=>'Thanks! Your comment is posted.',
        taken=>'That username already belongs to someone else. Choose another one, or comment from the browser where you first used it.',
        reserved=>'That username is reserved. Please choose another.',
        name=>"Usernames are 2–32 characters: letters, numbers, spaces and . _ - '",
        body=>'Write a comment of up to 2,000 characters.',
        links=>'Comments can include at most two links.',
        rate=>'You’re commenting quickly. Please wait a few minutes and try again.',
        dup=>'You already posted that comment.',
        unavailable=>'Comments are unavailable right now. Please try again later.');
    return $m{$code} // '';
}
# True when talk.js sent the request and wants a JSON answer.
sub wants_json { return ($ENV{HTTP_X_REQUESTED_WITH}//'') eq 'fetch' }
# Likes and comments must come from this site's own pages (or a browser that
# sends no Origin).
sub public_origin_ok { my $o=$ENV{HTTP_ORIGIN}//''; return $o eq '' || own_origin($o) }
# A comment's text as HTML: escaped, blank lines between paragraphs, single
# line breaks kept.
sub comment_html ($body) {
    return join '',map {my $p=h($_);$p =~ s/\n/<br>/g;"<p>$p</p>"} split /\n{2,}/, $body;
}
# The Comments screen (/admin/comments/, in the comments service). It has
# its own CSRF cookie (bf_comments_csrf) signed with the comments service's
# own key, as the admin's key isn't readable here. Actions: hide or show a
# comment, delete it, or release its username so someone else can take it.
# The list shows the newest 300, for one item, one library or everything,
# each with the item it's on.
sub comments_admin {
    require_admin() or return;
    my $c=attempt {comments_db(1)};
    unless ($c) {admin_page('Comments',section=>'comments');window('comments','<p>Comments aren’t set up on the server yet.</p>');end_page();return}
    attempt {csrf_setup(comments_secret('csrf'),'bf_comments_csrf','/admin/comments/');1} or do {header(403,'text/plain; charset=UTF-8');print h(clean_error($@));return};
    my $message=param('notice',2000);
    # What the list shows: one item (its reference), one library, or everything.
    my $item_filter=param('item',60);$item_filter='' unless item_from_ref($item_filter);
    my $kind_filter=param('library',20);$kind_filter='' unless item_kinds()->{$kind_filter};
    my $keep=join '&',($item_filter ? 'item='.CGI::escape($item_filter) : ()),($kind_filter ? "library=$kind_filter" : ());
    if ($method eq 'POST') {
        attempt {
            my $action=param('action',30);my $id=param('id',32);
            my $item=$c->selectrow_hashref('SELECT * FROM comments WHERE id=?',undef,$id) or die "That comment no longer exists.\n";
            my $done;
            if ($action eq 'hide' || $action eq 'show') {$c->do('UPDATE comments SET hidden=? WHERE id=?',undef,$action eq 'hide'?1:0,$id);$done=$action eq 'hide'?'Comment hidden.':'Comment visible again.'}
            elsif ($action eq 'delete') {$c->do('DELETE FROM comments WHERE id=?',undef,$id);$done='Comment deleted.'}
            elsif ($action eq 'release') {$c->do('DELETE FROM names WHERE name_key=?',undef,$item->{name_key});$done='Username “'.$item->{display}.'” released. Anyone can claim it now; existing comments keep it.'}
            else {die "Choose an action.\n"}
            redirect('/admin/comments/?'.(length $keep ? "$keep&" : '').'notice='.CGI::escape(encode('UTF-8',$done)));1;
        } or $message=failed_action($@);
    }
    my ($where,@args)=('');
    if ($item_filter) {($where,@args)=(' WHERE post_id=?',$item_filter)}
    elsif ($kind_filter) {my $r=item_kinds()->{$kind_filter}{ref};($where,@args)=length $r ? (' WHERE post_id LIKE ?',"$r:%") : (" WHERE post_id NOT LIKE '%:%'")}
    my $list=$c->selectall_arrayref("SELECT * FROM comments$where ORDER BY created_at DESC LIMIT 300",{Slice=>{}},@args);
    # Each comment's item (found even when it's no longer public), once.
    my %items;my $item_of=sub ($ref) {$items{$ref} //= do {my ($k,$i)=item_from_ref($ref);($k ? item_find($k,$i,all=>1) : undef) // 0}};
    admin_page('Comments',section=>'comments',notice=>$message,intro=>'Comments on articles, pictures, music and videos publish immediately. Hide anything you don’t want shown, delete spam, or release a username so someone else can use it.');
    my $html='<form method="get" action="/admin/comments/" class="inline-form comments-filter" data-auto-submit><label>Show <select name="library"><option value="">every library</option>'
        .join('',map {'<option value="'.$_.'"'.($_ eq $kind_filter ? ' selected' : '').'>'.h(lc item_kinds()->{$_}{label}).'</option>'} item_kind_order()).'</select></label> <button class="buttonlike no-js-only" type="submit">show</button></form>';
    if ($item_filter) {my $i=$item_of->($item_filter);$html.='<p>Showing comments on “'.h($i ? $i->{title} : 'something deleted').'”. <a href="/admin/comments/">Show all</a></p>'}
    $html.='<p class="empty-media">No comments yet.</p>' unless @$list;
    for my $row (@$list) {
        my $i=$item_of->($row->{post_id});my $what=$i ? item_kinds()->{$i->{kind}}{one} : '';
        my $on=$i ? '<a href="'.h(item_path($i)).'#comment-'.h($row->{id}).'" target="_blank" rel="noopener">'.h($i->{title}).'</a> ('.h($what).') · <a href="/admin/comments/?item='.CGI::escape($row->{post_id}).'">only this '.h($what).'</a>' : '<em>something deleted</em>';
        $html.='<article class="admin-comment'.($row->{hidden}?' is-hidden':'').'"><p class="comment-meta"><strong>'.h($row->{display}).'</strong> · '.h(substr($row->{created_at},0,16) =~ s/T/ /r).' UTC · on '.$on.($row->{hidden}?' · <span class="badge">hidden</span>':'').'</p><div class="comment-body">'.comment_html($row->{body}).'</div><div class="admin-comment__actions">';
        my $form=sub ($action,$label,$class='') {'<form method="post" action="/admin/comments/"'.($action eq 'delete'?' class="delete-form"':'').'>'.hidden(csrf=>$csrf,action=>$action,id=>$row->{id},item=>$item_filter,library=>$kind_filter).'<button class="text-button'.$class.'">'.$label.'</button></form>'};
        $html.=switch_button('comments',$row->{hidden}?'show':'hide',$row->{id},!$row->{hidden},'shown',what=>'Shown on the site',name=>"the comment by $row->{display}",to=>'/admin/comments/',post=>{item=>$item_filter,library=>$kind_filter})
            .row_menu("the comment by $row->{display}",$form->('release','release username').$form->('delete','delete',' danger'));
        $html.='</div></article>';
    }
    window('recent comments',$html);end_page();
}
1;