repository

BlowfishCMS

A small content management system for OpenBSD

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

393 lines · 26.7 KB · view the source · download this file

Writing a BlowfishCMS add-on

An add-on is a folder that adds one feature to a BlowfishCMS site: a block type, an admin screen, a few public addresses. It plugs in at a fixed set of places (hooks) and nowhere else, so core stays small and predictable. An add-on that's switched off is never loaded, so it costs nothing.

Add-ons live in the BlowfishCMS add-ons repository, one folder each. Its Store (store/) uses almost every hook and is the best example to read alongside this guide; GitHub projects (github/) is a small one with a settings screen and an hourly job. The sample in this repository's tests/fixtures/addons/hello/ is the smallest working one.

The folder

NAME/
  addon.json        what it is and what it adds (required)
  lib/Name.pm       its code (required)
  public/           CSS, JS and images, served at /addons/NAME/ (optional)
  tests/            its own tests (optional)
  README.md         what it does and how to set it up (recommended)

NAME is 2–20 lowercase letters and digits, starting with a letter, and must match the folder's name.

A site installs an add-on from an archive of its folder (NAME-1.0.0.tar.gz) uploaded on its Add-ons screen (or blowfishctl addon add, then addon install NAME). They go in /opt/blowfishcms-addons/NAME, which BlowfishCMS updates leave alone. A fresh install has none.

addon.json

{
  "name": "store",
  "label": "Store",
  "version": "1.0.0",
  "blowfishcms": "0.39.0",
  "description": "One or two sentences shown on the Add-ons screen.",
  "author": "Your name",
  "module": "lib/Store.pm",
  "package": "BlowfishCMS::Addon::Store",
  "service": true,
  "network": ["api.stripe.com"],
  "admin": [
    {"label": "Products", "screen": "admin"},
    {"label": "Orders", "screen": "service"}
  ],
  "assets": {"css": ["store.css"], "js": ["store.js"]}
}
KeyRequiredMeaning
name, label, versionyesVersion as 1.2.3.
blowfishcmsyesThe oldest BlowfishCMS version it works with. Older sites list it as unusable.
module, packageyesThe .pm file under lib/, and the package it defines (BlowfishCMS::Addon::Something).
description, authornoShown on the Add-ons screen.
servicenotrue if it needs secrets or outside connections; see Services below.
networknoEvery outside host it connects to. Shown to the site owner before they switch it on.
filesnotrue for a folder the add-on's service writes and httpd serves as they are, at /x/NAME/files/ (needs service). Find it with addon_files_dir("NAME"). Live keeps its stream's pieces there, so visitors fetch them straight from httpd. Everything in it is public.
request_maxnoThe most its addresses take in one request, in MB (1 to 64). Without it, 1 MB. Live takes 32 MB pieces.
adminnoIts admin screens, as one object or a list. screen is admin, service or page (the core's Page tab, under the label given here, for an add-on whose only screen is its page, such as Photography); see Admin screens. They appear as the add-on's tab on Site → Add-ons (several screens get a second row of tabs, as the Store's Products and Orders do). Since 0.44.0 a service screen may give a path (a lowercase word, such as "pod"): it's another screen of the add-on's service, at /admin/x/NAME/PATH, which service_admin receives as $rest and marks with section=>'x-NAME-service-PATH' (the Store's Print on demand).
assetsnoCSS and JS files under public/, added to the public pages that use the add-on while it's on: its own page, pages with its blocks, and its addresses under /x/NAME/. Add "everywhere": true for files every page needs (the Store's cart, which follows the buyer from page to page). Keep them small.
admin entries with hrefnoA link to a core screen, listed with the add-on: {"label": "Articles", "href": "/admin/?kind=blog"}. Core screens stay in the sidebar; since 0.39.2 a claims key is accepted and ignored (it used to move the screen into the add-on's tab).
pagenoIts own page: {"slug": "shop", "label": "Shop", "title": "Shop", "description": "…", "blocks": [{"type": "store_products", "width": "full", "data": {…}}]}. Switching the add-on on makes it (off, so the owner can fill it first), unless a page is already at one of the addresses its adopt list names, which becomes its page instead; the address falls back to the add-on's name, then a number. Each add-on gets a page once, so one the owner deletes isn't made again; instead a page the owner makes or moves to one of its adopt addresses, its slug or its name becomes its page, or the owner picks one on its Page tab (use this page). The page is edited on the add-on's Page tab: the page editor itself, under the add-on's tabs, after its own screens; edit in Pages and the page editor go there. A page with none of the blocks listed here is offered them (add NAME's blocks). While the add-on is off the page answers "not found". adopt (a list of addresses) takes over a page at one of them; blocks may be the core's own block types.

Hooks

Define any of these subs in your package. All are optional.

HookCalledReturns
migrate($db)when the add-on is switched on, and on every --migrate (updates)nothing. Create or alter your own tables, named NAME_…, with IF NOT EXISTS.
blocks()when pages are built{ NAME_type => spec }. A spec is like a core block type, plus render => sub ($block, %options) { … } returning HTML, and optionally about, one line shown under its name in the page builder's block choices. Fields use the core kinds: text and markdown (their fourth entry is the most characters, such as ['note','Note','markdown',4000]; without it 300 and 20,000), select, number, check, and items, a list of entries, each with its own fields: [name, label, 'items', [[sub, label, kind, …], …]], saved as a list of hashes; its button reads “add” and the label made singular (Resume's entries).
route($rest)for /x/NAME/$resttrue when it answered. Return false for a 404.
admin()for /admin/?kind=x-NAME (admin service)true. Use admin_page, window and end_page.
service_admin($rest)for /admin/x/NAME/$rest (your service)true when it answered.
sitemap()building /sitemap.xml[[path, 'YYYY-MM-DD'], …]
robots()building /robots.txt['/x/NAME/private/', …], addresses to keep out of search engines.
hourly()every hour, from root's crontab, as the admin service's account (it can write the catalogue)a line for the log (/var/log/blowfishcms-hourly.log). Die with a message when it fails. GitHub projects syncs here.
from_service($data)within a minute of the add-on's own service handing something over with addon_hand_over (0.45.0), as the admin service's account (it can write the catalogue and media)a line for the log (/var/log/blowfishcms-requests.log). Die with a message when it can't be done: the hand-over is kept in addons-in/failed/ with why, for a week. See Hand-overs below.

Every block type also gets two settings from the core, added after its own fields: an Anchor (section_anchor, made the id of the first tag your render returns, unless it already has one) and Leave out when printed (print_hide). Start your block's HTML with one element so the anchor has somewhere to go.

A block field of kind markdown gets the admin's Markdown toolbar and shortcuts by itself. A Markdown box on your own admin screen gets them too when its <textarea> has data-markdown (data-markdown="pictures" adds the picture button); markdown_help_html() prints the Markdown help, which the toolbar's ? opens (one per screen: its id is md-help).

A block's data is saved with the page. If your add-on is switched off, its blocks stay on their pages but aren't shown, and the page builder marks them.

Admin screens

There are two kinds of admin screen, because the services that run them have different rights:

  • "screen": "admin", at /admin/?kind=x-NAME, runs in the admin service. It can write the catalogue and upload media, but can't read any secrets. Store's Products screen is one.
  • "screen": "service", at /admin/x/NAME/, runs in your own service. It can read your private folders, such as API keys and orders, and can only read the catalogue. Store's Orders screen is one.

Neither is in the sidebar: while the add-on is on, it has a tab, named after its label, on Site → Add-ons, which opens its first screen; with more than one screen, they're a second row of tabs under it. The two kinds of screen mark their tab with section=>'x-NAME' and section=>'x-NAME-service' in admin_page.

Both are for signed-in owners only: the core checks the sign-in (and, where the site requires it, two-step sign-in) before your hook runs, so your code never sees anyone else. Each has its own CSRF key: build forms with fields($action, "x-NAME", $id) and they're checked for you.

fields() already includes an id field, so pass the item's id as its third argument. Never add a second hidden(id=>…). A browser sends both fields, param('id') reads the first one, which is empty, and the action falls back to "new item".

Buttons use the admin's words (listed in the core's Admin.pm): save for a form, add X for a form that makes something, new X for a link to an empty editor, delete for what the owner made, remove for taking something out, × to close. A filter applies when it changes: give its form data-auto-submit and its button the class no-js-only.

A list of things (yours, or the owner's) is drawn with the core's rows, so it looks and works like every other list: admin_list([map {admin_row(title=>…, meta=>[…], actions=>…, menu=>…)} @things], empty=>'Nothing yet.'). Switches and everyday buttons go in actions, the rarer ones (move, delete) in menu, the row's …. Tables are for records read across columns (orders, answers).

A list the owner puts in order works like every other one in the admin: drag a row by its handle, or use move up / move down in its … menu. The core does both; give the list order_list_attrs("x-NAME"), each row order_row_attrs($id) and drag_handle(), and its menu row_menu($name, move_buttons("x-NAME", $id, $position, $count, label=>$name)). Then, before your own actions:

list_order(ids=>[map {$_->{id}} @{things()}], back=>'/admin/?kind=x-NAME',
    save=>sub (@ids) {sort_order_save(db(), 'NAME_things', 'id', @ids)});

Anything that's on or off is a switch. In a list's row it acts at once: switch_button("x-NAME", "thing_active", $id, $on, "for sale", what=>"For sale", name=>$title) posts thing_active with on set to 1 or 0, the state wanted. In a form that's saved with a button, switch_field("name", "Label", $on, hint=>"…") is a tick box drawn as a switch, with a hidden 0 after it so that off is sent too. Keep tick boxes for choosing things and for agreeing to something.

list_order handles order (every id, dragged) and move (one id up or down), saves through your save, answers the script with JSON and a form with a redirect, and returns false for any other action. Links, Services, Store and Repositories do this.

Services

An add-on with "service": true gets the following when it's switched on (the server does it for the Add-ons screen within a minute, or doas blowfishctl addon enable NAME):

  • Its own account, _bfxNAME, in the _bfpublic group so it can read the catalogue.
  • A data folder for its own database and files. It's included in backups. Find it with addon_data_dir("NAME").
  • A secrets folder for API keys. It's only in --with-secrets backups. Find it with addon_secret_dir("NAME").
  • Its own FastCGI service, blowfish_xNAME.
  • httpd addresses: /x/NAME/* and /admin/x/NAME/* go to that service.
  • With "files": true, a served folder, NAME-files beside its data folder: the add-on's account writes it, httpd reads it (group www), and /x/NAME/files/* is served from it as files, with Cache-Control: no-cache. It isn't for anything private.

Without service, /x/NAME/* is answered by the public service, which can only read the catalogue, and the switch takes effect at once rather than through the server.

Keep secrets in the secrets folder, readable only by your account (mode 0400). Never show a saved secret again; say whether it's set.

Hand-overs: from your service to the catalogue (0.45.0)

Your service can read your secrets but not write the catalogue; the admin service can write the catalogue but not read your secrets. When something your service learns (with its API key) should change the catalogue, your service hands it over:

BlowfishCMS::addon_hand_over('store', {kind => 'printful', products => [...]});

It's written as a JSON file into your data folder's to-admin/. Within a minute root's runner (blowfishctl requests) moves it into the admin's addons-in/ (a file is taken only if it's a plain file of your account's, up to 8 MB) and runs site.pl --addons-in as the admin's account, which passes the data to your from_service($data) hook, oldest first. What it returns is logged; when it dies, the hand-over is kept in addons-in/failed/ with why, for a week. Check what you're handed as you would a form: it comes from your own service, but through files. The Store hands over Printful's products this way, which from_service adds to the Products library.

The core API

Call core functions as BlowfishCMS::name(...), or import the ones you use as Store does (BEGIN { *{$_}=\&{"BlowfishCMS::$_"} for qw(h param ...) }). These are stable:

AreaFunctions and variables
Outputh (escape HTML), header, redirect, json_response, finish; to send a file byte for byte after header(...) (a download), set $BlowfishCMS::stream_path to its path and return: the page's own output is UTF-8 text, which would change a binary file (Repositories does this)
Pagesstart_page, window, window_html, end_page, render_markdown, json_ld
Adminadmin_page, failed_action, fields, hidden, fetch_request; for lists in order (0.41.0): list_order, sort_order_save, order_list_attrs, order_row_attrs, drag_handle, move_buttons, row_menu; for on and off (0.41.0): switch_button, switch_field; for lists (0.41.0): admin_row, admin_list
Requestsparam($name, $max) (trimmed, UTF-8 decoded, length-checked), $BlowfishCMS::q (CGI), $BlowfishCMS::method, $BlowfishCMS::route
Data$BlowfishCMS::db (the catalogue: read-write in the admin service, read-only elsewhere), setting, addon_setting($name,$key,$default), addon_setting_save($name, key=>value…) (admin service)
Filessave_image($fh, $folder), remove_image($folder, $file), addon_data_dir, addon_secret_dir, addon_files_dir (with "files": true); addon_hand_over($name, $data) (0.45.0, in your service: see Hand-overs)
Pictureschoose_picture_button($title) beside a file field adds "or choose from Pictures"; upload_or_picture($field) then returns the uploaded file or the chosen library picture, for save_image to copy
Sitesite_url, own_origin, now, random_id, attempt { … } (eval that lets finish through)
Mail`mail_queue($name, to=>'owner'address, subject=>…, text=>…, html=>…, reply_to=>'owner'address, from_name=>…, tag=>…, headers=>{…})queues an email in the service's own outbox; within a minute it's sent through the site's Postmark connection.owneris the site owner (the update alerts address, else the receiving address), which add-ons can't read themselves.mail_address_ok($address)` checks an address.
VideosAn add-on with its own service hands a video to the Videos library by writing NAME.mp4 and then NAME.json ({"title": …, "description": …, "collection": …, "tags": "#one #two"}, all optional) into its data folder's videos/ (addon_data_dir("NAME")."/videos"); NAME is letters, digits, - and _. Within a minute root's runner moves them to the admin, which adds the video at the top of the library, public at once. A fragmented MP4 (HLS fMP4 pieces joined in order, as Live records them) is joined into an ordinary one; an ordinary MP4 is added as it is. One that can't be added is listed on the Overview. Write the JSON note before renaming the finished video into videos/: the runner takes a video only with its note. Live 1.1.0 uses this for saved streams.
DirectoriesA list of cards visitors search, filter and sort (GitHub projects, Repositories), with no script of its own: project-* classes for the look, and data-directory on a wrapper holding a form data-directory-tools (hidden until the script runs) with data-directory-search, selects data-directory-filter="KEY" (data-fill adds the cards' values; data-match="words" for space-separated ones) and data-directory-sort (option values are keys, - first for descending), a grid data-directory-grid of data-card elements carrying data-KEY values, data-directory-count (data-noun), data-directory-empty and data-directory-reset buttons.
Block settingsShared with the core's blocks, so an add-on's block works like them: link_fields($name,$label) and link_attrs($data,$name) (a link and "open in a new tab"); button_fields($prefix,$label) and button_html($data,$prefix); shape_fields() and shape_class($data) (picture shape and focus); list_fields($what) and list_cut($data,$items) (order, a limit and "See all"); cta_html($label,$link,style=>…); tones() and button_colours() for colour choices. Spread the *_fields into a block's fields.
Codecode_highlight($lang,$text,lines=>1): escaped HTML with the tokens in tok-* spans the core's stylesheet colours (with lines, each line a <span class="line" id="LN">); code_language($file_name,$text) and code_language_named($word) find the language ('' when none is known, which gives plain text). Repositories uses them since 1.2.0
Markdownrender_markdown($text) for anything visitors see. In the admin, data-markdown on a <textarea> gives it the toolbar and shortcuts; markdown_help_html(note=>…), once per screen, adds the help the toolbar's ? opens (Store, Forms, Newsletter, Events and Services since 0.40.3)
PaymentsSince 0.40.3 (Store 1.3.0, Services 2.1.0). Money: currencies(), money($amount,$cur,whole=>1) ("$85" rather than "$85.00"), parse_money($text,$what,$cur) (dies with a message), money_input($amount,$cur). Stripe Checkout, keys kept per add-on 0400 in its secret folder: stripe_secret($name,$file), stripe_secret_save($name,$file,$value), stripe_live($key), stripe_request($name,$verb,$path,\@pairs), stripe_problem($status,$reply); stripe_webhook_event($name) checks the signature and returns ($event,'') or (undef,$why); stripe_panel_html($name,$address,webhook=>…,last=>…,unset=>…) draws the keys panel and stripe_panel_action($name,$action) saves or removes them (returns a message, dies with what was wrong, or returns undef for another action). BLOWFISH_STRIPE_API in the start-up environment points them at a stand-in
QuestionsSince 0.40.3 (Forms 1.1.0, Services 2.1.0). An owner's questions, each {id, label, type, options, required}: questions_editor_html($id,$questions) (a list field in #bulk-edit) and questions_from_form($id,$old,max=>40) (dies with a message; ids kept while the words stay). A visitor's answers: question_html($q,id=>…,value=>…) (fields named a.ID; classes question-option, question-choices, optional), question_posted($q) (to fill the form in again), question_answers($questions) returns (\@answers,$problem,$email); question_kinds(), question_options($q)
Start-up%BlowfishCMS::startup_env: the environment when the process started. A FastCGI worker's %ENV changes on every request, so read your own settings from here.

Rules for add-ons

  1. Small and fast. No build step and no third-party JavaScript on public pages. Assets load on every page that uses the add-on (on every page with "everywhere": true), so keep them tiny.
  2. Escape everything you print with h(). Markdown goes through render_markdown.
  3. The security policy stays strict: default-src 'self', no inline scripts or styles. <script type="application/ld+json"> is fine (it's data, not code).
  4. A form can't be redirected to another site under form-action 'self'. Answer with JSON and navigate from your JS, as Store does for Stripe, or with a page that links on.
  5. Own tables only. Prefix them NAME_, and never change core tables.
  6. Declare every outside host in network.
  7. Test against stand-ins, never the real service. Store's tests run a local fake Stripe through BLOWFISH_STRIPE_API.

Settings and secrets

Add-ons have two places to keep configuration, depending on who may read it.

  • Ordinary settings (currency, button text, layout choices) go in the catalogue with addon_setting_save("NAME", key => value, …), called from your admin() screen. Read them anywhere with addon_setting("NAME", "key", "default"). Every service can read them, so never put secrets here.
  • Secrets (API keys, signing secrets) are files in addon_secret_dir("NAME"), written only from your service_admin screen, mode 0400. The Store's write_secret and read_secret show the pattern:
    • check a key with the service it belongs to before saving it;
    • show only whether it's set, or which mode it is in (test or live);
    • offer a "remove" button.

If something needs setting up outside the site (a DNS record, a webhook, an account on another service), say so on your admin screen, with the exact values to copy, such as the webhook address. Then repeat it in your README.

Testing your add-on

Each add-on keeps its tests in its own tests/ folder, written the way the core suites are (the add-ons repository's store/tests/store.py is the template). They run against a BlowfishCMS checkout:

  • Run the site from a temporary folder with its own settings file and catalogue (BLOWFISH_ROOT), so nothing real is touched.
  • Point any outside service at a local stand-in, started by the test. The Store reads BLOWFISH_STRIPE_API from %BlowfishCMS::startup_env.
  • Submit the page's own forms, read from its HTML, the way a browser would, rather than posting fields you made up. That catches mistakes such as a form sending the same field twice.
  • Run every test twice: once with cgi-bin/site.pl, and once with tests/fcgi-cgi.pl, which goes through FastCGI the way the server does. State leaking between requests only shows up the second way.
  • Set BLOWFISH_ADDONS_PATH to the add-ons repository's folder, so the site finds the add-on you're testing.
  • Sign requests in the way a browser is signed in: build the request's environment with 'REMOTE_USER' naming the user (or '' for nobody) and pass it through signin.sign() from the checkout's tests/signin.py, which turns the name into a signed session cookie (the admin trusts nothing else). The site's own admin account is made an owner if it isn't a user yet; other names have to be added by the test.
# from the core checkout, with the add-ons repository beside it as ../addons
python3 ../addons/tests/services.py cgi-bin/site.pl
python3 ../addons/tests/services.py tests/fcgi-cgi.pl

Documenting your add-on

Every add-on ships a README.md in its folder. Site owners read it before switching the add-on on, and again when something goes wrong. Use this outline; the Store's README.md follows it:

# Add-on name

One or two sentences: what it does for the site owner.

| | |
|---|---|
| Version | 1.0.0 |
| Needs | BlowfishCMS 0.39.0 or newer; any outside account |
| Connects to | every host in "network", or "nothing" |
| Runs as | the public/admin services, or its own service |
| Keeps | what data it stores, and where |

## Switching it on
Install it on the Add-ons screen, and what appears afterwards.

## Setting it up
Numbered steps. Name every field on your screens, and say exactly what to
copy from any outside service and where to paste it.

## Day to day
What the owner does regularly, and where.

## Troubleshooting
A table: "what you see" against "cause and fix". Include every error
message your add-on shows.

## Limits
What it deliberately doesn't do (yet).

Write for the site owner, not for programmers:

  • Say what each field is for, not how it's stored.
  • Give exact menu paths in other services ("Stripe → Developers → Webhooks").
  • Every error your add-on can show should have a troubleshooting row.
  • Notes for developers (hooks, tables) go in comments at the top of your module.

Before you release: checklist

  • addon.json passes (the Add-ons screen shows no "Can't be used").
  • network lists every outside host.
  • Every printed value goes through h(), and Markdown through render_markdown.
  • Forms use fields($action, "x-NAME", $id), with no second id.
  • Secrets are only in addon_secret_dir, mode 0400, and never shown again.
  • Tables are named NAME_… and created with IF NOT EXISTS.
  • Tests pass through both cgi-bin/site.pl and tests/fcgi-cgi.pl.
  • The add-on works after being switched off and on again, and its blocks hide cleanly while it's off.
  • README.md follows the outline above.
  • version is raised, and blowfishcms names the oldest release it needs.

Releasing an add-on

An add-on is released as an archive of its folder, NAME-VERSION.tar.gz, holding NAME/ and everything in it but its tests/. Owners upload it on their Add-ons screen, which offers:

  • install for add-ons it doesn't have, when its BlowfishCMS is at least the add-on's blowfishcms;
  • update to X for installed add-ons whose uploaded version is newer. Updates are never installed by themselves: the owner presses the button.

An archive may hold several add-ons, each in its own folder (directly, or under one top folder, as a repository's archive is); a server with /etc/blowfishcms-addons-url fetches such an archive each night. So raise version with every change a site should take; an archive whose add-on is older than the site's list has is left out. An install or update copies the add-on's folder to /opt/blowfishcms-addons/NAME (the replaced copy is kept as .NAME.previous.TIME), checks its addon.json against the site's release (and puts the old copy back if it doesn't fit), runs the migration and restarts the services.

doas blowfishctl addon add NAME-1.0.0.tar.gz
doas blowfishctl addon install NAME