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"]}
}
| Key | Required | Meaning |
|---|---|---|
name, label, version | yes | Version as 1.2.3. |
blowfishcms | yes | The oldest BlowfishCMS version it works with. Older sites list it as unusable. |
module, package | yes | The .pm file under lib/, and the package it defines (BlowfishCMS::Addon::Something). |
description, author | no | Shown on the Add-ons screen. |
service | no | true if it needs secrets or outside connections; see Services below. |
network | no | Every outside host it connects to. Shown to the site owner before they switch it on. |
files | no | true 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_max | no | The most its addresses take in one request, in MB (1 to 64). Without it, 1 MB. Live takes 32 MB pieces. |
admin | no | Its 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). |
assets | no | CSS 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 href | no | A 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). |
page | no | Its 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.
| Hook | Called | Returns |
|---|---|---|
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/$rest | true 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_bfpublicgroup 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-secretsbackups. Find it withaddon_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-filesbeside its data folder: the add-on's account writes it, httpd reads it (groupwww), and/x/NAME/files/*is served from it as files, withCache-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:
| Area | Functions and variables | ||
|---|---|---|---|
| Output | h (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) | ||
| Pages | start_page, window, window_html, end_page, render_markdown, json_ld | ||
| Admin | admin_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 | ||
| Requests | param($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) | ||
| Files | save_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) | ||
| Pictures | choose_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 | ||
| Site | site_url, own_origin, now, random_id, attempt { … } (eval that lets finish through) | ||
| `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. | |
| Videos | An 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. | ||
| Directories | A 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 settings | Shared 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. | ||
| Code | code_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 | ||
| Markdown | render_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) | ||
| Payments | Since 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 | ||
| Questions | Since 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
- 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. - Escape everything you print with
h(). Markdown goes throughrender_markdown. - 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). - 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. - Own tables only. Prefix them
NAME_, and never change core tables. - Declare every outside host in
network. - 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 youradmin()screen. Read them anywhere withaddon_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 yourservice_adminscreen, mode 0400. The Store'swrite_secretandread_secretshow 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_APIfrom%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 withtests/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_PATHto 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 throughsignin.sign()from the checkout'stests/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.jsonpasses (the Add-ons screen shows no "Can't be used"). -
networklists every outside host. - Every printed value goes through
h(), and Markdown throughrender_markdown. - Forms use
fields($action, "x-NAME", $id), with no secondid. - Secrets are only in
addon_secret_dir, mode 0400, and never shown again. - Tables are named
NAME_…and created withIF NOT EXISTS. - Tests pass through both
cgi-bin/site.plandtests/fcgi-cgi.pl. - The add-on works after being switched off and on again, and its blocks hide cleanly while it's off.
-
README.mdfollows the outline above. -
versionis raised, andblowfishcmsnames 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
versionis 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