Files
uberbringer/docs/plans/templates.md
T
57_WolveandClaude Opus 5.5 b06f2d8d65
Security / Vulnerability check (push) Successful in 45s
Test / Lint and test (push) Successful in 2m0s
Record the owner's acceptance of the ntfy plan
The owner accepted every proposed default of docs/plans/ntfy.md on
2026-12-01, keeping WebSockets first. Its open questions become
numbered decisions, without the alternatives, and design.md's Planned
next item 6 records them.

The plan's acceptance edits are made: design.md gives the conditions
under which ntfy replays a topic's whole history for a message ID;
formatters.md's phase 5 loses its publish endpoint item, since there is
none; templates.md's findings lose the open point on that endpoint.
formatters.md is not yet folded into design.md: printers.md and
job-store.md, not yet accepted, still plan edits to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:34:27 -06:00

578 lines
69 KiB
Markdown

# Plan: templates and rules in Expr, for ntfy and webhooks
Status: **planned; nothing is built.** The owner accepted every proposed default on 2026-12-01 (Decisions), and design.md's Planned next item 5 records them. Each stage runs in its own session, briefed from its section: stage 1 follows decisions 1-11, stage 2 decisions 12-17, stage 3 decision 18, and stage 4 decisions 19-29. The stages run in order, except that stage 3 needs only stage 2, and stage 4 needs stages 1 and 2. This plan shares Expr with docs/plans/printers.md, whose questions still await the owner; where a stage leans on one of its assumed defaults, the decision here says so. Stage 4 leans on docs/plans/job-store.md in the same way, on its stage 1c and question 10's duplicate check (decision 22). Every receipt printed on the live printer needs the owner's OK. Whichever stage finishes last deletes this plan, its findings with it, and design.md's Planned next item 5.
## Decisions (owner, 2026-11-30)
- **Templates and rule actions for webhooks and ntfy subscriptions are
written in Expr** (`github.com/expr-lang/expr`), as in Kanrisha's policy
engine, and share the routing engine that docs/plans/printers.md sets
out (`internal/pkg/rules`).
- **Webhooks come after templates,** since a webhook needs a template to
become a receipt.
The owner accepted the details below on 2026-12-01. They are numbered, so the rest of the plan can refer to them.
For stage 1:
1. **Who adds Expr and the shared engine.** printers.md adds Expr and `internal/pkg/rules` in its stage 2a, which may not have shipped when this plan starts. Whichever stage comes first adds Expr, at its latest stable release (v1.18.1, 2026-11-22, at the time of writing), with govulncheck, as printers.md question 10 plans. The licence notices and the binary's size, recorded in design.md, follow in the first commit that links Expr into the binary, since the notices come from what `./cmd/uberbringer` links (design.md:296-300). Stage 1 needs only the compile options both share, `rules.Options` (name assumed); stage 2 needs the engine. If printers stage 2a has not shipped by then, stage 2 builds `internal/pkg/rules` as printers.md's Architecture, ROUTING RULES, describes it, and printers stage 2a reuses it. If printers stage 2a has shipped with its options inline, stage 1's first commit moves them into `rules.Options` with no change in behaviour.
- This leans on printers.md's assumed defaults for rule order (its question 12), compile errors (14), runtime errors (15) and compile options (17). An answer there that differs changes stage 2 here the same way.
- Trade-off: the engine's interface is fixed here before the owner has answered printers.md. The first plan to ship carries the 5.3-5.8 MB that Expr adds.
2. **What a template is.** A template is one Expr expression, in one of two forms.
- `card`: the expression returns a map of a notification's fields (`title`, `message`, `markdown`, `priority`, `tags`, `topic`, `time`, `links`, `image` and `file`), and the existing card lays it out, as for the `notify` and `ntfy` modules: the priority's form, links as QR codes, markers, and every cap a card applies (design.md:116-176). On a subscription, the card is marked `(updated)` from what the subscriber knows, as today's card is.
- `elements`: the expression returns a list of elements, as a `/print` job's `elements` array. Expr's map and list literals and its `map`, `filter`, `concat` and `flatten` build it, so a template can lay out any receipt the blocks can.
- A template that returns `nil` prints nothing, so it can pass over a payload it has no receipt for.
- A template builds a `receipt.Job`, which takes the same path as any job: validation, the queue, then rendering in full before anything is sent.
- Trade-off: the shape of an `elements` result is checked only when it runs, not when it compiles: a JSON body has no Go type, so Expr types `body` as `any`. Decision 9 runs every template on its sample at load to catch most mistakes early.
3. **Where templates live.** Templates live in the config file, as a list of tables, `[[templates]]`, read from the file only, as `[[ntfy.subscriptions]]` is. Each has `name`, `description`, `input` (`json` or `ntfy`, decision 5), `form` (`card` or `elements`), `expr`, the expression, best written as a TOML multi-line literal string so that quotes need no escaping, and `sample`, a sample payload in JSON, which is required.
- A list of tables builds on the subscriptions' loader, so this plan does not wait for the named tables printers stage 1a adds, and `config get` already refuses to print one (config/value.go:28-30), samples included.
- The sample needs only the fields the template reads, so a payload of many kilobytes can be cut down to a few lines.
- No variable sets `[[templates]]`, nor, from later stages, `[[ntfy.rules]]` or `[webhooks]`. At start one WARN line names any `UBERBRINGER_TEMPLATES_*` or `UBERBRINGER_WEBHOOKS_*` variable, never its value, as printers.md question 2 does for its sections.
- Trade-off: long templates make the config long, and the config holds `api.secret`, so whoever edits templates can read it.
4. **Templates and the existing modules.** Every template is also a module. It appears in `GET /api/v1/modules` with its description, prints at `POST /api/v1/print/<name>` and previews at `POST /api/v1/preview/<name>`, with the same query (`copies`, `printer`), answers and token scopes as `note`, `notify` and `ntfy`. A `json` template takes a JSON object as its body, as the module routes document it (server/handlers_modules.go:21-23); an `ntfy` template takes one ntfy message object, decoded leniently as the `ntfy` module does.
- Template names share the modules' namespace and pattern, `^[a-z][a-z0-9-]{0,31}$` (modules/registry.go:96). A template named like a built-in module is a config error.
- So a script that can send a bearer token uses a template without a webhook, a token from `uberbringer token --modules <name>` limits it to that template, and the preview route is the dry-run over HTTP (decision 10). `uberbringer token` reads the config before it checks the names, which today it checks against the built-in modules only (internal/app/uberbringer/cli.go:156-161).
- Emoji are removed from the text fields of what a template returns (`text`, `title`, `footer`, `key`, `value`, list items and the card's fields), as on the notification path (design.md:134-138), rather than printed as `?`. `url`, `data` and `base64` are left as they are. The `note` module keeps printing them as `?`.
- `GET /api/v1/modules` lists every template's name and description to any token, those limited to other modules included. docs/security.md says so.
- Trade-off: the module list now depends on the config, and a later release whose new built-in module takes a template's name refuses that config at start, which is **Breaking** for it.
5. **What a template sees.** A template sees a typed environment per input, a Go struct whose `expr` tags name the variables, as printers.md's `routing.Env` is. Architecture, THE ENVIRONMENTS, lists them.
- `json`: `body`, the decoded body; and `now`. Stage 4 adds a webhook's `hook`, `event`, `delivery` and `headers`, which are empty on a module route.
- `ntfy`: a message's fields, those `FromNtfy` uses (modules/ntfy.go:85-119), the subscription's name and `now`. `http`, `broadcast` and `copy` actions stay out, since their headers, bodies and values can hold secrets (ntfy/message.go:104-116).
- Numbers: a body is decoded with `UseNumber`, and a whole number that fits 64 bits becomes an int, any other a float. Expr's `string()` prints a float in exponent form, so order 1234567 would print as `1.234567e+06`, and a 64-bit ID would lose digits. Expr's own `fromJSON` is replaced by one that decodes the same way.
- Two helper functions: `cut(s, n)`, which keeps at most `n` characters and ends a cut string with `...`, as titles are cut; and `stamp(t)`, which formats a time in `format.timezone` with `format.time_layout`, as cards print times.
- Trade-off: a template cannot read anything outside its payload, such as a printer's state or a value from another message.
6. **Compile options and Expr's limits.** The options of printers.md question 17, shared through `rules.Options`: `now()` and `$env` turned off, `Timezone` set to `format.timezone` once it is known to load, and Expr's default node limit (10,000) and memory budget (1,000,000 per run). `now` is injected: the time the payload was received, so a dry-run and the tests reproduce any output. Expr does no I/O. Turning off `$env` needs v1.18 or later: v1.17.8's checker ignores it.
- Expr counts no steps, and its VM takes no context, so a run cannot be stopped from outside (Investigation findings, EXPR). The text it loops over need not be the owner's: an issue's body or a commit message comes from whoever wrote it, and a `json` template on a module route takes a body from a token limited to modules. A predicate inside another, or `in` on a list inside a predicate, is quadratic in that text.
- So a run has a budget of 1,000,000 iterations. A `Patch` visitor (name of the guard assumed) wraps the list of every predicate builtin (`map`, `filter`, `all`, `any`, `none`, `one`, `count`, `sum`, `find`, `groupBy`, `sortBy`, `reduce` and the like) and the right side of `in` in a guard that charges the list's length, passed through `WithContext`. A nested predicate is charged on each pass of the outer one, so the bound is the total. A run past the budget fails, as any run that fails (decisions 8 and 15).
- A run still going after 1 s is logged at WARN with the template's or rule's name, from a timer, so even a run that never ends is seen.
- Trade-off: a template over a very large body can fail where it would only have been slow, and the guard is code of our own around Expr's AST.
7. **What a template's output may hold.**
- The result is encoded as JSON and decoded by the strict job decoder (`receipt.DecodeJob`, receipt/job.go:205), so an unknown key or a value of the wrong type is an error, then validated. A `card` result is decoded strictly into the notification's fields. A decoding error becomes a fixed message, `the result is not a job`, with at most a path we work out ourselves: Expr allows computed keys, such as `{(body.x): 1}`, and the decoder's own message, `unknown field "…"`, would quote the payload.
- The checks run on the decoded job, not on Expr's maps, since the decoder matches names in any letter case: a `HEX` key fills `hex`. `raw` is refused wherever it stands, at the top, in a box or, once blocks.md stage 5 has shipped, in a group, and so is a `hex` field on any element, whatever the token. formatters.md's invariant 5 holds: payload text only lands in string fields.
- One walker visits every string field of the decoded job by reflection, with a list of the fields it leaves alone (`url`, `data`, `base64`, `hex`); a test fails when `Element` gains a string field the walker does not place. Each text field is at most 4,096 bytes, ntfy's message limit, and the encoded result at most 256 KiB. Over either, the run fails; `cut` keeps a string inside the limit. `data` keeps validation's limits, and `base64` the 256 KiB. A `card` result is cut to the card's caps instead, as an ntfy card is.
- Every `image` a template builds is `optional`, as a card's are (modules/card.go:233). Its `url` may come from the payload. It is fetched by the worker through `safehttp`, like every image, so it cannot reach the host's own network unless `images.*` allows it, and a broken one prints `[image unavailable]` rather than failing the job.
- Each built job is laid out by the text preview, which fetches nothing, before it is queued, so a job over `format.max_lines` fails as a template's run fails, not later in the worker.
- Trade-off: a commit message over 4,096 bytes fails the receipt unless the template cuts it. A template cannot make an image required.
8. **A template that fails on a module route.** A run fails when Expr returns an error or the result fails decision 7's checks. The route answers `422` with a new code, `template_failed`, whose `details` give the template's name and, for an Expr error, the line and column, never Expr's message. The failure is logged once at WARN with the template's name and position, and reported to Sentry once per template per run, without the message, as printers.md question 15 does for a rule. A result that fails validation gives its problems' paths only, such as `elements[2] (kv)`, since a problem's text can quote the payload.
- Expr's messages quote values from the env, such as `invalid operation: int(alerts-door)` (printers.md, Investigation findings, EXPR), and the env holds print contents.
- The error type lives in `modules` (`TemplateError`, name assumed), so the server matches it without importing templates or Expr (invariant 7).
- `module_failed` stays for a built-in module's bug, which is a fault of the code; a template's failure is a fault of the config.
- Trade-off: the answer does not say what went wrong; `uberbringer template` (decision 10) does, on the terminal. A sender whose payloads vary, so that some lack a field the template reads, sends one Sentry event per template per run.
9. **Checking templates at load.** At start, in `config get` and in `preview`, each template compiles, runs on its sample, and its result passes decision 7's checks and renders in full through the text preview, which fetches nothing. Any failure is a config error naming the template. A compile error gives Expr's position and message, which quotes the template, not data. A failure on the sample gives the position only and points to `uberbringer template <name>`, since a sample may be a captured payload with private data.
- So `config get` and `preview` fail on any broken template, even for a job that uses none. docs/cli.md says so.
- Trade-off: a template whose sample is not representative still fails on real payloads.
10. **The dry-run and the preview.** A command, `uberbringer template <name> [payload.json|-]`, reads the config, runs the template on the payload, or on its sample without one, and prints the text preview, or with `--json` the built job. It prints Expr's message in full, on the terminal only. It sends nothing and fetches nothing. Over HTTP, `POST /api/v1/preview/<name>` previews a template with any payload (decision 4). `uberbringer preview --module <name>` works too, since a template is a module.
- Trade-off: two commands overlap; `template` alone shows Expr's message and the job.
11. **The `group` block.** blocks.md expects the group to be built with templates (its decision 22). Templates do not need it. This changes the reason blocks.md decision 22 gives for the group, and that bullet and blocks.md's Overview item 5 say so. Expr's `concat` and `flatten` turn one value into several elements of a flat list, which is what decision 22 names the group for. A group still comes with blocks.md stage 5 when a heading or a shared font is wanted, and decision 7's `raw` check then walks it.
- Trade-off: a template that wants a heading and a shared font for each item sets them on each element itself.
For stage 2:
12. **Where ntfy rules live, and their shape.** They live in `[[ntfy.rules]]`, a list of tables read from the file only, as `[[ntfy.subscriptions]]` is. Each rule has `name`, `order`, `when`, `action`, `template`, `bypass` (decision 16) and `enabled`, as printers.md's rules have (its questions 11 and 12): a unique name by the subscriptions' rule; a unique, required `order`, lower first, disabled rules included; and the first match wins. `when` sees decision 5's `ntfy` environment, `subscription` and `updated` included, so one list serves every subscription. `template` names a template whose `input` is `ntfy`; the config refuses one that does not.
- Trade-off: a rule for one subscription says so in `when`.
13. **The actions, and today's settings.** There are three actions.
- `print`: print the message, through `template` if it names one, or as today's card if it is empty;
- `drop`: leave the message out, with a DEBUG line naming the rule;
- `digest` (stage 3): hold the message for a digest of its own (decision 18).
- The rules run after the server's `min_priority` filter and after `updates = "skip"`, so a skipped update reaches no rule. `drop` and `digest` end there. `print` goes on through quiet hours, then the paper budget and `bypass_priority` (ntfy/subscriber.go:497-534). So the rules decide what prints and how, and the subscription's settings still decide when. A message no rule matches prints as today.
- A rule does not route. Which printer prints stays with printers.md's `[routing]` rules; where both have shipped, the routing environment gains `template`, the template's name or empty, so a routing rule can send by template.
- Trade-off: a dropped message counts nowhere but the DEBUG line, and two rule lists decide one message's fate.
14. **What an ntfy rule sees, and its errors.** Unlike a routing rule, which sees routing facts only (printers.md question 16), an ntfy rule sees the message's title and text, since choosing by them is the point. Its runtime error is handled as printers.md question 15 has it: the rule does not match, the next is tried, and a WARN line gives the subscription, the rule's name and Expr's position, never the message, at most once a minute per rule. A rule's `Explain` output goes to the terminal only.
- A panic while the environment is built, a rule runs or a template's result is walked is recovered, since on the subscription's goroutine it would end the daemon: logged at ERROR, reported once, and then the rule does not match, or the card prints.
- Trade-off: a rule can now read print contents, which raises the stakes of a log line that quotes it; the tests send a sentinel through every path (stage 2, Tests).
15. **A template that fails on an ntfy message.** The message prints as today's card instead, so a broken template loses nothing. The failure is logged at WARN with the subscription, the template and the position, and reported once per template per run, as decision 8. A template that returns `nil` prints nothing, as a `drop` does.
- Trade-off: a broken template's messages print in the wrong shape until someone reads the log.
16. **Held messages, `bypass`, and offers again.** Today a message the budget or quiet hours hold prints as a row of the digest: its title, or the first line of its text cut to 256 bytes (ntfy/ratelimit.go:113-139). A templated message's body is often the point: the `shop-order` example's text is JSON, so its row would read `{"number": 42, …` and the order's lines would never print.
- A `print` rule may set `bypass = true`: the message skips the paper budget, as one at `bypass_priority` does. During quiet hours `quiet.min_priority` still decides first, as design.md's paper budget decision has it.
- Without `bypass`, a held message prints as a digest row, as today; docs/templates.md warns of it.
- A rule's decision is made each time the subscription offers a message, and never stored. A message offered again after a full queue is decided again.
- Trade-off: a `bypass` rule can print more than the budget allows, which is what `bypass_priority` already does by priority. A reload between two offers can change the decision.
17. **Reloading.** Once printers stage 2b ships, SIGHUP swaps `[[templates]]`, `[[ntfy.rules]]` and, from stage 4, `[webhooks]` together with `[routing]`, as one snapshot behind one `atomic.Pointer`. A file that fails keeps the old snapshot, as printers.md question 20 has it. Until then, a change needs a restart.
- Each message and each request loads the snapshot once. The subscriber's decision carries an opaque handle to the compiled template, which ntfy hands back to `Handler.Message` untouched, so a reload between the two cannot leave a decision naming a template the snapshot lacks. A webhook's handler takes one value bound to one snapshot, its preset, secret, rules and templates, and uses only that.
- Templates compile with the running `format.timezone` and lay out cards with the running card options, as printers.md question 20 compiles its rules, so `stamp`, `date()` and the cards agree. A reload resets the once-per-run reports, so a template fixed and broken again is reported again.
- Trade-off: this plan adds no reload of its own.
For stage 3:
18. **The `digest` action.** Today a held message prints as soon as the budget has room (ntfy/subscriber.go:616-628), so a message a rule holds would print at once as a digest of one. So a new subscription key, `digest_wait` (default `1h`, 1 minute to 24 hours), sets how long a rule holds them, and rule-held messages are kept apart from those the budget and quiet hours hold.
- The rule's digest prints once its oldest message has waited `digest_wait`, then as the budget and quiet hours allow, as one budgeted receipt.
- Today a waiting digest holds every later message below `bypass_priority`, so that they print in order (ntfy/subscriber.go:518; design.md, "The paper budget is a strict window"). That check counts only the messages the budget and quiet hours hold, so a message no rule matches still prints as today. This narrows the owner's decision that later messages join a waiting digest to the digests the budget and quiet hours make, from stage 3 on.
- The saved state keeps the rule's held messages and when the first came, as new fields of the state file's version 1, which an older binary ignores (ntfy/state.go:22-23), so a restart keeps the wait.
- Trade-off: one more key and a second held set; a budget digest and a rule digest can print close together as two receipts.
For stage 4:
19. **The route, and its rate limit.** The route is `POST /hooks/{name}`, outside `/api/v1`, since a webhook sender sends no bearer token. It is an entry in the route table like any other, with a new flag beside `Auth` and `NoStore` (server/routes.go:34-38; `Hook`, name assumed): no bearer token and `Cache-Control: no-store`. It has its own case in `TestRoutesConform`. Hooks are `[[webhooks.hooks]]`, a list of tables read from the file only, each with a `name` by the subscriptions' rule, `^[a-z0-9][a-z0-9_-]{0,31}$`, unique.
- No per-client limit stands in front of a delivery whose signature passes. GitHub and gitlab.com send every customer's hooks from shared addresses, and `/api/v1`'s limiter counts a request before its token is read (server/server.go:177-187). With it, anyone could point their own hook at `/hooks/forge` and spend the owner's budget with refused deliveries; GitHub never retries the real ones it then refuses.
- Refused requests (`401`, `404` and `415`) count per client in a limiter of their own, at `webserver.rate_limit` per `rate_window` (60 a minute by default, config.go:363-364). A client over it gets `429` before any hashing, which bounds the HMAC work and the log lines.
- An unknown name answers `404` with a new code, `hook_not_found`, before the body is parsed or hashed. It cannot come before the body is read, as formatters.md's item asked: fasthttp reads the whole body, up to `webserver.body_limit`, before any handler runs (Investigation findings, THE REPOSITORY).
- Caddy, as install.sh sets it up, already proxies every path and drops query strings from its log (install.sh:381-421). An operator's own proxy in front of the Docker image must pass `/hooks/` too.
- Trade-off: `404` and `401` tell a stranger which names exist. A name is not a secret; the hook's secret is. Valid deliveries have no rate limit (decision 28).
20. **Authentication.** Every hook has a secret, `secret` or `secret_file`, exactly one, read as the subscriptions' credential files are; a hook without one is a config error. Its `preset` says how the sender proves it holds the secret (Architecture, WEBHOOKS, gives the table): `github`, `gitea` and `forgejo` sign the body with HMAC-SHA256 in hex; `gitlab` and `standard` sign the message ID, a timestamp and the body, in base64, as the Standard Webhooks specification has it; `header` compares a header with the secret.
- The signature is checked on the body's bytes as they came, Fiber's `BodyRaw`, before the body is parsed, and compared with `hmac.Equal`. `header` compares SHA-256 digests of the two in constant time, so the comparison does not tell the secret's length. A missing, malformed or wrong signature answers `401` with a new code, `invalid_signature`, and no detail.
- `gitlab` and `standard` pass over a signature of another version in the header, such as `v1a`, and check every `v1` one it lists. A `whsec_` secret that is not base64, or gives fewer than 24 bytes, is a config error.
- `header` takes `Authorization` or `X-Gitlab-Token` only, and with `Authorization` the secret is the whole value, scheme included, as Gitea and Forgejo send what was typed. Caddy redacts `Authorization` in its access log by default, but not `X-Gitlab-Token`, so install.sh's log filter deletes that header too.
- A secret never goes in the URL, where proxies log it, so no preset reads one from the query.
- `config get` prints no hook: `[[webhooks.hooks]]` is a list of tables, which it refuses (config/value.go:28-30), and a test holds that.
- For `github`, `gitea`, `forgejo` and `header`, a secret is made straight into a 0600 file, `umask 077; uberbringer secret > /etc/uberbringer/hook-forge.secret`, and pasted into the sender's settings from that file. For `gitlab` and `standard`, the sender makes the secret, `whsec_` and 24-64 random bytes in base64, and it is written into the file with an editor, never on a command line. docs/templates.md signs its test request with a script that reads the secret from the file, never with `openssl -hmac` on the command line.
- Trade-off: `header` sends the secret itself on every request, so it is only as safe as TLS to the proxy and the proxy's log.
21. **Bodies and content types.** A hook takes a JSON object only, as on the module routes, sent as `application/json` or a `+json` type in UTF-8, decoded with `UseNumber` and refused with trailing data, as the `ntfy` module refuses it (modules/ntfy.go:54-63). Anything else answers `415` with a new code, `unsupported_media_type`, whose message says to choose JSON in the sender's settings; GitHub and Gitea can send a form instead. So does a `Content-Encoding` other than `identity`, before any hashing: Fiber's `Body` would inflate a compressed body first, and on a broken one return the error's text as the body. None of the senders compresses. A body that is not a JSON object is `400` `invalid_payload`. The body limit is `webserver.body_limit` (4 MiB), applied before routing, by Caddy too.
- Trade-off: a GitHub event larger than 4 MiB (GitHub caps them at 25 MB) is refused unless `body_limit` is raised for the whole server.
22. **Replays and repeats.**
- `gitlab` and `standard` refuse a timestamp more than 5 minutes from the host's clock, `401` `invalid_signature`. The specification leaves the window open. A Raspberry Pi without a clock that boots with the wrong time refuses them until its clock is set; docs/templates.md says to start the daemon after the time is synced.
- A delivery's ID, where its preset has one, becomes the job's reference, with the source `hook:<name>`. An ID longer than 128 bytes, or with a byte that is not visible ASCII, is ignored, and the ID and the header values are copied out of fasthttp's buffers, as the request ID is.
- The ID is reserved under a lock before the rules run, so a second delivery with it, sent while the first is in hand, waits and gets the first's answer. It is recorded with the job's ID after a `202`, and as "nothing printed" after a `204`, so a repeat gets the same answer. After any other answer it is released, so a retry runs again.
- Until job-store stage 1c has shipped, each hook keeps its last 512 IDs in memory. Once it has, hook jobs join its duplicate check (job-store question 10), which runs in `Submit` under the submit lock and replaces the memory for jobs that were queued.
- This leans on job-store question 10's assumed default, which leaves the HTTP routes' jobs out because a client chooses their reference. A hook's ID is read only after its signature passed, which is why hook jobs may join.
- What it covers: a GitHub redelivery keeps its ID, and so do a Standard Webhooks retry and GitLab's retries, so none prints twice. Gitea and Forgejo give each attempt a new ID, a manual replay included, so a replay prints again, as the person replaying asked. GitHub's ID is not signed, so someone who captured a whole request could send it again under a new ID; only `gitlab` and `standard` sign theirs.
- Trade-off: without the job store, a restart forgets the IDs.
23. **Webhook rules.** They are `[[webhooks.rules]]`, shaped as `[[ntfy.rules]]` (decision 12) less `bypass`, seeing decision 5's `json` environment with `hook`, `event`, `delivery` and `headers` set. Actions are `print`, which needs `template`, and `drop`. A hook's own `template` key is what prints when no rule matches; a hook without one prints nothing then. So a hook for one kind of event needs no rule, and `event == "push"` picks Gitea's pushes out of everything else. `template` names a template whose `input` is `json`.
- `headers` holds a list of allowed headers by lowercased name: `content-type`, `user-agent`, and the senders' own `x-github-*`, `x-gitea-*`, `x-gogs-*`, `x-forgejo-*` and `x-gitlab-*` headers and `webhook-id`, less every signature and token header among them. The header a `header` hook compares is never in it, so no template can print a secret. Repeated headers are joined with `, `.
- The rules sit in `[webhooks]` beside the hooks, as printers.md's sit in `[routing]` beside its groups, so a hook can be named anything.
- Trade-off: two places say which template prints.
24. **What a sender is answered.**
- `202` with the job and `Location`, as `/print` answers; `204` when nothing prints: a `drop`, no match, a template that returns `nil`, or an event the preset answers itself after the signature passed, GitHub's `ping`.
- A template that fails on a hook prints a short fallback receipt that quotes nothing of the delivery: the hook, the event, the delivery's ID, the template's name and its position. It answers `202`, logs at WARN and reports once per template per run, as decision 8. GitHub never retries a failed delivery, and GitLab turns a hook off for a while after four failures in a row, so an event the template does not handle, such as a branch deleted with no commits, would otherwise lose that delivery or every later one.
- `400` `invalid_payload`; `401` `invalid_signature`; `404` `hook_not_found`; `413` `body_too_large`; `415` `unsupported_media_type`; `429` `rate_limited`; `503` `queue_full` or `shutting_down`. A repeat gets the first delivery's answer (decision 22).
- Nothing waits for the printer, so an answer takes as long as the template's run, which decision 6's budget bounds: well inside GitHub's 10-second limit.
- Trade-off: a broken template prints a fallback for each delivery until it is fixed. GitHub does not retry, so a `503` there is lost unless someone redelivers it.
25. **Token scopes.** No new claim is added. A template is a module, so a `mod` claim names it (decision 4). A hook takes no bearer token: its secret is its scope, and opens that hook alone. Agent tokens (docs/plans/remote-printers.md decision 6) are bearer tokens and open nothing here.
- Trade-off: a sender that can send a bearer token but cannot sign uses the template's module route, not `/hooks`.
26. **Presets for common senders.** The signature presets of decision 20 ship, each tested against its sender's documented scheme, GitHub's test values included. No template ships: docs/templates.md shows one for a Gitea push, the owner's own forge.
- Trade-off: everyone writes their own template.
27. **Privacy.** A webhook's body and headers are print contents. They never reach logs, Sentry, job status or an error answer, and neither does a template's output. The request line logs the path, so the hook's name, as it does for module names. A refused signature is a refusal, logged by the request line only and never sent to Sentry.
- Trade-off: a sender whose signatures fail shows only `401` lines; `uberbringer rules hook` (stage 4) does not check signatures, so a mismatched secret is found by comparing it by hand.
28. **A hook's paper budget and quiet hours.** A hook has neither. It prints at once, as `/print` does; `drop` rules on `event` or `body` thin it out.
- Trade-off: a sender that floods with valid deliveries prints every one, and nothing slows it but the rules, since decision 19 puts no limit in front of a valid signature.
29. **Where it is documented.** On a new page, docs/templates.md: templates, their environments and forms, ntfy rules, webhooks and their presets, with the Gitea example. docs/configuration.md lists the keys and points there; docs/api.md gets `/hooks/{name}`, the new codes and templates under Modules. README's documentation table, CLAUDE.md's "Read first" and `.goreleaser.yaml`'s archive files list the new page.
- Trade-off: one more page in the release archives.
## Investigation findings
Research ran on 2026-12-01: the repository at 8b9e838, Kanrisha's `internal/policy`, Expr's source at v1.18.1, fasthttp and Fiber from the module cache, and each webhook sender's own documents. Two independent reviews then checked the draft against the code, one for its engineering and one against the owner's rules; one ran a probe against Expr v1.17.8 from the module cache. Nothing contacted the printer, no `config.toml` was read, and nothing was built in the repository.
EXPR
- proxy.golang.org gives v1.18.1 (2026-11-22) as the latest release, as printers.md found. Its advisories and size are in printers.md's findings.
- Defaults at v1.18.1 (`conf/config.go`): a node limit of 10,000 (`MaxNodes`, 0 turns it off) and a memory budget of 1,000,000 per run, which a `vm.VM` can set per run. Running out is an error, not a panic. The budget is charged for ranges, arrays, maps and sorts the run makes, not for passes over a list it already has (`vm/vm.go`).
- The VM takes no context and counts no steps (`vm/vm.go`). `WithContext` passes a context to functions that take one, which is what decision 6's guard uses.
- `DisableBuiltin("$env")` works at v1.18.1, whose checker reads the disabled set; at v1.17.8 it does nothing.
- `string()` formats with `%v` (`builtin/lib.go`), so a float prints as `1.234567e+06`. The probe also gave `invalid operation: int(s3cr3t-value)` for a runtime error, quoting the env.
- Builtins include `map`, `filter`, `concat`, `flatten`, `take`, `join`, `split`, `trim`, `trimPrefix`, `upper`, `fromJSON`, `toJSON`, `fromPairs`, `date`, `duration`, `timezone` and `now` (`builtin/builtin.go`). A map literal's key may be a bare name, so `{type: "text", text: title}` parses, or an expression in brackets, so a key can come from the payload (`parser/parser.go`, `parseMapExpression`). `let` and `if`/`else` exist, as do `?.` and `??` for missing fields.
KANRISHA
- Rules return a bool and carry an `Action` from a fixed list, with typed `ActionParams` whose keys are checked by reflection over their JSON tags (policy.go:22-179). `delete` is a recognised action that no rule may be created with, so a dangerous action needs a person (policy.go:65-82).
- The engine itself is as printers.md's findings describe. Its runtime error log quotes Expr's message (engine.go:236-245), which this plan does not copy.
THE REPOSITORY
- A module turns a body into a `receipt.Job` (modules/registry.go:72-87). The module routes answer `204` for `ErrSkip` and `422` `module_failed` for an invalid built job, with the problems' text (server/handlers_modules.go:90-118). They never call `checkRaw`, which only `/print` does.
- The subscriber's order (ntfy/subscriber.go:497-534): skip by `min_priority`; skip an update if `updates = "skip"`; quiet hours drop or hold; the budget holds unless `bypass_priority`, and so does a digest already waiting (line 518); then `Handler.Message`. An error from the handler stops reading and offers the message again. Held messages print as soon as the budget has room, or when quiet hours end (ntfy/subscriber.go:616-628). A digest row is a message's title, or its text's first line cut to 256 bytes (ntfy/ratelimit.go:113-139).
- internal/app turns a message into a card and submits it; a card that fails validation is logged, reported and dropped (internal/app/uberbringer/ntfy.go:165-206).
- `checkRaw` walks top-level elements only (server/auth.go:135-150), so a job built elsewhere must refuse `raw` itself.
- Routes under `/api/v1` sit behind the limiter and the bearer token in one group (server/server.go:177-187); the table registers them (server/routes.go:329-351).
- fasthttp reads a request's whole body before any handler, up to the body limit, unless `StreamRequestBody` is set (fasthttp v1.80.0, server.go:2762-2767). The server does not set it (server/server.go:151-162), and Fiber v3.7.0 already uses fasthttp's `HeaderReceived` hook itself (app.go:1949). Fiber's `Body` inflates a compressed body and returns a decoding error's text in its place (req.go:189-240); `BodyRaw` does not.
- `config get` refuses `api.secret` by name before it loads (internal/app/uberbringer/cli.go:103), refuses a list of tables (config/value.go:28-30), and prints any other map with `fmt.Sprint` (value.go:42-43). Each request is logged with its path, never its query or body (docs/configuration.md:214-216).
- `uberbringer token` checks `--modules` names against the built-in modules before it reads the config (internal/app/uberbringer/cli.go:156-161).
WEBHOOK SENDERS
| Sender | Signature | Signed | Delivery ID | A redelivery | Types |
|---|---|---|---|---|---|
| GitHub | `X-Hub-Signature-256: sha256=<hex>`, HMAC-SHA256 | the body | `X-GitHub-Delivery`, unsigned | keeps the ID | JSON or form |
| Gitea | `X-Gitea-Signature: <hex>`, HMAC-SHA256; also `X-Hub-Signature-256` and `X-Gogs-Signature` | the JSON payload: the body, or a form's `payload` field | `X-Gitea-Delivery`, per attempt; also `X-GitHub-Delivery` | a new ID | JSON or form (`payload`) |
| Forgejo | `X-Forgejo-Signature: <hex>`, HMAC-SHA256 | the body | `X-Forgejo-Delivery` | not checked | JSON or form |
| GitLab 19.1+ | `webhook-signature: v1,<base64>`, HMAC-SHA256 | ID, timestamp and body | `webhook-id` | keeps the ID | JSON |
| GitLab, older | `X-Gitlab-Token`, the secret itself | nothing | `X-Gitlab-Event-UUID` | not checked | JSON |
| Standard Webhooks | `webhook-signature: v1,<base64>` | `id.timestamp.body` | `webhook-id` | keeps the ID; new timestamp | any, JSON advised |
- GitHub sends the SHA-1 `X-Hub-Signature` too, for legacy use, and gives a secret, a payload and the signature they must give, which the tests use. It caps payloads at 25 MB, counts an answer slower than 10 s as failed, and never retries a failed delivery by itself. Its best-practice page advises `X-GitHub-Delivery` against replays.
- Gitea's replay creates a new task with a new UUID (models/webhook/hooktask.go:121-122 and 153-170 at v28.4.0, its latest release). It signs the payload it stores, whether it sends it as the body or in a form's `payload` field (services/webhook/deliver.go:39-100 at v28.4.0). Gitea and Forgejo can also send a configured `Authorization` header with every delivery.
- GitLab's signing token came in 19.0 behind a flag and is generally available in 19.1. It keeps `webhook-id` and `Idempotency-Key` across retries, and disables a hook for a while after four failures in a row. Its docs call the plain `X-Gitlab-Token` not recommended for new hooks.
- Standard Webhooks 1.0.0: the secret is 24-64 random bytes, base64-encoded after `whsec_`; the signature header may hold several, space-separated, for key rotation, and `v1a` is a deprecated version; the timestamp must be within a tolerance the specification leaves open.
- Caddy's access log redacts `Cookie`, `Set-Cookie`, `Authorization` and `Proxy-Authorization` and logs every other request header as sent.
WHERE THE FINDINGS ARE UNSURE
- Forgejo's headers: its docs' example only, not its source.
- GitLab's `Content-Type`; whether `webhook-timestamp` stays the same across its retries; and whether its signing token takes the `whsec_` form: its docs do not say.
- Gitea's own retry rules: not read.
- Expr v1.18.1 was read on GitHub, not built; the probe ran v1.17.8, and the example templates were not compiled. Stage 1's tests check them, and its first step checks that decision 6's guard can wrap every predicate.
- How long a nested predicate over a large webhook body runs: not measured.
SOURCES
- Expr: https://proxy.golang.org/github.com/expr-lang/expr/@latest; at tag v1.18.1, `expr.go`, `conf/config.go`, `vm/vm.go`, `builtin/builtin.go`, `builtin/lib.go`, `checker/checker.go` and `parser/parser.go` under https://github.com/expr-lang/expr.
- Kanrisha: `internal/policy/engine.go` and `policy.go`.
- fasthttp v1.80.0 and Fiber v3.7.0, from the module cache.
- GitHub: https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries, https://docs.github.com/en/webhooks/webhook-events-and-payloads, https://docs.github.com/en/webhooks/using-webhooks/best-practices-for-using-webhooks, https://docs.github.com/en/webhooks/using-webhooks/handling-failed-webhook-deliveries.
- Gitea: https://docs.gitea.com/usage/webhooks; at tag v28.4.0, https://github.com/go-gitea/gitea/blob/v28.4.0/services/webhook/deliver.go and https://github.com/go-gitea/gitea/blob/v28.4.0/models/webhook/hooktask.go.
- Forgejo: https://forgejo.org/docs/latest/user/webhooks/.
- GitLab: https://docs.gitlab.com/user/project/integrations/webhooks/.
- Standard Webhooks: https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md.
- Caddy: https://caddyserver.com/docs/caddyfile/options, `log_credentials`.
## Overview
WHAT SHIPS WHEN
1. Stage 1: templates in Expr, `card` and `elements`, each a module with its routes, checked on its sample at load, and `uberbringer template`.
2. Stage 2: `[[ntfy.rules]]`, which print a message through a template, as today's card, or drop it.
3. Stage 3: the `digest` action and `digest_wait`.
4. Stage 4: webhooks at `/hooks/{name}`, with signature presets, `[[webhooks.rules]]` and repeats answered once.
COMPATIBILITY
- Nothing breaks. Every key, route and code is new, and a config without `[[templates]]`, `[[ntfy.rules]]` or `[webhooks]` behaves as today. The CHANGELOG lists each user-visible commit under Added.
- `GET /api/v1/modules` lists the templates with the built-in modules, sorted by name as today.
- A downgrade refuses the new sections as unknown keys. After stage 3 it keeps the ntfy state: an older binary ignores the new fields, and the messages a rule held are lost.
- What prints does not change: no block or card code changes, so TestRenderCompat and TestPaperReceipts keep passing.
INVARIANTS
1. Nothing reaches the printer unless the whole receipt rendered. A template builds a `receipt.Job`, which is validated, queued and rendered in full before it is sent, as every job is.
2. A template never sends printer commands. Its output takes the strict decoder; `raw` and `hex` are refused on the decoded job, wherever they stand; text is transcoded and stripped of control characters when it renders.
3. Print contents never reach logs, Sentry, job status or an error answer: not an ntfy message, a webhook's body or headers, a template's environment or output, nor Expr's or the JSON decoder's messages, which quote them. Logs give names and positions.
4. Expr reads nothing outside its environment: no clock, no variables, no I/O. `now` is injected. A run is bounded in nodes, memory and iterations.
5. A webhook's signature is checked on the body's bytes as they came, before the body is parsed, in constant time. A hook without a secret does not start.
6. Each message and each request uses one snapshot of templates, rules and hooks, from the decision to the job.
7. printqueue, server and config never import Expr (printers.md invariant 9), and ntfy imports neither modules, templates nor Expr.
8. A template that fails never loses an ntfy message: the message prints as today's card. A template's job is previewed before it is queued and its images are optional, so in the worker it can fail only as any job can, at the printer.
## Architecture
PACKAGES
- `internal/pkg/rules` (printers.md): stage 1 adds `Options(zone)`, the compile options both share, and the iteration guard (decision 6); stage 2 adds the engine if printers stage 2a has not (decision 1). It imports only Expr.
- `internal/pkg/templates` (new, stage 1): `Template` (name, input, form, compiled program), `Compile`, `Run(env) (receipt.Job, error)` with decision 7's checks, the environments and their decoding, the helper functions, the `card` form's mapping onto `modules.Notice`, and `Module`, which wraps a template as a `modules.Module`. Imports: Expr, rules, modules, receipt.
- `internal/pkg/modules` gains `TemplateError` (name assumed): a template's name, the line and column, and the paths of its output's problems, never a message. templates returns it, and server matches it without importing templates.
- `internal/pkg/hooks` (new, stage 4): the presets, `Verify(preset, secret, header, body, now)`, the delivery ID, the event and the allowed headers. Pure functions on bytes and headers: no Fiber, no Expr.
- server gains the `/hooks/{name}` handler, which verifies with `hooks` and passes the request to a `Hooks` interface that internal/app implements with templates and rules, so server never imports templates or Expr. Template modules reach server through the existing `Modules` interface, whose registry internal/app gives from the snapshot.
- internal/app builds the snapshot, wires the subscriber's decision function, and implements `Hooks`.
- Imports: templates → rules, modules, receipt; hooks → nothing of ours; server → hooks; internal/app → templates, hooks, rules. CLAUDE.md's list gains them, and a test holds that server, printqueue and config do not depend on Expr (`go list -deps`).
THE ENVIRONMENTS (decisions 5, 12 and 23)
| Variable | Type | Input | Value |
|---|---|---|---|
| `body` | any | json | the decoded object: maps, lists, strings, whole numbers as ints, other numbers as floats, bools and nil |
| `hook` | string | json | the hook's name (stage 4); else empty |
| `event` | string | json | the preset's event header, such as `push` (stage 4); else empty |
| `delivery` | string | json | the delivery's ID (stage 4); else empty |
| `headers` | map | json | the allowed headers by lowercased name (decision 23; stage 4); else empty |
| `subscription` | string | ntfy | the subscription's name; empty on a module route |
| `id`, `topic`, `title`, `message` | string | ntfy | the message's |
| `markdown` | bool | ntfy | the message is markdown |
| `priority` | int | ntfy | 1-5, 3 when it has none |
| `tags` | list | ntfy | its tags |
| `time` | time | ntfy | when ntfy received it |
| `links` | list | ntfy | the click URL and view actions, each `{label, url}` |
| `attachment` | map or nil | ntfy | `{name, type, size, url}` |
| `updated` | bool | ntfy | an earlier message of its sequence printed, with `updates = "mark"` (subscriber only) |
| `now` | time | both | when the payload was received, in `format.timezone` |
A template on `/api/v1/print/<name>` sees the hook fields empty, so one written for a hook can be tried there.
TEMPLATES IN THE CONFIG (stage 1)
```toml
[[templates]]
name = "gitea-push"
description = "A Gitea push: the repository, the branch and each commit"
input = "json"
form = "elements"
expr = '''
let commits = take(body.commits ?? [], 20);
concat(
[{type: "box", title: cut(body.repository.full_name, 40), children: [
{type: "kv", pairs: [
{key: "Branch", value: trimPrefix(body.ref, "refs/heads/")},
{key: "By", value: body.pusher.login}]}]}],
len(commits) == 0 ? [] :
[{type: "list", items: map(commits, cut(split(.message, "\n")[0], 200))}]
)
'''
sample = '''
{"ref": "refs/heads/main", "repository": {"full_name": "owner/uberbringer"},
"pusher": {"login": "owner"}, "commits": [{"message": "Feed blank lines before the cut"}]}
'''
[[templates]]
name = "shop-order"
description = "An order sent as JSON in an ntfy message"
input = "ntfy"
form = "card"
expr = '''
let order = fromJSON(message);
{title: "Order " + string(order.number), priority: priority, tags: tags,
message: join(map(order.lines, string(.qty) + " x " + .name), "\n")}
'''
sample = '''{"topic": "shop", "priority": 4, "message": "{\"number\": 42, \"lines\": [{\"qty\": 2, \"name\": \"Flat white\"}]}"}'''
```
- The names, fields and values are examples, checked against the language when stage 1 tests them.
- Each entry is checked by the loader like a subscription: an unknown key is an error, `input` and `form` are enums, and `name`, `expr` and `sample` are required.
NTFY RULES (stages 2 and 3)
```toml
[[ntfy.rules]]
name = "orders"
order = 10
when = 'subscription == "shop" && "order" in tags'
action = "print"
template = "shop-order"
bypass = true
[[ntfy.rules]]
name = "no-tests"
order = 20
when = 'title startsWith "[test]"'
action = "drop"
[[ntfy.rules]]
name = "stars-later"
order = 30
when = 'topic == "forge" && "star" in tags'
action = "digest"
```
- The subscriber gains `Options.Decide` (name assumed), a function internal/app gives it. It returns the action, `bypass`, the rule's name and an opaque handle to the compiled template, which ntfy hands back to `Handler.Message` untouched, so ntfy imports nothing new. A nil `Decide` keeps today's behaviour.
- In `deliver`, `Decide` runs after the `min_priority` and updates checks (decision 13). A `digest` holds the message in the rule's own held set (stage 3).
- internal/app's `Message` runs the template, or prints the card when it fails (decision 15), then submits as today.
WEBHOOKS (stage 4)
```toml
[[webhooks.hooks]]
name = "forge"
preset = "gitea"
secret_file = "/etc/uberbringer/hook-forge.secret"
template = "gitea-push"
[[webhooks.rules]]
name = "pushes-to-main-only"
order = 10
when = 'hook == "forge" && event == "push" && body.ref != "refs/heads/main"'
action = "drop"
```
| Preset | Header checked | Signed | Event | Delivery ID |
|---|---|---|---|---|
| `github` | `X-Hub-Signature-256`, `sha256=` and hex | the body | `X-GitHub-Event` | `X-GitHub-Delivery` |
| `gitea` | `X-Gitea-Signature`, hex | the body | `X-Gitea-Event` | `X-Gitea-Delivery` |
| `forgejo` | `X-Forgejo-Signature`, hex | the body | `X-Forgejo-Event` | `X-Forgejo-Delivery` |
| `gitlab` | `webhook-signature`, `v1,` and base64 | `webhook-id`, `webhook-timestamp` and the body | `X-Gitlab-Event` | `webhook-id` |
| `standard` | `webhook-signature`, `v1,` and base64 | the same | none | `webhook-id` |
| `header` | `Authorization` or `X-Gitlab-Token`, equal to the secret | nothing | none | none |
A request runs in this order:
1. The name (`404`). A client over its count of refused requests gets `429` first (decision 19).
2. The content type and `Content-Encoding` (`415`).
3. The signature on `BodyRaw`, and the timestamp (`401`).
4. The delivery ID: reserved, or a repeat answered with the first delivery's answer (decision 22).
5. A preset's own event, such as `ping` (`204`).
6. The body as a JSON object (`400`).
7. The snapshot's rules, first match, then the hook's `template` (`204` for nothing).
8. The template; a failure prints the fallback receipt (decision 24).
9. The job's preview and `Submit`, with the source `hook:<name>` and the delivery's ID as its reference (`202`, `503`).
LOGGING AND PRIVACY
- A template's failure: one WARN line with the template's name, its position and the source (`module:<name>`, `ntfy:<subscription>` or `hook:<name>`), reported once per template per run (decisions 8, 15 and 24). A run past 1 s: one WARN line with the name, from a timer (decision 6).
- A rule's runtime error: a WARN line with the rule's name and position, at most once a minute per rule (decision 14). A drop: one DEBUG line with the rule's name and the message's or delivery's ID.
- Hooks: the request line, with the path, as for every request. Never a header or the body. install.sh's Caddy log leaves out `X-Gitlab-Token` (decision 20).
- The env, the output and Expr's runtime messages reach the terminal only, through `uberbringer template` and `uberbringer rules`.
## Phases
Every commit below that changes behaviour carries its own tests, docs, regenerated docs/swagger.json where a route or type changes, and its own CHANGELOG entry under Added. A stage's last commit marks the stage built in the Status line.
### Stage 1: Templates, served as modules
**Goal.** Templates written in Expr, in the `card` and `elements` forms, each served as a module and checked on its sample at load. Decisions 1-11.
**Work.**
go.mod
- Expr at its latest stable release, unless printers stage 2a has added it; govulncheck. The licence notices are regenerated in the commit that first links Expr into the binary (commit 3).
internal/pkg/rules
- options.go: `Options(zone)` and the iteration guard (decision 6). Its first step checks, on v1.18.1, that the guard wraps every predicate builtin and `in`, and that a nested predicate is charged on each pass.
internal/pkg/modules
- `TemplateError` (decision 8).
internal/pkg/templates (new)
- template.go: `Template`, `Compile` and `Run`, with decision 7's checks, the walker, forced `optional` images and the timer.
- env.go: the `json` and `ntfy` environments, without stage 4's fields; the body decoded with `UseNumber`; `fromJSON`, `cut` and `stamp`.
- card.go: the `card` form onto `modules.Notice`, decoded strictly.
- module.go: `Module`, a template as a `modules.Module`.
internal/pkg/config
- `Templates []TemplateConfig` (`templates`), a list of tables read from the file only, each entry from its defaults as a subscription's is; validation of names, enums and required keys. No Expr. The names of any `UBERBRINGER_TEMPLATES_*` variables, for the WARN.
internal/app/uberbringer
- load.go (new, unless printers stage 1a has added it; name assumed): compile every template and run it on its sample (decision 9), at start, in `config get` and in `preview`.
- modules.go: the registry gains the templates; a name clash is a config error.
- cli.go: `uberbringer token` reads the config, builds the registry with its templates, then checks `--modules`.
- serve.go: the WARN for `UBERBRINGER_TEMPLATES_*` variables; each built job is previewed before `Submit` (decision 7).
- template.go (new): `uberbringer template` (decision 10).
internal/app/uberbringer/server
- errors.go: `template_failed`; handlers_modules.go answers it for a `*modules.TemplateError`, with the name and position.
Docs
- docs/templates.md (new): templates, their forms, environments, numbers, limits and helpers, the module routes, and the Gitea example.
- docs/configuration.md: § templates, pointing to docs/templates.md; § Environment variables, `[[templates]]` among the sections with no variable. configs/config.example.toml: a commented template.
- docs/api.md: Modules says templates are modules; `template_failed` in the errors table. docs/swagger.json regenerated.
- docs/cli.md: `uberbringer template`; `config get` and `preview` fail on a broken template; `token --modules` takes a template's name.
- docs/security.md: templates never produce raw ESC/POS; a `mod` token can be limited to one template; the module list shows every template to any token; § What is never logged, a template's environment, output and Expr's messages.
- docs/development.md § Package layout: `internal/pkg/templates`, and `internal/pkg/rules` if this stage adds it.
- docs/docker.md: templates come from the file only, so a container that uses them mounts a config.
- README: the feature list and the documentation table. CLAUDE.md: "Read first", the layout and the imports. `.goreleaser.yaml`: docs/templates.md in the archives.
- design.md: a decision "Templates build ordinary jobs", beside "Modules build ordinary jobs"; the stack choices, with Expr's version and size, unless printers stage 2a has recorded them, and `[[templates]]` with no variable.
**Tests.**
internal/pkg/rules
- The guard: a nested predicate over two lists of 2,000 fails with the budget spent; `in` on a list inside a predicate is charged; a template within the budget runs unchanged.
internal/pkg/templates
- Compile: a syntax error, an unknown name, `now()` and `$env` refused, with positions; the node limit.
- Run: each form on its sample; a nil field through `?.` and `??`; `nil` returned; `cut` and `stamp`; `now` injected, in a zone with clock changes; 1234567 and a 64-bit ID print whole, from `body` and from `fromJSON`.
- Refused output: `raw` at the top and in a box; `hex`, `HEX` and `Hex` on a `text`; an unknown key; a wrong type; a text field over 4,096 bytes; a result over 256 KiB; the memory budget spent. Each is a `*modules.TemplateError` with a position or path and no payload text.
- An image is made `optional`; a result over `format.max_lines` fails before it is queued.
- A sentinel string in the payload, used as a value and as a map key, never appears in an error's text.
- The walker places every string field of `Element`.
- `Run` from 100 goroutines under `-race`.
- A fuzz target over the output path: any Expr value (maps, lists, strings, numbers, keys in any letter case) through the encoding, decoding, checks and walker never panics, never yields an accepted job with `raw` or `hex`, and never puts its input in an error's text.
- The job each example template builds from its sample is pinned as a JSON golden.
internal/pkg/config
- `[[templates]]`: names by pattern and unique; unknown keys; enums; required keys; no variable; a `UBERBRINGER_TEMPLATES_*` variable named for the WARN.
internal/app/uberbringer
- A template that fails to compile, or fails on its sample, fails the start and `config get`, naming it; the sample's failure gives no data. `config get templates` prints nothing.
- A template named like a built-in module is refused.
- `uberbringer token --modules gitea-push` gives a token whose `mod` claim names it; an unknown name still fails.
- `uberbringer template`: golden outputs for the examples, and Expr's full message for a failing payload.
- server, printqueue and config do not depend on Expr.
internal/app/uberbringer/server
- `/api/v1/print/<template>`, `/api/v1/preview/<template>` and `GET /api/v1/modules`; a `mod` token for one template; `template_failed` with no payload text in the answer or the logs; schema_test holds the new code.
**Commits.**
1. Add the compile options shared by Expr rules and templates
2. Add Expr templates that build receipts
3. Serve each template as a module
4. Add the template command
Commit 1 carries the Expr dependency in go.mod and go.sum, unless printers stage 2a added it; nothing links it yet, so the licence notices do not change. If printers stage 2a has shipped with its options inline, commit 1 is "Share the Expr compile options with templates", with no change in behaviour. Commit 2 is library code with its tests. Commit 3 is the first user-visible change: the config, the check at load, the module routes, `token --modules`, the regenerated licence notices and the size Expr adds. Its load error names the template and position only. Commit 4 adds `uberbringer template` and the pointer to it in that error.
**Done when.**
- The full gate passes; govulncheck is clean; the snapshot builds, and the size Expr adds is recorded if this stage added it.
- Paper, with the owner's OK: the Gitea example's sample, sent to `/api/v1/print/gitea-push` with the token in a curl header file (`-H @file`), never on the command line. Look at the box and its title, the key-value rows, the list's line breaks and the cut. Judge by the paper and `/healthz`, never by a log line or the `202`. Wait for the owner's report. Once the owner passes it, its job joins receipt's testdata/paper and its bytes are pinned in TestPaperReceipts as `template-gitea-push.hex`, folded into commit 3.
### Stage 2: Rules for ntfy messages
**Goal.** `[[ntfy.rules]]` print a subscription's messages through a template, as today's card, or drop them. Decisions 12-17.
**Work.**
- internal/pkg/rules: the engine, if printers stage 2a has not built it (decision 1).
- internal/pkg/ntfy: `Options.Decide` and the decision with its opaque handle; `deliver` runs it after the updates check; `bypass` skips the budget; `Handler.Message` takes the decision; `drop` logs at DEBUG; a panic in `Decide` is recovered.
- internal/pkg/config: `[[ntfy.rules]]`, each entry from a default with `enabled` true; validation of names, `order`, actions (`digest` refused until stage 3), `bypass` on `print` only, and `template` against `ntfy` templates.
- internal/app/uberbringer: compile the rules against the `ntfy` environment at load; `Decide` from the snapshot; `Message` runs the template or prints the card (decision 15), with panics recovered; `uberbringer rules ntfy <subscription> [message.json|-]` (name assumed) prints the environment, each rule's result and the decision, then the preview.
- Docs: docs/templates.md § ntfy rules, `bypass` and the digest rows of held messages; docs/ntfy.md, the order of the checks and a pointer there; docs/configuration.md, § ntfy and § Environment variables, and the example config; docs/cli.md; docs/security.md § What is never logged, a rule's environment; README's feature list; design.md, the subscriptions' decision gains the rules, and `[[ntfy.rules]]` has no variable.
**Tests.**
- The order: a `drop` spends no budget; a `print` still waits in quiet hours and counts in the budget; a `bypass` rule skips the budget but not `quiet.min_priority`; `updates = "skip"` skips an update before any rule.
- A rule failing at run time: the next rule decides, one WARN line with the position and no message text, at most once a minute.
- A template failing on a message, or panicking: the card prints, one WARN or ERROR line, one report per template per run.
- A template returning `nil` prints nothing.
- A held message prints as a digest row, not through its template.
- A reload between `Decide` and `Message`, simulated by swapping the snapshot, still prints through the template `Decide` chose.
- A sentinel title, message and tag sent through a printed, dropped, failing and held message: no log line, Sentry event or job status holds it.
- The synctest soak (design.md, "The subscriber is tested on a virtual clock") runs with rules that print, drop, bypass and fail.
**Commits.**
1. Add the Expr rules engine
2. Let the subscriber's caller decide how each message prints
3. Print or drop ntfy messages by rules
4. Add the ntfy rules dry-run
Commit 1 only if printers stage 2a has not built the engine. Commit 2 is ntfy's `Options.Decide`, nil keeping today's behaviour, with its tests; nothing a user sees changes, so it has no docs or CHANGELOG entry.
**Done when.**
- The full gate passes.
- Paper, with the owner's OK: one ntfy message through the `shop-order` example, published to a test topic. Look at the title, the order lines and their wrapping, the priority's form and the cut. Judge by the paper and `/healthz`, never by a log line. Wait for the owner's report, then pin its bytes as `template-shop-order.hex`, folded into commit 3.
### Stage 3: The `digest` action
**Goal.** A rule holds a message for a digest of its own, which prints once the oldest has waited `digest_wait`. Decision 18.
**Work.**
- internal/pkg/ntfy: a held set for rule-held messages, apart from the budget's, with the time its first message came; `flushAt` waits for `digest_wait` for it; the check that holds later messages behind a waiting digest counts the budget's set only; the state file keeps the new set as new fields of version 1.
- internal/pkg/config: `digest_wait` per subscription, its default and range; `digest` allowed in `[[ntfy.rules]]`.
- Docs: docs/templates.md, docs/ntfy.md, docs/configuration.md and the example config; design.md's paper budget decision, as decision 18 amends it.
**Tests.**
- On the virtual clock: a rule-held message prints on a digest after `digest_wait`, not at once; an ordinary message after it prints at once as its own card; a budget digest and a rule digest each print; quiet hours still hold the rule's digest; a restart keeps the wait; a state file without the new fields loads as today.
**Commits.**
1. Hold ntfy messages for a digest by rule
**Done when.**
- The full gate passes. Nothing new prints: a rule's digest is laid out as today's digest.
### Stage 4: Webhooks
**Goal.** `POST /hooks/{name}` takes a signed delivery from a forge or any Standard Webhooks sender and prints it through a template. Decisions 19-29.
**Work.**
- internal/pkg/hooks (new): the presets, `Verify`, the delivery ID and its form check, the event and the allowed headers (Architecture, WEBHOOKS).
- internal/pkg/templates: the `json` environment's stage 4 fields.
- internal/pkg/config: `[[webhooks.hooks]]` (`name`, `preset`, `secret`, `secret_file`, `header`, `template`) and `[[webhooks.rules]]`; validation, file only, a `whsec_` secret's form; the names of any `UBERBRINGER_WEBHOOKS_*` variables, for the WARN.
- internal/app/uberbringer/server:
- routes.go: the `Hook` flag; `registerRoutes` registers it outside `BasePath` with `noStore` and the limiter of refused requests; `DocumentedErrors` adds `rate_limited` for it; the signature, timestamp, event and delivery headers as header `Params`.
- the handler, in the order under Architecture, WEBHOOKS, on `BodyRaw`; the repeat check (decision 22), job-store's when it has shipped.
- errors.go: `hook_not_found`, `invalid_signature` and `unsupported_media_type`.
- the `Hooks` interface, whose lookup gives one value bound to one snapshot.
- tools/genopenapi: a `Hook` route has no bearer security.
- internal/app/uberbringer: the hooks into the snapshot, secrets read at load; `Hooks`; the fallback receipt (decision 24); `uberbringer rules hook <name> [--headers file] [body.json|-]` (name assumed), which skips the signature and reads headers from a file, one `Name: value` a line, leaving out the signature and secret headers, so that none goes on the command line.
- install.sh: Caddy's log filter deletes the `X-Gitlab-Token` request header.
- printqueue: `Status.Source`'s doc comment names `hook:<name>`, so docs/swagger.json changes for it.
- Docs:
- docs/templates.md § webhooks: each preset and its sender's settings; making a secret into a file; a test request signed by a script that reads the secret from the file; the clock on a Pi.
- docs/api.md: the route table, the route and its answers, the new codes, the opening paragraph (a hook proves itself by its signature, not a token), the no-store sentence, and the job source `hook:<name>` with the delivery's ID as its reference. docs/swagger.json regenerated.
- docs/security.md: hook secrets, what each preset proves, replays, the proxy's log, and § What is never logged, webhook bodies and headers.
- docs/configuration.md: § webhooks and § Environment variables; § Logs, the source `hook:<name>`. configs/config.example.toml.
- docs/cli.md: `uberbringer rules hook`, and never a secret in `--headers`' file.
- docs/docker.md: a hook's `secret_file` mounted read-only, owned by 10001, mode 600, as token files are; an operator's own proxy passes `/hooks/` and keeps `X-Gitlab-Token` out of its log.
- docs/install.md: the Caddy log filter.
- docs/development.md § Package layout: `internal/pkg/hooks`.
- README's feature list. CLAUDE.md's layout and imports.
- design.md: a decision for webhooks; "Jobs remember their source" names `hook:<name>` and the delivery's ID; `[webhooks]` has no variable.
**Tests.**
internal/pkg/hooks
- Each preset against its documented scheme: GitHub's test values; a Gitea and a Forgejo signature made by the test; a Standard Webhooks message signed with a `whsec_` secret; several signatures in one header, a `v1a` one passed over; a stale timestamp; a wrong, missing or malformed signature; `header` with `Authorization` and with `X-Gitlab-Token`; a delivery ID that fails its form check.
- The allowed headers leave out every signature, token and `header` secret.
- A fuzz target: any headers and body never panic.
internal/app/uberbringer/server
- TestRoutesConform's case for `/hooks/{name}`; TestRegisteredRoutesAreTheTable with it; the generated document gives it no bearer security.
- An unknown name answers `404` without hashing the body, seen through a counting `Verify` given to the server; a form body, and a gzip body, `415`, nothing inflated; a bad signature `401`; a client past its refused count `429`, while a valid delivery from it still prints.
- Repeats: two concurrent deliveries with one ID give one job; a repeat after a `202` gets the same job, after a `204` the `204`, after a `503` a new attempt.
- `ping` answers `204`; a `drop` and no match `204`; a template failure prints the fallback receipt, with no body text, and answers `202`; `queue_full` `503`.
- A reload between the signature check and the template, simulated, uses one snapshot.
- A sentinel in the body and in a header: no log line, Sentry event, job status or answer holds it.
- schema_test holds the new codes.
internal/pkg/config
- `[[webhooks.hooks]]`: a hook without a secret, with both kinds, with an unknown preset, a `header` other than the two, a bad `whsec_` secret, a repeated name, or a `template` whose input is not `json`, is refused. `config get webhooks.hooks` prints nothing.
**Commits.**
1. Add webhook signature checks for common senders
2. Print signed webhooks through templates
3. Answer a repeated webhook delivery once
4. Add the webhook rules dry-run
Commit 1 is library code with its tests. Commit 2 also carries install.sh's log filter, since the `header` preset needs it.
**Done when.**
- The full gate passes; the snapshot builds, since install.sh changed.
- Paper, with the owner's OK: one test delivery from the owner's Gitea to a hook behind Caddy, through the `gitea-push` example. Look at the repository, the branch, the commit lines and the cut. Judge by what printed, the job's status and `/healthz`, never by a log line or the `202`. Wait for the owner's report.