Add the notify and ntfy modules and scoped tokens
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m57s

Breaking: a job with a raw element prints only with a token issued with
uberbringer token --raw. Every other token, every existing one included,
gets 403 token_scope for it, with the raw elements in details, and keeps
every other route.

The notify module prints a notification card from a title, message,
priority and tags, with topic, click, up to three actions, image,
markdown and time as options; it decodes strictly and refuses a payload
over its length caps. The ntfy module takes one ntfy message as ntfy
sends it, such as the ntfy client's $NTFY_RAW, ignores fields it does
not know, cuts text over the caps, and answers 204 for other events and
binary bodies. Both print every message plain: one message cannot tell
the first of a sequence from a replacement, since a publisher may choose
the sequence ID. internal/pkg/ntfy holds ntfy's message types.

Both print the same card. The priority picks the form: a dark URGENT
rule and a double box, a double box headed HIGH, a single box with the
title in its border, or a rule with no box. Tags print as markers in
front of the title, the rest on a Tags row; links print as QR codes with
their labels; attached PNG, JPEG, GIF and WebP images print after the
card. A line-level markdown subset is laid out without a dependency,
keeping marks inside code spans and URLs, and emoji are removed after a
few typed ones become markers. A card that cannot be laid out prints as
a plain receipt, and the server logs the fault once at ERROR and reports
it to Sentry once. [ntfy.format] and [ntfy.markers] shape the cards; the
markers table is a setting with the user's own keys, also settable as
UBERBRINGER_NTFY_MARKERS=name=value,...

uberbringer token --modules issues a token limited to those modules'
print and preview routes, job status and the module list; each route in
the table says which tokens it takes, and a scope claim that could read
as absent makes the token invalid. image elements take optional, which
also shrinks a too-wide image to the paper; a QR code that could be too
wide for the paper prints with smaller modules; box takes title_bold.
Submit takes a Meta whose source shows in job status and, with a copy
of the request ID, in every worker log line of the job.

The four ntfy cards passed on the TM-T88IV, posted as the client recipe
posts them, and their bytes are pinned in TestPaperReceipts. docs/api.md
describes the modules, the card and the client recipe, with tokens read
from a header file; docs/swagger.json is regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 13:57:08 -06:00
1 parent fa15cb27b1
commit 1335ed0687
119 files changed
+5626 -468

No files matched your search

+51
View File
@@ -7,6 +7,57 @@ version may break callers; such changes are listed under **Breaking**.
## [Unreleased]
### Breaking
- A job with a `raw` element prints only with a token issued with
`uberbringer token --raw`. Every other token, every token issued so far
included, gets `403` `token_scope` for it and keeps every other route.
Re-issue tokens with `--raw` for the clients that send ESC/POS bytes of
their own.
### Added
- Notifications:
- The `notify` module prints a card from
`{"title", "message", "priority", "tags"}`, with `topic`, `click`,
up to 3 `actions`, `image`, `markdown` and `time` as options, for
scripts, cron jobs and phone shortcuts.
- The `ntfy` module prints one ntfy message as ntfy sends it, such as
the ntfy client's `$NTFY_RAW`, so the client can print a topic with one
entry in its `client.yml` and no other tools. `docs/api.md` gives the
recipe for Linux and Windows.
- Both print the same card: its form follows the priority (a dark
`URGENT` rule and a double box, a double box headed `HIGH`, a single
box, or no box), tags print as markers such as `[!]` in front of the
title, links print as QR codes, and attached images print after the
card. A subset of markdown is laid out, and emoji are left out. Titles,
topics, tags, labels, links and messages are capped in length: `notify`
refuses a payload over a cap, and from an ntfy message the text over a
cap is cut and the tags and links over one are left out. A card that
cannot be laid out prints as a plain receipt, and the fault is logged
and reported to Sentry.
- `[ntfy.format]` (`style`, `max_lines`, `qr`, `images`, `markdown`) and
`[ntfy.markers]` in the config shape the cards.
- Scoped tokens: `uberbringer token --modules ntfy,notify` issues a token
that may only print and preview through those modules and read job status
and the module list. Any other route answers `403` with the new error code
`token_scope`. A token whose `mod` claim is `null`, or whose `mod` or
`raw` claim is written in another letter case, is refused with `401`.
- `GET /api/v1/jobs/:id` reports the job's `source`: `print`, or
`module:<name>`. The worker's log lines carry the source and the ID of the
request that sent the job.
- `image` elements take `"optional": true`: an image that cannot be fetched
or decoded prints as `[image unavailable]` instead of failing the job,
and one whose `width` is wider than the paper shrinks to it.
- `box` takes `"title_bold": true` to print its title bold.
### Changed
- A QR code that could be wider than the paper prints with smaller modules
instead of running off its edge. Its width is worked out as if its data
were bytes, so a code of digits or capitals may shrink before it
strictly has to.
## [0.2.0] - 2026-11-30
The daemon is rewritten, and so are its install script and release process,
+1 -1
View File
@@ -41,7 +41,7 @@ that embeds its own output. The module path is the bare
`uberbringer`, so imports read `uberbringer/internal/...`. Imports point down:
- server → modules, printqueue, receipt, printer, escpos
- modules → receipt
- modules → receipt, ntfy
- printqueue → receipt
- receipt → escpos, raster
- printer → escpos
+45 -6
View File
@@ -18,6 +18,12 @@ REST API and prints them on an EPSON ESC/POS network receipt printer.
checkbox lists, sized to the paper when the job prints.
- **Modules**: send a few plain fields, such as a note's title, text and
checklist, and get a laid-out receipt back.
- **Notifications**: print [ntfy](https://ntfy.sh) messages as they arrive,
through the ntfy client with no other tools, or post a title, message,
priority and tags from any script. Each prints as a card styled by its
priority, with links as QR codes.
- **Scoped tokens**: integration tokens reach only their modules, and only
tokens issued for it can send raw ESC/POS.
- **Preview**: see the exact lines a job prints, without using paper.
- **Images that print well**: PNG, JPEG, GIF or WebP from a URL or base64,
scaled to the paper and dithered. Image URLs can't reach internal network
@@ -148,7 +154,9 @@ Every key can also be set by an environment variable named
`false` for a flag, `5s` for a duration. Lists take comma-separated values,
e.g. `UBERBRINGER_WEBSERVER_TRUSTED_PROXIES=127.0.0.1,::1`; an empty item,
from a doubled or trailing comma, is an error. In the file, a number, flag
or list may also be written as such a string.
or list may also be written as such a string. A table of your own entries,
`ntfy.markers`, takes `name=value` entries separated by commas, e.g.
`UBERBRINGER_NTFY_MARKERS=backup=[B],nas01=`; a value cannot hold a comma.
- An empty variable counts as unset, and one that holds only spaces is an
error. Variables that name no key are ignored, but when the configuration
fails to load, the error names them, since they are likely misspelt.
@@ -193,6 +201,19 @@ Settings worth knowing:
notation, in which `02 Jan 2006 15:04:05` stands for the parts of a date,
e.g. `2006-01-02 15:04`. A layout that shows no part of a date is an
error.
- `[ntfy.format]` shapes the [notification cards](docs/api.md#notification-cards)
of the `notify` and `ntfy` modules:
| Key | Default | Values |
|-----|---------|--------|
| `style` | `auto` | `auto` picks the form from the priority; `box` prints priorities 1 and 2 in a box too; `compact` prints every priority without a box |
| `max_lines` | `40` | 1–400 lines of the message, as written, before `... N more lines` |
| `qr` | `all` | Which links print as QR codes: `all`, `first` (the rest as text) or `none` |
| `images` | `true` | `false` names attached images on a `File` row instead of printing them |
| `markdown` | `true` | `false` prints markdown messages as written |
- `[ntfy.markers]` adds or changes the [markers](docs/api.md#markers)
printed for tags, at most 16 characters each, and `""` hides a tag:
`backup = "[B]"`, `nas01 = ""`.
- `webserver.trusted_proxies` / `proxy_header`: the real client IP for
per-client rate limits comes from the `X-Real-IP` header set by the reverse
proxy (Caddy, as `install.sh` configures it) on `127.0.0.1`.
@@ -210,12 +231,18 @@ Settings worth knowing:
`request_id`, and one Sentry event.
- A recovered panic adds one ERROR `panic` line, with `panic` and `stack`,
and one Sentry event.
- A print job that fails after its retries is logged as ERROR `job failed`
with its `job_id`, and is reported to Sentry.
- The worker logs each job with its `job_id`, its `source` (`print` or
`module:<name>`) and its `ref`, the ID of the request that sent it, never
with what it prints. A job that fails after its retries is logged as
ERROR `job failed` and is reported to Sentry.
- A module that builds an invalid receipt (`422` `module_failed`) is
logged as ERROR `module built an invalid receipt`, with the `module` and
the number of `problems` but not the problems themselves, and is
reported to Sentry once.
- A notification card that cannot be laid out prints as a plain receipt,
and is logged as ERROR `module printed its fallback receipt`, with the
`module`, the cause in `err` and, after a panic, its `stack`, and is
reported to Sentry once. Neither quotes the notification.
- Refusals are never logged at ERROR and never go to Sentry. Refusals are
4xx answers other than `module_failed`, the `queue_full` and
`shutting_down` 503s, and 503s from `/healthz`.
@@ -226,16 +253,27 @@ Settings worth knowing:
uberbringer [--config config.toml] run the daemon (default command)
uberbringer secret print a new random API secret
uberbringer token [--subject s] [--ttl 720h] print a signed bearer token
[--modules ntfy,notify] [--raw] ... limited to modules, or able to print raw ESC/POS
uberbringer preview [file.json|-] show the lines a job would print
uberbringer preview --module note [file|-] show the receipt a module builds
uberbringer config get <key> print one setting, e.g. webserver.port
uberbringer version print the version
```
`token` signs a token with `api.secret`. Without flags, it may use every
route but cannot print jobs with `raw` elements:
- `--raw` lets it print them. Give it only to clients that send ESC/POS
bytes of their own.
- `--modules ntfy,notify` limits it to those modules' print and preview
routes, job status and the module list. Give integrations, such as the
[ntfy client](docs/api.md#printing-from-the-ntfy-client), one of these.
The names must be modules the daemon has, and `--raw` cannot be added.
`config get` prints a setting as the daemon would use it, from the file,
`UBERBRINGER_*` variables and the defaults, and fails when the configuration
does not load. Durations print as `15s`, lists comma-separated. It never
prints `api.secret`.
does not load. Durations print as `15s`, lists comma-separated, and tables
as sorted `name=value` entries. It never prints `api.secret`.
Every command that reads the config takes `--config` (`-c`); see
[Configuration](#configuration) for its default and for running without a
@@ -313,7 +351,8 @@ internal/app/uberbringer/ CLI commands and wiring
internal/pkg/config/ Config from TOML and UBERBRINGER_* variables (Viper): defaults, validation
internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status, interpreter
internal/pkg/receipt/ Job format, validation, text folding, word wrap, blocks, rendering, preview
internal/pkg/modules/ Modules that build jobs from plain payloads, such as note; strict payload decoding
internal/pkg/modules/ Modules that build jobs from plain payloads: note, notify, ntfy; notification cards, markdown
internal/pkg/ntfy/ ntfy's message types
internal/pkg/raster/ Image decoding, scaling and dithering
internal/pkg/safehttp/ SSRF-guarded image fetching
internal/pkg/printer/ TCP printer client (port 9100) and status queries
+18
View File
@@ -79,6 +79,24 @@
timezone = "Local"
time_layout = "02 Jan 15:04"
[ntfy.format]
# How the notify and ntfy modules lay out a notification. "auto" picks the
# form from the priority: urgent and high print in double boxes, default
# in a single box, low and min under a rule with no box. "box" and
# "compact" print every priority boxed or without a box.
style = "auto"
max_lines = 40 # lines of the message that print, as written, 1-400
qr = "all" # links printed as QR codes: all, first or none
images = true # print attached images; false names them instead
markdown = true # lay out markdown messages; false prints them as written
[ntfy.markers]
# Markers printed in front of the title for ntfy's tags, at most 16
# characters each. An entry adds a marker or changes a built-in one, and
# "" hides the tag. As a variable: UBERBRINGER_NTFY_MARKERS=backup=[B],nas01=
# backup = "[B]"
# nas01 = ""
[queue]
size = 100 # jobs that may wait; more get 503
history = 1000 # finished jobs whose status is kept
+359 -14
View File
@@ -17,6 +17,9 @@ the daemon.
- [Glyphs and code pages](#glyphs-and-code-pages)
- [Modules](#modules)
- [`note`](#note)
- [`notify`](#notify)
- [`ntfy`](#ntfy)
- [Notification cards](#notification-cards)
## API
@@ -25,6 +28,35 @@ tokens with `uberbringer token`. Tokens created by the old install script keep
working as long as the secret is unchanged. Tokens in query strings are not
accepted, because they leak into proxy logs.
Keep a token off command lines too, where other users of the machine can
read it. The examples here send the header from a file only you can read,
which curl 7.55 and later take as `-H @file`. On a host set up by
`install.sh`, whose config is `/etc/uberbringer/config.toml`, make it like
this. The token passes through a shell variable, never a command's
arguments or the terminal, and the file is written only if the token
command succeeded; for a client on another machine, copy the file there.
```sh
token=$(sudo uberbringer token --config /etc/uberbringer/config.toml --subject my-script) &&
(umask 077; printf 'Authorization: Bearer %s\n' "$token" > ~/.uberbringer-auth)
unset token
```
What a token may do is set when it is issued:
- **Raw ESC/POS needs `--raw`.** A job with a [`raw`](#raw) element prints
only with a token from `uberbringer token --raw`. Any other token, every
token issued before scopes existed included, gets `403` `token_scope`
with the raw elements in `details`, and keeps every other route.
- **Integration tokens are limited to modules.** A token from
`uberbringer token --modules ntfy,notify` may only call
`POST /api/v1/print/:module` and `POST /api/v1/preview/:module` for the
modules it names, `GET /api/v1/modules` and `GET /api/v1/jobs/:id`. Any
other route answers `403` `token_scope`, e.g.
`token is limited to modules ntfy, notify`. Give one of these to an
integration such as the [ntfy client](#printing-from-the-ntfy-client),
so that it cannot send printer commands.
Responses from `/healthz` and every `/api/v1` route, error responses
included, carry `Cache-Control: no-store`.
@@ -53,7 +85,7 @@ also accepts other letter case and a few aliases, such as `centre`.
```sh
curl -X POST https://printer.example.com/api/v1/print \
-H "Authorization: Bearer $TOKEN" \
-H @"$HOME/.uberbringer-auth" \
-H "Content-Type: application/json" \
-d '{
"elements": [
@@ -73,7 +105,7 @@ curl -X POST https://printer.example.com/api/v1/print \
The response is `202 Accepted` with a `Location` header:
```json
{"id": "job_01kbx4n6m3ex8tq0wq3r5vrzq1", "status": "queued", "created_at": "2026-11-29T21:04:05Z"}
{"id": "job_01kbx4n6m3ex8tq0wq3r5vrzq1", "status": "queued", "source": "print", "created_at": "2026-11-29T21:04:05Z"}
```
Job IDs are [TypeIDs](https://github.com/jetify-com/typeid): UUIDv7 values
@@ -82,13 +114,14 @@ with a `job_` prefix, so they sort by creation time.
### Job status
```sh
curl -H "Authorization: Bearer $TOKEN" https://printer.example.com/api/v1/jobs/job_01kbx4n6m3ex8tq0wq3r5vrzq1
curl -H @"$HOME/.uberbringer-auth" https://printer.example.com/api/v1/jobs/job_01kbx4n6m3ex8tq0wq3r5vrzq1
```
```json
{
"id": "job_01kbx4n6m3ex8tq0wq3r5vrzq1",
"status": "done",
"source": "module:ntfy",
"attempts": 1,
"created_at": "2026-11-29T21:04:05Z",
"started_at": "2026-11-29T21:04:05Z",
@@ -97,7 +130,9 @@ curl -H "Authorization: Bearer $TOKEN" https://printer.example.com/api/v1/jobs/j
```
`status` is `queued`, `printing`, `done` or `failed`. A failed job includes an
`error` field. The last `queue.history` finished jobs are kept.
`error` field. `source` says where the job came from: `print` for
`/api/v1/print`, or `module:<name>` for a [module](#modules) route. The last
`queue.history` finished jobs are kept.
### Preview a receipt
@@ -107,7 +142,7 @@ with the lines the printer would print, as `text/plain; charset=utf-8`:
```sh
curl -X POST https://printer.example.com/api/v1/preview \
-H "Authorization: Bearer $TOKEN" \
-H @"$HOME/.uberbringer-auth" \
-H "Content-Type: application/json" \
-d '{"elements": [{"type": "box", "fit": true, "padding": 3, "text": "!!! ACHTUNG !!!"},
{"type": "qr", "data": "https://example.com"}]}'
@@ -203,8 +238,9 @@ Errors are JSON:
framework's own text; for example, an unknown route answers `not found`.
- `details` lists every problem when a job fails validation (`invalid_job`),
a module payload is invalid (`invalid_payload`) or a module builds an
invalid receipt (`module_failed`). Each job problem names the element by
its path, e.g.
invalid receipt (`module_failed`), and the raw elements a token may not
print (`token_scope`). Each job problem names the element by its path,
e.g.
`elements[0].children[3] (qr): not allowed inside a box; place it after the box`,
and each payload problem names the field, e.g.
`done[0]: index 5 is out of range`.
@@ -217,6 +253,7 @@ Errors are JSON:
| 400 | `unknown_printer` | On a module route: `printer` names a printer other than `default` |
| 400 | `bad_request` | A malformed HTTP request, refused by the server itself |
| 401 | `unauthorized` | `missing bearer token`, or `invalid or expired token`. Sent with `WWW-Authenticate` |
| 403 | `token_scope` | The token does not allow the request: a token limited to modules on another route, e.g. `token is limited to modules ntfy, notify`, or a job with `raw` elements from a token issued without `--raw`, which lists them in `details`. See [tokens](#api) |
| 404 | `not_found` | Unknown route |
| 404 | `job_not_found` | Unknown, expired or malformed job ID |
| 404 | `module_not_found` | Unknown module, e.g. `module "notx" not found` |
@@ -237,8 +274,9 @@ Any other status that the HTTP layer produces itself gets the code
shown under [Health](#health), not with this shape.
Validation happens before a job is queued. Images are fetched by the worker,
so a blocked or broken image URL shows up as a `failed` job. Nothing is sent
to the printer unless the whole receipt rendered.
so a blocked or broken image URL shows up as a `failed` job, unless the image
is `optional`. Nothing is sent to the printer unless the whole receipt
rendered.
## Elements
@@ -296,7 +334,7 @@ sizes on one line still wrap correctly.
| Field | Default | Values |
|--------------|---------|--------|
| `data` | | Required. Encoded as UTF-8, up to 7089 bytes |
| `size` | `6` | Module size in dots, 1–16 |
| `size` | `6` | Module size in dots, 1–16. A code that could be wider than the paper prints with smaller modules. Its width is worked out as if its data were bytes, the least dense way to encode them, so a code of digits or capitals may shrink before it strictly has to |
| `correction` | `M` | `L`, `M`, `Q`, `H` |
| `align` | `left` | |
@@ -319,6 +357,7 @@ sizes on one line still wrap correctly.
| `base64` | | Image data, or a `data:image/png;base64,...` URI |
| `width` | natural | Target width in dots, up to the model's print width (512 on a TM-T88) |
| `align` | `left` | |
| `optional` | `false` | `true` prints the line `[image unavailable]`, aligned as the image, in place of an image that cannot be fetched or decoded, instead of failing the job, and shrinks an image whose `width` is wider than the paper to it |
PNG, JPEG, GIF and WebP are supported. Images wider than the paper are scaled
down to fit, and every image is dithered to black and white. URL fetches have
@@ -333,6 +372,10 @@ or link-local addresses (including cloud metadata endpoints) are refused unless
|-------|--------|
| `hex` | ESC/POS bytes as hex, spaces allowed, e.g. `"1B 61 01"` |
The bytes are sent as given, so a job with a `raw` element prints only with
a token issued with `uberbringer token --raw`; any other token gets `403`
`token_scope`. Previewing one needs no such token.
### `cut`
| Field | Default | Values |
@@ -388,6 +431,7 @@ footer or label is cut with `...` instead of failing.
| `style` | `single` | `single` ┌─┐, `double` ╔═╗, `double-h` ╒═╕ (double lines across, single down), `double-v` ╓─╖ (single across, double down), `ascii` +-+ |
| `title` | | Text set into the top border |
| `title_style` | `inline` | `inline` `┌─ Title ───┐`, or `capped` `╔═╡ Title ╞══╗` |
| `title_bold` | `false` | `true` prints the title bold; the border around it stays plain |
| `footer` | | Text set into the bottom border, on the right: `└──── footer ──┘` |
| `align` | `left` | Alignment of `text`, and the default for text children |
| `bold`, `underline`, `invert` | | Styles of `text`, as on a `text` element |
@@ -515,12 +559,14 @@ them, so a script or a phone shortcut does not have to lay one out from
elements. `GET /api/v1/modules` lists them:
```json
[{"name": "note", "description": "Boxed note with an optional checklist"}]
[{"name": "note", "description": "Boxed note with an optional checklist"},
{"name": "notify", "description": "Notification card from title, message, priority and tags"},
{"name": "ntfy", "description": "One ntfy message object, e.g. the CLI's $NTFY_RAW"}]
```
```sh
curl -X POST https://printer.example.com/api/v1/print/note \
-H "Authorization: Bearer $TOKEN" \
-H @"$HOME/.uberbringer-auth" \
-H "Content-Type: application/json" \
-d '{"title": "Shopping", "text": "Milk, eggs and the good bread from the bakery on Elm St.",
"items": ["Milk", "Eggs", "Bread"], "done": [2]}'
@@ -533,8 +579,9 @@ job and a `Location` header, or `503` when the queue is full or closing.
- `204` with no body means the module had nothing to print.
- `400` `invalid_payload` lists every problem with the payload in `details`.
Payloads are decoded strictly: an unknown field, or a field name in
another case, is a problem.
`note` and `notify` decode their payloads strictly: an unknown field, or a
field name in another case, is a problem. `ntfy` takes ntfy's messages as
they are and ignores the fields it does not know.
- `404` `module_not_found` names an unknown module.
- `422` `module_failed` means the module built a receipt that fails
validation. That is a bug in the module, and it is logged.
@@ -573,3 +620,301 @@ the bottom border. The request above prints:
| `style` | `single` | The border: `single`, `double`, `double-h` or `double-v`, as on a [`box`](#box) |
| `footer` | | Text for the bottom border in place of the time |
| `stamp` | `true` | `false` leaves the bottom border empty when there is no `footer` |
### `notify`
A [notification card](#notification-cards), for scripts, cron jobs and
phone shortcuts. The smallest payload is `{"message": "Back at 3"}`:
```text
┌─ Notification ─────────────────────────┐
│ Back at 3 │
└──────────────────────── 29 Nov 21:04 ──┘
```
```sh
curl -X POST https://printer.example.com/api/v1/print/notify \
-H @"$HOME/.uberbringer-auth" \
-H "Content-Type: application/json" \
-d '{"title": "Disk almost full", "message": "/var is at 94% on nas01", "priority": "high",
"tags": ["warning", "nas01"], "topic": "alerts", "click": "https://grafana.lan/d/disk",
"actions": [{"label": "Open dashboard", "url": "https://grafana.lan/d/disk"}]}'
```
```text
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
```
| Field | Default | Values |
|------------|---------|--------|
| `message` | | Required. Up to 4096 bytes; `\n` starts a new line |
| `title` | the topic, or `Notification` | Up to 250 characters |
| `priority` | `3` | 1–5, or `min`, `low`, `default`, `high`, `max` or `urgent`, as a number or a string. It picks the [form](#notification-cards) |
| `tags` | | Up to 20 tags of up to 64 characters. Those with a [marker](#markers) print it in front of the title; the rest are listed on a `Tags:` row |
| `topic` | | Up to 64 characters, printed in the bottom border before the time |
| `click` | | An `http` or `https` URL of up to 2000 bytes, printed as a QR code |
| `actions` | | Up to 3 links, `{"label": "Open dashboard", "url": "https://..."}`, each printed as a QR code with its label: labels up to 64 characters, URLs up to 2000 bytes. A card prints at most 3 different URLs, `click` first: an action with the same URL as `click` or an earlier action prints once, with its label when the link had none, and the actions after the third different URL are left out |
| `image` | | An `http` or `https` URL of up to 2000 bytes, of an image printed after the card |
| `markdown` | `false` | `true` lays out the message as [markdown](#markdown) |
| `time` | now | When it happened: Unix seconds, or RFC 3339 such as `2026-11-29T21:04:05Z` |
A payload over a limit is `400` `invalid_payload`, e.g.
`title: 300 characters, limit is 250`.
### `ntfy`
One message from [ntfy](https://ntfy.sh)'s subscribe API, exactly as ntfy
sends it, printed as a [notification card](#notification-cards). The ntfy
command line client passes such a message to a command in `$NTFY_RAW`, so
it can be posted as it is:
```json
{"id": "sPs71M8A2Tq9", "time": 1795986245, "event": "message", "topic": "alerts",
"title": "Disk almost full", "message": "**/var** is at *94%* on nas01",
"content_type": "text/markdown", "priority": 4, "tags": ["warning", "nas01"],
"click": "https://grafana.lan/d/disk",
"actions": [{"id": "a1", "action": "view", "label": "Open dashboard", "url": "https://grafana.lan/d/disk", "clear": false}],
"attachment": {"name": "graph.png", "type": "image/png", "size": 33848, "expires": 1796029445,
"url": "https://ntfy.example.com/file/sPs71M8A2Tq9.png"}}
```
Printed on 29 Nov 2026 at 21:04 UTC, when it was sent, before its
attachment expires:
```text
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
[qr: https://grafana.lan/d/disk]
Open dashboard
[image 384 dots: sPs71M8A2Tq9.png]
- - - - - - - partial cut - - - - - - - -
```
- Fields the module does not know are ignored, so messages from newer ntfy
versions still print. A body that is not one JSON object, or a known
field of the wrong type, is `400` `invalid_payload`.
- Events other than `message` (`open`, `keepalive`, `poll_request`,
`message_delete`, `message_clear`) and messages with a binary body
(`"encoding": "base64"`) answer `204` and print nothing. A message
without an `event` counts as a message.
- `title`, `message`, `tags`, `topic` and `time` print as on `notify`. A
missing or out-of-range `priority` is 3. `"content_type": "text/markdown"`
lays out the message as [markdown](#markdown).
- The links are `click` and the URLs of the `view` actions. `http`,
`broadcast` and `copy` actions never print, since their headers, bodies
and values can hold secrets. `icon` is ignored.
- An `attachment` that is an image prints after the card until its
`expires` passes, and after that, like any other file, is named on a
`File` row; see [links and attachments](#links-and-attachments). When the
message is only ntfy's `You received a file: <name>`, it is left out,
since the file shows on its own.
- A message that updates an earlier one, with the same `sequence_id`,
prints as it is, like any other: one message cannot tell whether it is
the first of its sequence, since a publisher may choose the sequence ID.
- A message over the [limits](#notify) of `notify` is not refused; what is
over them is cut or left out. A title, topic, tag, label or file name is
cut with `...`, and the message after 4096 bytes. Tags after the 20th are
left out, and so is a link whose URL is longer than 2000 bytes; an
attachment with such a URL is named on a `File` row instead of printed.
#### Printing from the ntfy client
The [ntfy command line client](https://docs.ntfy.sh/subscribe/cli/) can
subscribe to topics and post each message here, with no other tools. Give it
a token limited to the module, so that it cannot print anything else, in a
header file that only the user the client runs as can read. Both setups
below keep the token off command lines and out of shell history.
For your own client, with `~/.config/ntfy/client.yml`, make the file as
yourself, as [above](#api):
```sh
mkdir -p ~/.config/ntfy
token=$(sudo uberbringer token --config /etc/uberbringer/config.toml --subject ntfy-cli --modules ntfy) &&
(umask 077; printf 'Authorization: Bearer %s\n' "$token" > ~/.config/ntfy/uberbringer-auth)
unset token
```
and add an entry like this to `~/.config/ntfy/client.yml`:
```yaml
default-host: https://ntfy.sh
default-token: tk_...
subscribe:
- topic: alerts
command: |
printf '%s' "$NTFY_RAW" | curl -fsS -X POST \
-H @"$HOME/.config/ntfy/uberbringer-auth" -H "Content-Type: application/json" \
--data-binary @- https://printer.example.com/api/v1/print/ntfy
if:
priority: default,high,urgent
```
For the system-wide `ntfy-client` service, with `/etc/ntfy/client.yml`, the
header file belongs to the user the service runs as, shown by
`systemctl cat ntfy-client`; here it is `ntfy`. Once the token command has
succeeded, create the file empty with that owner and mode `600`, then fill
it through `tee`, which keeps both:
```sh
token=$(sudo uberbringer token --config /etc/uberbringer/config.toml --subject ntfy-cli --modules ntfy) &&
sudo install -m 600 -o ntfy -g ntfy /dev/null /etc/ntfy/uberbringer-auth &&
printf 'Authorization: Bearer %s\n' "$token" | sudo tee /etc/ntfy/uberbringer-auth > /dev/null
unset token
```
The entry in `/etc/ntfy/client.yml` is the one above with
`-H @/etc/ntfy/uberbringer-auth` in place of the path under `$HOME`.
On Windows, `cmd.exe` breaks `%NTFY_RAW%`, so the command runs PowerShell,
with the token in the client's environment as `UBERBRINGER_TOKEN`:
```yaml
command: powershell -NoProfile -Command "Invoke-RestMethod -Method Post -Uri https://printer.example.com/api/v1/print/ntfy -Headers @{Authorization=('Bearer ' + $env:UBERBRINGER_TOKEN)} -ContentType 'application/json' -Body ([Text.Encoding]::UTF8.GetBytes($env:NTFY_RAW))"
```
`if:` picks the priorities that print; leave it out to print them all.
> [!WARNING]
> Anyone who knows a topic's name on the public `ntfy.sh` can publish to it,
> and so print on your printer. Use a reserved or access-controlled topic
> or your own ntfy server, or at least a long random topic name.
### Notification cards
`notify` and `ntfy` print the same card. Its form follows the priority:
| Priority | Form |
|----------|------|
| 5, `max` or `urgent` | A dark rule `URGENT`, a double box with the title row bold and inverted and a double divider, then another dark rule |
| 4, `high` | A double box headed `HIGH`, with the title row bold and a single divider |
| 3, `default` | A single box with the title, in bold, set into its top border |
| 1–2, `min` and `low` | No box: a rule with the topic and time, then the title in bold and the message |
```text
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
╔════════════════════════════════════════╗
║ (!) Backup FAILED on nas01 ║
╠════════════════════════════════════════╣
║ Job nightly-offsite exited with code 2 ║
║ after 3h12m. Last good run: 2 days ║
║ ago. ║
╚══════════════ backups · 29 Nov 21:04 ══╝
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
┌─ [√] Nightly backup ───────────────────┐
│ restic: 2.1 GB added in 14m 02s, 0 │
│ errors. │
│ │
│ Tags: restic │
└────────────── backups · 29 Nov 03:12 ──┘
── backups · 29 Nov 03:12 ────────────────
Prune finished
41 snapshots kept, 3 removed.
```
The settings in [`[ntfy.format]`](../README.md#configuration) shape every
card: `style = "box"` gives priorities 1 and 2 the single box too, and
`style = "compact"` prints every priority without a box, with `URGENT` or
`HIGH` in front of the topic. The title is the payload's, or else the
topic, or else `Notification`; a long title is cut with `...` in a border.
The bottom border holds the topic and the time, in `format.timezone` and
`format.time_layout`.
The message prints its first `ntfy.format.max_lines` lines as written
(default 40), then `... N more lines`. Emoji are left out, apart from a few
that print as [markers](#markers): `⚠` as `[!]`, `✅` as `[√]`, `❌` as
`[x]`, `🚨` as `(!)` and `👍` as `(+1)`. Symbols a code page prints, such as
`■`, stay. A title or tag that is only emoji counts as missing.
If a card cannot be laid out, a plain receipt prints instead: the title in
bold, the message, then the topic and time. That is a bug: it is logged at
ERROR as `module printed its fallback receipt` and reported to Sentry, and
`uberbringer preview --module` prints a warning.
#### Markers
Up to two tags with a marker print it in front of the title, each marker
once. The other tags are listed on a `Tags: a, b` row at the end of the
card. Tags match in lower case.
| Tags | Marker |
|------|--------|
| `warning` | `[!]` |
| `rotating_light`, `fire`, `boom` | `(!)` |
| `white_check_mark`, `heavy_check_mark`, `ballot_box_with_check` | `[√]` |
| `x`, `negative_squared_cross_mark`, `no_entry`, `no_entry_sign` | `[x]` |
| `information_source` | `(i)` |
| `question` | `(?)` |
| `+1`, `thumbsup` | `(+1)` |
| `-1`, `thumbsdown` | `(-1)` |
| `loudspeaker`, `mega` | `<!>` |
| `tada` | `\o/` |
| `skull` | `x_x` |
| `hourglass` | `(...)` |
`[ntfy.markers]` in the config adds markers or changes these, and an empty
marker hides a tag: `backup = "[B]"`, `nas01 = ""`.
#### Markdown
A markdown message (`"markdown": true`, or ntfy's
`"content_type": "text/markdown"`) is laid out line by line:
| Written | Prints as |
|---------|-----------|
| `# Title`, `## Title`, `### Title` | A bold line |
| `- item`, `* item`, `+ item` | A `·` list |
| `1. item` | A numbered list |
| `> quote` | The line with `│ ` in front |
| Lines between ` ``` ` fences | As written |
| `---` | A divider across the card |
| `**bold**`, `__bold__`, `*italic*`, `_italic_`, `` `code` ``, `~~struck~~` | The text, without the marks |
| `[text](https://...)` | The text; the URL is added to the links |
| `![alt](url)` | `[image: alt]` |
A backslash keeps a mark as written: `\*` prints `*`. Marks inside a code
span or a bare URL print as written, as in `__init__.py`; a mark or
punctuation at the end of a URL is not part of it, so `**https://x.lan**`
prints the URL plain. Every other line prints as written, and a run of
empty lines as one. With
`ntfy.format.markdown = false`, markdown prints as written.
#### Links and attachments
- The links are the click URL, then the actions' URLs, then the markdown
links, each URL once and at most 3. Only `http` and `https` URLs of up to
2000 bytes print.
- With `ntfy.format.qr = "all"`, the default, each link prints after the
card as a centred QR code with its label, or else its host and path, in
the small font below it. `"first"` prints only the first as a QR code
and the others as `» label` and the URL; `"none"` prints them all as
text. On narrow paper a QR code prints with smaller modules, so that it
fits; a link longer than 500 bytes always prints as text.
- An attached PNG, JPEG, GIF or WebP image, known by its type or else its
name or URL, prints after the links, centred and 384 dots wide, or as
wide as a narrower paper. It is
fetched when the job prints, as an [`image`](#image) with `optional` set:
one that cannot be fetched prints `[image unavailable]`, and the rest of
the card prints anyway. `ntfy.format.images = false` names images on a
`File` row instead.
- Any other file, and an image whose `expires` has passed, is named on a
`File` row with its size, e.g. `File ....... report.pdf (1.4 MB)`.
+99 -4
View File
@@ -105,6 +105,89 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
OpenAPI document describes their body as a JSON object whose fields the
module defines, not as a strict schema: one route serves every module,
and each module checks its own payload.
- **Notifications print as one card.** The `notify` and `ntfy` modules turn
their payloads into a `Notice` and lay it out with the same `Card`, which
phase 4's subscriber will use too.
- `ntfy` decodes leniently, so that messages from newer ntfy versions
still print, while `notify`, which scripts write by hand, is strict like
`note`. A message without an `event` counts as a message, so that a
hand-made body does not silently print nothing.
- The routes print every message plain, never marked `(updated)` and
never skipped as an update (owner, 2026-11-30). A publisher may choose
a message's sequence ID, so the first message of a sequence can carry
one that differs from its ID, and one message cannot tell a first from
a replacement. Only the subscriber, which remembers what it printed,
can mark replacements.
- The priority picks the form; `[ntfy.format] style` can force the box or
the boxless form. The default form prints its title bold in the top
border, so `box` has `title_bold`; it is a field of its own because
making every box title bold would change receipts already checked on
paper.
- Emoji are removed on this path rather than printed as `?`, after a few
typed ones become markers. `receipt.StripEmoji` keeps the symbols among
the emoji ranges that some code page prints or folds (`■ → ✓`), since
a module does not know the configured code page. A title or tag that
is only emoji counts as missing.
- The markdown subset is line by line and hand-written, with no
dependency: a card needs bold lines, lists, dividers and links, not
full CommonMark. Emphasis inside a word follows CommonMark, so `2*3*4`
loses its stars; `_` inside a word stays, and so does every mark inside
a code span or a bare URL, such as `__init__.py`. As in GitHub's
autolinks, marks and punctuation at a URL's end are not part of it, so
`**https://x.lan**` is bold around a whole URL.
- A module lays out a job before it knows the printer, so its lengths are
capped in characters, not lines: title 250, topic 64, 20 tags of 64,
labels 64, file names 128, links 2000 bytes and the message 4096 bytes,
ntfy's own default. `notify` refuses a payload over a cap. From an ntfy
message a card cuts the text over a cap and leaves out the tags after
the 20th and the links over 2000 bytes, and names an attachment with
such a URL on a `File` row. A card then prints well inside the default
`format.max_lines` of 2000, even on 58 mm paper; with a much lower
limit a long card can still fail when it renders, which stays the
backstop, as for `/print`. `ntfy.format.max_lines` counts the
message's lines as written and is at most 400, so that a card stays
under the 500-element limit.
- Links print as QR codes, size 5, and the renderer narrows a code's
modules until it fits the paper; a link over 500 bytes prints as text.
Only view actions and the click URL become links; `http`, `broadcast`
and `copy` actions can carry secrets in their headers, bodies and
values and never print.
- Only PNG, JPEG, GIF and WebP attachments print as images, the formats
the renderer decodes; any other `image/*` type is named on a `File` row
rather than printed as `[image unavailable]`. Attached images are
`optional` images 384 dots wide, which the renderer shrinks to a
narrower paper: an optional image never fails for its width. `optional`
is an image-only field; the other older types refuse it as they refuse
the block fields.
- A card always prints: a layout that panics or builds an invalid job
gives a plain receipt of title, message, topic and time. `Card` returns
the fault with it, and the server logs it once at ERROR, with the
panic's stack, and reports it to Sentry once, as for any unexpected
error, without quoting the notification.
- The card options travel in the module `Env`, and their zero value is
the default, so a module built without config still prints sensibly.
- **Tokens carry their scope (owner, 2026-11-30).** Integration tokens must
not send printer commands, and the owner chose to fence raw ESC/POS off
for every token rather than only for new ones.
- A `mod` claim limits a token to the module routes it names, plus job
status and the module list. Each route in the table says whether such
tokens may use it, and the check runs before the handler.
- Printing a job with a `raw` element needs a `raw: true` claim
(`uberbringer token --raw`). Tokens without it, every older token
included, keep every other route, so only clients that send raw hex
need a new token. Previewing raw elements stays open, since a preview
sends nothing to the printer.
- A scope claim that could read as absent makes the token invalid
(`401`): one of the wrong type, `mod` given as `null`, and `mod` or
`raw` written in another letter case, which `encoding/json` would
match. A malformed scope can therefore never widen access.
- **Jobs remember their source.** `Submit` takes a `Meta`: the source
(`print`, `module:<name>`, later `ntfy:<subscription>`) and a reference,
the request ID on the HTTP routes. Job status shows the source and every
worker log line of the job carries both, so a printed receipt can be
traced to its request without logging what it says. The server copies
both strings, since a request ID the client sent lives in a buffer that
fasthttp reuses for the next request.
- **The preview reads the bytes back.** `escpos.Interpret` parses the stream
the renderer produced, so the preview and the tests show what the printer
receives rather than what the layout meant. It simulates the printer's own
@@ -118,6 +201,13 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
its own edge (`seve` / `ral`). A profile wider than the printer breaks
words, while a narrower one only shortens lines. So `tm-t88` (512 dots, 42
columns) is the default.
- A QR code is fitted to the paper the same way. The printer encodes it
and picks the mode, so its width is worked out from the bytes each QR
version holds, byte mode being the least dense: a code that could be
wider than the paper prints with smaller modules instead of running off
the edge, and one of digits or capitals may shrink before it strictly
has to. Data that only a denser mode holds counts as the largest
version.
- **Status is read in a way that tolerates a busy printer.** `/healthz` sends
DLE EOT 1 to 4 over the same connection slot that sends use.
- The DLE EOT 2 bits (cover open, paper-end stop) are cleared while DLE
@@ -157,7 +247,8 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
hand. The server gets the document in its config, so the generator does
not build the package that embeds its own output.
- **What stays compatible with 0.1.** The endpoint, the HS256 tokens and the
config keys stay as they were. The 0.1 body and its plain-text answer do
config keys stay as they were, though a job with raw elements now needs a
token issued with `--raw`. The 0.1 body and its plain-text answer do
not. A 0.1 body gets a `400` that points to the element format in
`docs/api.md`, instead of being translated. Tokens are read only from the header, because tokens in
query strings end up in proxy logs.
@@ -172,6 +263,9 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
variable, which wins over the file, so a container can run without one.
Unknown keys in the file stay errors; unknown variables are ignored,
because the environment holds much besides Überbringer's settings.
A table whose keys are the user's own, such as `ntfy.markers`, is one
setting: its variable holds `name=value` entries separated by commas,
and in the file a name with a dot or a nested table is an unknown key.
- `go.mod`'s go line is the latest Go release, with no separate toolchain
line.
- **Packaging.** The daemon serves no TLS itself and binds 127.0.0.1 by
@@ -194,9 +288,10 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
## Planned: formatters
Modules, ntfy among them, that turn plain input into receipts built from the
blocks. The plan is `docs/plans/formatters.md`. Its first two phases are
built: the blocks and the preview, then the `list` block, the module layer
and the `note` module. Decided so far (owner, 2026-11-29):
blocks. The plan is `docs/plans/formatters.md`. Its first three phases are
built: the blocks and the preview; the `list` block, the module layer and
the `note` module; then the `notify` and `ntfy` modules and scoped tokens.
Next is the built-in ntfy subscriber. Decided so far (owner, 2026-11-29):
- ntfy is an input: its notifications are printed. The server is
self-hosted at a public URL, the subscriber authenticates with a token, and
+28 -320
View File
@@ -1,6 +1,6 @@
# Plan: CP437 blocks, modules and ntfy printing
Status: **phases 1 and 2 are done**. Phase 1: box, rule and kv, text folding and the preview. Phase 2: the list block, the module layer, the note module and its routes, and `[format] timezone` and `time_layout`. Both are built and checked on paper (docs/api.md § Blocks and § Modules, design.md). Phases 3-5 are not started. Every design decision for phases 3-4 is made; the open questions left are an assumed default, config values and the second printer. Each phase runs in its own session, briefed from its section.
Status: **phases 1-3 are done**. Phase 1: box, rule and kv, text folding and the preview. Phase 2: the list block, the module layer, the note module and its routes, and `[format] timezone` and `time_layout`. Phase 3: the notify and ntfy modules and their cards, scoped tokens, optional images and job sources. All three are built and checked on paper (docs/api.md § Blocks and § Modules, design.md). Phases 4-5 are not started. Every design decision for phase 4 is made; the open questions left are config values and the second printer. Each phase runs in its own session, briefed from its section.
## Decisions (owner, 2026-11-29)
@@ -42,10 +42,10 @@ Ideas taken from the other designs:
- From Design 2 (templates): fit boxes, a hand-written markdown subset with no new dependency, a plain fallback receipt, a since=<time> cursor, token scopes, and '?' warnings in preview.
- From Design 3 (sources): a simple Notice input (the notify module), images marked optional, a cursor taken from ntfy server time, the time/tzdata import, and Submit Meta for traceability.
WHAT SHIPS WHEN (about 8 developer days left to the end of phase 4)
WHAT SHIPS WHEN (about 5 developer days left to the end of phase 4)
1. Boxes and preview: done.
2. Notes and modules: done. POST /api/v1/print/note {title, text, items} prints a boxed checklist.
3. Notifications, 3 days. POST /api/v1/print/notify {title, message, priority, tags} is for scripts and phone shortcuts. POST /api/v1/print/ntfy takes the ntfy CLI's $NTFY_RAW unchanged. After this phase, ntfy printing needs only a client.yml entry and no jq.
3. Notifications: done. POST /api/v1/print/notify {title, message, priority, tags} is for scripts and phone shortcuts. POST /api/v1/print/ntfy takes the ntfy CLI's $NTFY_RAW unchanged, so ntfy printing needs only a client.yml entry and no jq.
4. Built-in ntfy subscriber, 5 days. You only change the config. It reconnects safely, removes duplicates, caps the backlog, folds floods into a digest receipt, and holds non-urgent messages during quiet hours for a morning digest.
5. Later, on demand: the second-printer pool, user templates, an ntfy-compatible publish endpoint, table/banner/spans, and webhooks.
@@ -58,28 +58,26 @@ WHERE THE JUDGES DISAGREED, AND WHAT THIS PLAN CHOSE
- list: in (phase 2), because the note module needs checklists.
- spans, table, group, banner, nested boxes and goldmark: deferred.
- Geometry checks in the HTTP handler (Renderer.Check): rejected. Layout never fails on a valid job, preview shows the result and line count synchronously, and each module caps its own length.
- Scoped tokens: in phase 3, before any integration token is handed out.
- Scoped tokens: built in phase 3; design.md records the decision.
- Quiet hours: phase 4, as a morning digest (owner decision).
## Open questions
Before phase 3 (assumed unless the owner says otherwise):
1. Integration tokens: tokens created with --modules can only use module
routes, while existing tokens keep full access including raw ESC/POS.
Before phase 4 (config, not design):
2. Topics and auth: which topics and quiet-hours window to configure. A
1. Topics and auth: which topics and quiet-hours window to configure. A
dedicated read-only ntfy user with an access token is assumed.
When the second printer arrives:
3. Which jobs and ntfy topics go to which printer, and should urgent messages
2. Which jobs and ntfy topics go to which printer, and should urgent messages
print on both?
## Mockups (42 columns, CP437)
The notification cards are built: docs/api.md § Notification cards shows
the four priority forms as they printed. Still to come:
```text
All lines are at most 42 columns; every
glyph is a CP437 byte >= 0x20 (checked
@@ -87,56 +85,6 @@ with Python cp437). Ruler, not printed:
1 2 3 4
123456789012345678901234567890123456789012
--- 1. ntfy priority 4 (high)
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
[qr: grafana.lan/d/disk]
Open dashboard
[image 384 dots: graph.png]
- - - - - - - partial cut - - - - - - - -
Input: the brief's example message.
Row 2 prints bold. [!] is the "warning"
tag; "nas01" has no marker, so it is
listed. **/var** *94%* prints plain.
The QR is the click URL. The view action
has the same URL, so its label is the
caption. [...] lines are real graphics.
--- 2. ntfy priority 5 (max/urgent)
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
╔════════════════════════════════════════╗
║ (!) Backup FAILED on nas01 ║
╠════════════════════════════════════════╣
║ Job nightly-offsite exited with code 2 ║
║ after 3h12m. Last good run: 2 days ║
║ ago. ║
╚══════════════ backups · 29 Nov 21:04 ══╝
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
Row 3 prints bold and inverted. (!) is
the "rotating_light" tag.
--- 3. ntfy priority 3 (default)
┌─ [√] Nightly backup ───────────────────┐
│ restic: 2.1 GB added in 14m 02s, 0 │
│ errors. │
│ │
│ Tags: restic │
└────────────── backups · 29 Nov 03:12 ──┘
The title prints bold in the top border.
--- 4. ntfy priority 1-2 (no box)
── backups · 29 Nov 03:12 ────────────────
Prune finished
41 snapshots kept, 3 removed.
"Prune finished" (the title) is bold.
--- 12. Rate-limit digest (phase 4)
┌─ ntfy digest · 6 held ─────────────────┐
│ 21:05 [!] Disk almost full │
@@ -158,89 +106,15 @@ Use · ∙ ■ » √ ° instead.
## API
All /api/v1 routes keep the existing Bearer JWT, rate limiter and error shape {"error","details"}. Successful print responses keep today's 202 body plus a Location header:
{"id":"job_01kbx4n6m3ex8tq0wq3r5vrzq1","status":"queued","created_at":"2026-11-29T21:04:05Z"}
{"id":"job_01kbx4n6m3ex8tq0wq3r5vrzq1","status":"queued","source":"print","created_at":"2026-11-29T21:04:05Z"}
==== Blocks in POST /api/v1/print ====
==== PHASE 4: configuration ====
box, rule, kv and list, the preview (POST /api/v1/preview, `uberbringer preview`) and format.max_lines are built; docs/api.md § Blocks and § Preview a receipt describe them. Validation problems name nested elements, e.g. elements[0].children[3] (qr). Still to come:
Keys go through internal/pkg/config as today: strict keys in the file, an UBERBRINGER_<SECTION>_<KEY> variable for each setting. [format] and the card settings [ntfy.format] and [ntfy.markers] are built (README § Configuration).
image (phase 3)
- New field optional: true. If the image can't be fetched or decoded, the receipt prints "[image unavailable]" instead of failing the whole job.
==== Modules ====
Built in phase 2 (docs/api.md § Modules): GET /api/v1/modules, POST /api/v1/print/{module} and /api/v1/preview/{module} (202, 204 for ErrSkip, 400 invalid_payload, 404 module_not_found, 422 module_failed, 503 as on /print), ?copies, ?printer reserved for "default", and the note module. Payloads decode with modules.DecodeStrict, which reports every problem. Still to come:
- GET /api/v1/modules also lists notify and ntfy once they are registered in newModules (internal/app/uberbringer/modules.go):
{"name":"notify","description":"Notification card from title, message, priority and tags"},
{"name":"ntfy","description":"One ntfy message object, e.g. the CLI's $NTFY_RAW"}
- 403: the token's scope does not include this module (phase 3). It needs a new code in server/errors.go and docs/api.md.
- 422 stays a module bug; ntfy and notify print the fallback receipt instead of building an invalid job.
==== PHASE 3: notifications ====
notify payload (strict; for scripts, cron jobs and phone shortcuts):
POST /api/v1/print/notify
{"title":"Disk almost full","message":"/var is at 94% on nas01","priority":"high","tags":["warning","nas01"],
"topic":"alerts","click":"https://grafana.lan/d/disk","markdown":false}
- Optional fields:
- time: Unix seconds or RFC 3339. Default now.
- actions: up to 3 [{label, url}].
- image: a URL.
- priority is 1-5, or one of min, low, default, high, max, urgent.
- Minimal call: {"message":"Back at 3"} prints a priority-3 single box.
ntfy payload: one ntfy subscribe-API message, exactly as received.
- Decoded leniently: unknown fields are ignored, so new ntfy versions keep working.
POST /api/v1/print/ntfy
{"id":"sPs71M8A2Tq9","time":1764450245,"event":"message","topic":"alerts","title":"Disk almost full",
"message":"**/var** is at *94%* on nas01","content_type":"text/markdown","priority":4,"tags":["warning","nas01"],
"click":"https://grafana.lan/d/disk",
"actions":[{"id":"a1","action":"view","label":"Open dashboard","url":"https://grafana.lan/d/disk","clear":false}],
"attachment":{"name":"graph.png","type":"image/png","size":33848,"expires":1764461045,"url":"https://ntfy.example.com/file/sPs71M8A2Tq9.png"}}
- 202: prints mockup 1.
- 204: open, keepalive, poll_request, message_delete and message_clear events, and encoding=base64.
ntfy CLI recipe (works after phase 3; no jq). Linux, in ~/.config/ntfy/client.yml or /etc/ntfy/client.yml:
default-host: https://ntfy.sh
default-token: tk_...
subscribe:
- topic: alerts
command: |
printf '%s' "$NTFY_RAW" | curl -fsS -X POST \
-H "Authorization: Bearer $UBERBRINGER_TOKEN" -H "Content-Type: application/json" \
--data-binary @- https://printer.example.com/api/v1/print/ntfy
if:
priority: default,high,urgent
Windows: cmd.exe breaks %NTFY_RAW%, so use PowerShell:
command: powershell -NoProfile -Command "Invoke-RestMethod -Method Post -Uri https://printer.example.com/api/v1/print/ntfy -Headers @{Authorization=('Bearer ' + $env:UBERBRINGER_TOKEN)} -ContentType 'application/json' -Body ([Text.Encoding]::UTF8.GetBytes($env:NTFY_RAW))"
Scoped tokens:
- uberbringer token --subject ntfy-cli --modules ntfy,notify adds the claim "mod":["ntfy","notify"].
- A token with that claim may only call:
- POST /api/v1/print/{m} and /api/v1/preview/{m} for the listed modules
- GET /api/v1/modules
- GET /api/v1/jobs/{id}
- Anything else returns 403 {"error":"token is limited to modules ntfy, notify"}.
- Tokens without the claim keep full access, so existing tokens keep working.
Job status:
- GET /api/v1/jobs/{id} gains "source", e.g. "module:ntfy" or, in phase 4, "ntfy:home".
==== PHASE 3-4: configuration ====
Keys go through internal/pkg/config as today: strict keys in the file, an UBERBRINGER_<SECTION>_<KEY> variable for each setting, and [format] max_lines, timezone and time_layout already built.
[ntfy.format] # phase 3
style = "auto" # auto | box | compact
max_lines = 40
qr = "all" # all | first | none
images = true
markdown = true
updates = "print" # print | skip (sequence_id updates)
[ntfy.markers] # optional overrides; "" hides a tag
backup = "[B]"
[ntfy] # phase 4
[ntfy.format]
updates = "print" # print | skip: a message replacing one the subscriber printed
[ntfy]
state_dir = "/var/lib/uberbringer"
[[ntfy.subscriptions]]
name = "home"
@@ -270,8 +144,8 @@ GET /healthz (phase 4) adds a field. The HTTP status still depends only on the p
LAYERS (each calls only downward)
- server (Fiber v3 handlers) -> modules (payload to receipt.Job) -> receipt (blocks, layout, render, preview) -> escpos (bytes, code pages, interpreter).
- internal/pkg/ntfy holds the ntfy wire types (phase 3) and the subscriber (phase 4). modules imports it for the Message type. serve.go connects the subscriber to modules through a callback, so ntfy never imports modules.
- printqueue is unchanged apart from Submit(job, Meta).
- internal/pkg/ntfy holds the ntfy wire types (built) and the subscriber (phase 4). modules imports it for the Message type. serve.go connects the subscriber to modules through a callback, so ntfy never imports modules.
- printqueue takes Submit(job, Meta) (built).
INVARIANTS (all match the current code)
1. receipt.Job stays printer-neutral. Blocks are sized at render time from Options.Columns or Profile.Columns(font). The same job therefore prints correctly on a TM-T88IV, TM-T88VII or TM-m50II, and on several printers later.
@@ -283,7 +157,7 @@ INVARIANTS (all match the current code)
- one level of nesting only
3. Layout never fails on a valid job. Widths clamp, titles are cut with "...", and over-long words split the way wrap() already splits them. The only new render-time failure is the [format].max_lines backstop (default 2000).
4. Renderer.Render is still the only path to printer bytes, and still all-or-nothing.
5. New code never emits raw ESC/POS. Payload text only ever lands in string fields of elements. The raw element stays available on /print only, and scoped tokens cannot reach it.
5. New code never emits raw ESC/POS. Payload text only ever lands in string fields of elements. The raw element stays available on /print only, to tokens issued with --raw.
6. /print stays strictly decoded (DisallowUnknownFields). A byte-compatibility test pins today's bytes.
DATA FLOW
@@ -294,101 +168,22 @@ DATA FLOW
- /print/{module}: module.Build(body, Env) -> Validate (a failure here is a module bug, 422) -> Submit(job, Meta{Source: "module:<name>"}).
- Subscriber (phase 4): ntfy stream -> skip, dedupe, filter, rate limit -> modules.FromNtfy -> Card -> Validate -> Submit(job, Meta{Source: "ntfy:<sub>", Ref: <ntfy id>}).
KEY TYPES (new or changed; the escpos interpreter, the blocks, Renderer.Preview and the module layer are built)
KEY TYPES (the blocks, the preview, the module layer, the notification card and the ntfy wire types are built; docs/api.md and design.md describe them)
receipt
Element gains Optional bool on image (phase 3)
func StripEmoji(s string) string (phase 3)
modules (built: Env, Module, ErrSkip, PayloadError, Registry, DecodeStrict, Note; phase 3 adds the rest)
Env gains Card CardOptions
type Notice struct{ ID, Topic, Title, Message string; Markdown bool; Priority int; Tags []string;
Time time.Time; Links []Link; Image string; File *File; Updated bool }
func FromNtfy(m ntfy.Message) (Notice, error) // ErrSkip for non-message events
func Card(n Notice, o CardOptions, env Env) receipt.Job
modules (built)
type Notice; type CardOptions (zero value is the default; Env.Card carries it)
func FromNtfy(m ntfy.Message) (Notice, error) // ErrSkip for non-message events and base64 bodies
func Card(n Notice, o CardOptions, env Env) (receipt.Job, error) // the job always prints; a *FallbackError comes with the plain receipt, for the caller to log and report
ntfy
type Message, Action, Attachment // mirror ntfy model/model.go
func (m Message) Priority() int // 0 or missing becomes 3
type Message, Action, Attachment // built
type Subscriber // phase 4
func (s *Subscriber) Run(ctx context.Context, handle func(context.Context, Message) error) error
printqueue
Submit(job receipt.Job, meta Meta) (Status, error)
type Meta struct{ Source, Ref string }
Status gains Source
printqueue (built)
Submit(job receipt.Job, meta Meta) (Status, error); type Meta struct{ Source, Ref string }; Status.Source
BLOCK LAYOUT (receipt/blocklayout.go and receipt/glyphs.go)
box, rule, kv and list are built; docs/design.md records their rules.
TEXT NORMALIZATION (receipt/normalize.go)
Built: NFC, the fold table and one '?' per emoji sequence on /print. Phase 3 adds StripEmoji for modules: it maps a few typed emoji to markers (⚠ to [!], ✅ to [√], ❌ to [x], 🚨 to (!), 👍 to (+1)), then removes the remaining emoji instead of printing '?'.
NTFY AND NOTIFY CARD (modules/card.go)
The same card is used for /print/notify, /print/ntfy and the subscriber.
Skip
- event other than "message", or encoding = "base64": ErrSkip, which returns 204.
Priority
- A missing or 0 priority counts as 3.
Style ladder (style = auto; box and compact force one form):
- 5: a dark rule "URGENT", a double box, the title row bold and inverted, a double divider, the body, the footer, then another dark rule.
- 4: a double box with "HIGH" in the top border, a bold title row, a single divider, then the body.
- 3: a single box with the bold title set into the top border.
- 1-2: a left-labelled rule "topic · time", then a bold title line and the body, with no box.
Title
- The title; if empty, the topic; if that is empty too, "Notification".
- Up to 2 tag markers go in front of it.
- " (updated)" goes after it when sequence_id differs from id. With updates = skip, such messages are not printed.
Tag markers (exact lowercase match)
- warning → [!]
- rotating_light, fire, boom → (!)
- white_check_mark, heavy_check_mark, ballot_box_with_check → [√]
- x, negative_squared_cross_mark, no_entry, no_entry_sign → [x]
- information_source → (i)
- question → (?)
- +1, thumbsup → (+1)
- -1, thumbsdown → (-1)
- loudspeaker, mega → <!>
- tada → \o/
- skull → x_x
- hourglass → (...)
[ntfy.markers] in the config can override any marker, and "" hides a tag. Any other tag prints as text on a "Tags: a, b" row.
Body
- The message, with the markdown subset applied when content_type is text/markdown (or markdown: true on notify):
- #, ## and ### headings → bold lines
- - * + items → · list
- 1. items → numbered list
- > quotes → a "│ " prefix
- ``` fences → printed as written
- --- → a divider
- inline ** __ * _ ` ~~ → removed
- [t](u) → t, with u added to the links
- ![a](u) → [image: a]
- The body is capped at [ntfy.format].max_lines (default 40), followed by "... N more lines".
- The "You received a file: X" placeholder becomes a "File" row.
Footer
- "<topic> · <time>", using [format].timezone and time_layout (default "02 Jan 15:04").
Links
- The links are the click URL plus view actions (http or https), with duplicates removed, at most 3.
- qr = all (default): every link prints as a centred QR code (size 5, correction M) with a Font B caption, the action's label or else host/path.
- qr = first prints only the first link as a QR code and the others as "» label" plus the URL; qr = none prints them all as text.
- http, broadcast and copy actions are never printed, because their headers and body can hold secrets.
Attachments
- An image (type image/*, or a .png, .jpg, .jpeg, .gif or .webp name) that has not expired, with images = true: an image element with optional:true, 384 dots wide, centred. The renderer fetches it through safehttp.
- Otherwise: a kv row such as "File ... name (33 KB)".
- icon is ignored.
Failures
- Card never fails. Any internal error produces the plain fallback receipt: title, message, topic and time.
The subscriber marks and skips updates itself (Dedupe and state below); Card prints the notice it is given.
SUBSCRIBER (phase 4, internal/pkg/ntfy)
@@ -405,6 +200,7 @@ Cursor
Dedupe and state
- A ring of the last 512 ids is persisted. It drops ntfy 2.31+ same-second repeats and the overlap after a reconnect.
- Updates: the sequence IDs of printed messages are remembered with the ids. A message whose sequence was printed before sets Notice.Updated, so its card shows "(updated)", or with updates = "skip" it is left out. The module routes print every message plain (design.md).
- State is JSON in state_dir, written as temp file, then fsync, then rename. It is written at most once a second, and on shutdown.
Reconnects
@@ -431,94 +227,6 @@ Images and logging
## Phases
### Phase 3: Notifications, the notify and ntfy modules (3 days)
**Goal.** ntfy prints with minimal effort. The ntfy CLI posts $NTFY_RAW unchanged, and scripts can send {title, message, priority, tags}. Both print the same priority-styled card. Integration tokens can't send raw ESC/POS.
**Work.**
internal/pkg/ntfy (new)
- message.go: Message, Action and Attachment, following ntfy model.go, plus Priority().
internal/pkg/modules
- notice.go: the Notice type. Priority names min, low, default, high, max and urgent map to 1-5.
- notify.go: strict decode with DecodeStrict into a Notice.
- notify and ntfy are registered in newModules (internal/app/uberbringer/modules.go).
- ntfy.go: lenient decode into ntfy.Message, then FromNtfy into a Notice. It returns ErrSkip for events other than message and for encoding=base64.
- card.go: Card(Notice, CardOptions, Env) builds the receipt.Job using the priority ladder, title and markers, body cap, footer, links and QR, the attachment image or File row, and the updates policy.
- markers.go: the tag and typed-emoji marker table, merged with the [ntfy.markers] overrides, then StripEmoji.
- markdown.go: the line-level subset described in the architecture section, about 150 lines, with no new dependency.
- fallback.go: a plain receipt (title, message, topic, time). Card falls back to it on any internal error.
internal/pkg/receipt
- image `optional`: loadImages returns a placeholder for an optional image that fails, and the renderer prints "[image unavailable]".
- StripEmoji is exported.
internal/pkg/printqueue
- Submit(job, Meta{Source, Ref}).
- Status.Source.
- Source and ref are added to the worker logs.
- The caller in server is updated: the Jobs interface and s.submit, which /print and the module routes share; module routes pass Meta{Source: "module:<name>"}.
internal/app/uberbringer/server
- auth.go: parse the optional "mod" claim and enforce the allowed routes, returning 403 otherwise.
- handleJob: shows source.
internal/app/uberbringer
- cli.go: `token --modules ntfy,notify`.
internal/pkg/config
- [ntfy.format] (style, max_lines, qr, images, markdown, updates) and [ntfy.markers], with validation.
Docs
- docs/api.md: notify and ntfy sections under § Modules, the ntfy CLI recipe for Linux client.yml and Windows PowerShell, token scopes and their 403 code, and a warning that public ntfy.sh topics can be guessed.
- README: `token --modules` under Command line and [ntfy.format] and [ntfy.markers] under Configuration. Update configs/config.example.toml.
**Tests.**
internal/pkg/modules
- Card golden previews:
- priorities 1-5 × style auto, box and compact (mockups 1-4)
- the brief's example message rendered exactly
- Markers: built-in table, a config override, hiding a tag with "", and the unmapped tag row.
- Markdown subset golden tests, plus FuzzMarkdown: no panic, and every line fits.
- FromNtfy table:
- unknown fields ignored
- priority 0 or missing becomes 3
- missing title falls back to the topic
- the 'You received a file' placeholder becomes a File row
- an image attachment becomes an optional image; an expired one becomes a File row
- an attachment with no type is sniffed by extension
- sequence_id gives "(updated)", or a skip with updates=skip
- non-message and base64 events give ErrSkip
- http, broadcast and copy actions never print: assert their URL, header and body strings appear nowhere in the preview.
- A body longer than max_lines gives '... N more lines'.
- Typed ⚠ becomes [!], and other emoji are stripped.
- Links: deduped, at most 3; qr=first, all and none.
- notify: strict decode errors.
- Fallback: Card with a forced internal error still returns a valid job.
internal/pkg/receipt
- An optional image that fails prints the placeholder, while a non-optional failure still fails the whole job and produces nothing.
internal/app/uberbringer/server
- Scoped token:
- 202 on /print/ntfy
- 403 on /print and /print/note
- 200 on GET /jobs/{id}
- An unscoped token is unchanged.
- 204 for a keepalive body.
internal/pkg/printqueue
- Meta appears in Status.
**Done when.**
- On the owner's machine, the ntfy CLI recipe prints mockup 1 for the brief's example message and mockups 2-4 for priority 5, 3 and 1.
- /api/v1/preview/ntfy and `uberbringer preview --module ntfy` show the same output.
- A token from `uberbringer token --modules ntfy` gets 403 on /api/v1/print.
- The full gate passes (CLAUDE.md lists it).
### Phase 4: Built-in ntfy subscriber (5 days)
**Goal.** No client code and no extra programs: add [[ntfy.subscriptions]] to the config and the phone's ntfy app becomes the only client. Restarts and outages must not lose a flood's worth of paper or reprint old messages, and nothing but urgent messages prints during quiet hours.
+67 -3
View File
@@ -150,6 +150,10 @@
"description": "newline false keeps the next element on the same line. Default true.",
"type": "boolean"
},
"optional": {
"description": "optional prints the line [image unavailable] in place of an image that cannot be fetched or decoded, instead of failing the whole job, and shrinks an image whose width is wider than the paper to it.",
"type": "boolean"
},
"padding": {
"description": "padding is the spaces between a box's side borders and its body, 0-3. Default 1.",
"maximum": 3,
@@ -166,7 +170,7 @@
"type": "array"
},
"size": {
"description": "size sets width and height together: 1-8 for text, 1-3 for a block, whose borders scale with its text. For a QR code it is the module size in dots, 1-16, default 6. 0 means the default.",
"description": "size sets width and height together: 1-8 for text, 1-3 for a block, whose borders scale with its text. For a QR code it is the module size in dots, 1-16, default 6, made smaller for a code that could be wider than the paper, its width worked out as if its data were bytes. 0 means the default.",
"maximum": 16,
"minimum": 0,
"type": "integer"
@@ -208,6 +212,10 @@
"description": "title is text set into a box's top border.",
"type": "string"
},
"title_bold": {
"description": "title_bold prints a box's title bold.",
"type": "boolean"
},
"title_style": {
"description": "title_style is inline, the default, or capped.",
"enum": [
@@ -398,6 +406,10 @@
"pattern": "^job_[0-7][0-9a-hjkmnp-tv-z]{25}$",
"type": "string"
},
"source": {
"description": "source says where the job came from: print for POST /api/v1/print, or module:<name> for a module route, e.g. module:ntfy.",
"type": "string"
},
"started_at": {
"description": "started_at is when the worker took the job.",
"format": "date-time",
@@ -995,6 +1007,19 @@
"unauthorized"
]
},
"403": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Forbidden. token_scope: the token does not allow this request.",
"x-uberbringer-codes": [
"token_scope"
]
},
"413": {
"content": {
"application/json": {
@@ -1166,6 +1191,19 @@
"unauthorized"
]
},
"403": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Forbidden. token_scope: the token does not allow this request.",
"x-uberbringer-codes": [
"token_scope"
]
},
"404": {
"content": {
"application/json": {
@@ -1255,7 +1293,7 @@
},
"/api/v1/print": {
"post": {
"description": "Validates the whole job and queues it. The worker renders it in full before anything is sent to the printer, and fetches its images then, so a broken image URL shows up as a failed job.",
"description": "Validates the whole job and queues it. The worker renders it in full before anything is sent to the printer, and fetches its images then, so a broken image URL shows up as a failed job. A job with raw elements needs a token issued with uberbringer token --raw, and a token limited to modules cannot use this route.",
"operationId": "printJob",
"requestBody": {
"content": {
@@ -1320,6 +1358,19 @@
"unauthorized"
]
},
"403": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Forbidden. token_scope: the token does not allow this request.",
"x-uberbringer-codes": [
"token_scope"
]
},
"413": {
"content": {
"application/json": {
@@ -1405,7 +1456,7 @@
},
"/api/v1/print/{module}": {
"post": {
"description": "The module named in the path builds a receipt from the body, its own payload, which is decoded strictly: an unknown field or one of the wrong type is refused, with every problem listed. The receipt is then validated and queued as on /api/v1/print. A module with nothing to print answers 204.",
"description": "The module named in the path builds a receipt from the body, its own payload. note and notify decode it strictly: an unknown field or one of the wrong type is refused, with every problem listed; ntfy ignores the fields it does not know. The receipt is then validated and queued as on /api/v1/print. A module with nothing to print answers 204. A token limited to modules (uberbringer token --modules) may use only the modules it names.",
"operationId": "printModule",
"parameters": [
{
@@ -1504,6 +1555,19 @@
"unauthorized"
]
},
"403": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Forbidden. token_scope: the token does not allow this request.",
"x-uberbringer-codes": [
"token_scope"
]
},
"404": {
"content": {
"application/json": {
+77 -16
View File
@@ -9,6 +9,7 @@ import (
"fmt"
"io"
"os"
"slices"
"strings"
"time"
@@ -16,6 +17,7 @@ import (
"github.com/liamg/tml"
"github.com/spf13/cobra"
"uberbringer/internal/app/uberbringer/server"
"uberbringer/internal/pkg/config"
)
@@ -140,20 +142,24 @@ func newSecretCommand() *cobra.Command {
}
func newTokenCommand(configPath *string) *cobra.Command {
var (
subject string
ttl time.Duration
)
var spec tokenSpec
cmd := &cobra.Command{
Use: "token",
Short: "Prints a bearer token signed with the config's api.secret.",
Args: cobra.NoArgs,
Long: "Prints a bearer token signed with the config's api.secret. A token may use every\n" +
"route except that only one issued with --raw prints jobs with raw ESC/POS elements.\n" +
"With --modules, the token may only print and preview through those modules and\n" +
"read job status and the module list: give integrations such as ntfy one of these.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
if err := spec.check(cmd.Flags().Changed("modules")); err != nil {
return err
}
cfg, err := config.Load(*configPath)
if err != nil {
return err
}
token, err := signToken([]byte(cfg.API.Secret), subject, ttl, time.Now())
token, err := signToken([]byte(cfg.API.Secret), spec, time.Now())
if err != nil {
return err
}
@@ -161,11 +167,62 @@ func newTokenCommand(configPath *string) *cobra.Command {
return err
},
}
cmd.Flags().StringVar(&subject, "subject", "uberbringer", "token subject, e.g. the client's name")
cmd.Flags().DurationVar(&ttl, "ttl", 0, "token lifetime, e.g. 720h (0 means it never expires)")
cmd.Flags().StringVar(&spec.subject, "subject", "uberbringer", "token subject, e.g. the client's name")
cmd.Flags().DurationVar(&spec.ttl, "ttl", 0, "token lifetime, e.g. 720h (0 means it never expires)")
cmd.Flags().StringSliceVar(&spec.modules, "modules", nil,
"limit the token to these modules' routes, e.g. ntfy,notify")
cmd.Flags().BoolVar(&spec.raw, "raw", false, "let the token print jobs with raw ESC/POS elements")
return cmd
}
// tokenSpec is what a token is issued for.
type tokenSpec struct {
subject string
// ttl is the token's lifetime; zero means no expiry.
ttl time.Duration
// modules, when not nil, limits the token to these modules' routes.
modules []string
// raw lets the token print raw ESC/POS.
raw bool
}
// check refuses a spec the daemon could not honour. limited is set when
// --modules was given, even with no names.
func (s *tokenSpec) check(limited bool) error {
if !limited {
return nil
}
if s.raw {
return fmt.Errorf("--raw does nothing with --modules: a token limited to modules cannot reach /api/v1/print")
}
registry, err := newModules()
if err != nil {
return err
}
var names []string
for _, info := range registry.List() {
names = append(names, info.Name)
}
var modules []string
for _, name := range s.modules {
name = strings.TrimSpace(name)
if _, ok := registry.Get(name); !ok {
return fmt.Errorf("--modules: unknown module %q; the modules are: %s", name, strings.Join(names, ", "))
}
if !slices.Contains(modules, name) {
modules = append(modules, name)
}
}
if len(modules) == 0 {
return fmt.Errorf("--modules needs at least one module: %s", strings.Join(names, ", "))
}
s.modules = modules
return nil
}
// newSecret returns a random base64 API secret. crypto/rand.Read never fails
// on supported platforms; it crashes the program rather than return weak bytes.
func newSecret() string {
@@ -174,17 +231,21 @@ func newSecret() string {
return base64.StdEncoding.EncodeToString(b)
}
// signToken returns an HS256 JWT for subject. A zero ttl means no expiry.
func signToken(secret []byte, subject string, ttl time.Duration, now time.Time) (string, error) {
if ttl < 0 {
// signToken returns an HS256 JWT issued at now for spec.
func signToken(secret []byte, spec tokenSpec, now time.Time) (string, error) {
if spec.ttl < 0 {
return "", fmt.Errorf("ttl must not be negative")
}
claims := jwt.RegisteredClaims{
Subject: subject,
IssuedAt: jwt.NewNumericDate(now),
claims := server.TokenClaims{
RegisteredClaims: jwt.RegisteredClaims{
Subject: spec.subject,
IssuedAt: jwt.NewNumericDate(now),
},
Modules: spec.modules,
Raw: spec.raw,
}
if ttl > 0 {
claims.ExpiresAt = jwt.NewNumericDate(now.Add(ttl))
if spec.ttl > 0 {
claims.ExpiresAt = jwt.NewNumericDate(now.Add(spec.ttl))
}
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret)
if err != nil {
+59 -1
View File
@@ -10,6 +10,8 @@ import (
"time"
"github.com/golang-jwt/jwt/v5"
"uberbringer/internal/app/uberbringer/server"
)
func runCommand(t *testing.T, args ...string) (string, error) {
@@ -120,8 +122,64 @@ func TestTokenCommand(t *testing.T) {
}
}
func TestTokenCommandScopes(t *testing.T) {
secret := "env-only-secret-env-only-secret-0123"
t.Setenv("UBERBRINGER_API_SECRET", secret)
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "192.168.1.245")
parse := func(t *testing.T, out string) server.TokenClaims {
t.Helper()
var claims server.TokenClaims
_, err := jwt.ParseWithClaims(strings.TrimSpace(out), &claims, func(*jwt.Token) (any, error) { return []byte(secret), nil },
jwt.WithValidMethods([]string{"HS256"}))
if err != nil {
t.Fatal(err)
}
return claims
}
tests := []struct {
args []string
modules []string
raw bool
}{
{nil, nil, false},
{[]string{"--modules", "ntfy,notify"}, []string{"ntfy", "notify"}, false},
{[]string{"--modules", "ntfy", "--modules", " ntfy , note"}, []string{"ntfy", "note"}, false},
{[]string{"--raw"}, nil, true},
}
for _, tt := range tests {
out, err := runCommand(t, append([]string{"token", "--config", ""}, tt.args...)...)
if err != nil {
t.Errorf("%v: %v", tt.args, err)
continue
}
claims := parse(t, out)
if strings.Join(claims.Modules, ",") != strings.Join(tt.modules, ",") || (claims.Modules == nil) != (tt.modules == nil) || claims.Raw != tt.raw {
t.Errorf("%v: claims mod %q raw %v, want %q and %v", tt.args, claims.Modules, claims.Raw, tt.modules, tt.raw)
}
}
refused := []struct {
args []string
wantErr string
}{
{[]string{"--modules", "ntfy,pager"}, `--modules: unknown module "pager"; the modules are: note, notify, ntfy`},
{[]string{"--modules", ""}, "--modules needs at least one module: note, notify, ntfy"},
{[]string{"--modules", "ntfy", "--raw"}, "--raw does nothing with --modules"},
}
for _, tt := range refused {
out, err := runCommand(t, append([]string{"token", "--config", ""}, tt.args...)...)
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("%v: error %v, want it to contain %q", tt.args, err, tt.wantErr)
}
if strings.Count(out, ".") >= 2 {
t.Errorf("%v: printed a token", tt.args)
}
}
}
func TestTokenCommandNoExpiryByDefault(t *testing.T) {
token, err := signToken([]byte("0123456789abcdef0123456789abcdef"), "x", 0, time.Now())
token, err := signToken([]byte("0123456789abcdef0123456789abcdef"), tokenSpec{subject: "x"}, time.Now())
if err != nil {
t.Fatal(err)
}
+17 -3
View File
@@ -10,18 +10,32 @@ import (
// newModules returns the registry of every module the daemon offers.
func newModules() (*modules.Registry, error) {
return modules.NewRegistry(modules.Note())
return modules.NewRegistry(modules.Note(), modules.Notify(), modules.Ntfy())
}
// moduleEnv returns a func that gives modules the time now, in the zone and
// layout cfg's [format] names.
// layout cfg's [format] names, and the card options of its [ntfy] tables.
func moduleEnv(cfg *config.Config) (func() modules.Env, error) {
loc, err := time.LoadLocation(cfg.Format.Timezone)
if err != nil {
return nil, fmt.Errorf("config format.timezone: %w", err)
}
layout := cfg.Format.TimeLayout
card := cardOptions(cfg.Ntfy)
return func() modules.Env {
return modules.Env{Now: time.Now(), Location: loc, TimeLayout: layout}
return modules.Env{Now: time.Now(), Location: loc, TimeLayout: layout, Card: card}
}, nil
}
// cardOptions returns the notification layout cfg describes.
func cardOptions(cfg config.NtfyConfig) modules.CardOptions {
f := cfg.Format
return modules.CardOptions{
Style: f.Style,
MaxLines: f.MaxLines,
QR: f.QR,
NoImages: !f.Images,
NoMarkdown: !f.Markdown,
Markers: modules.NewMarkers(cfg.Markers),
}
}
+16 -3
View File
@@ -67,7 +67,14 @@ func readJobInput(stdin io.Reader, args []string) ([]byte, error) {
// With a module name, data is that module's payload.
func preview(ctx context.Context, cfg *config.Config, data []byte, module string, out, errOut io.Writer, styled bool) error {
job, ok, err := previewJob(ctx, cfg, data, module)
if err != nil {
var fallbackErr *modules.FallbackError
switch {
case errors.As(err, &fallbackErr):
// The plain receipt is still shown, as it would print.
if _, err := fmt.Fprintf(errOut, "warning: module %s: %v\n", module, fallbackErr); err != nil {
return err
}
case err != nil:
return err
}
if !ok {
@@ -101,7 +108,8 @@ func preview(ctx context.Context, cfg *config.Config, data []byte, module string
// previewJob returns the job to preview: data itself, or with a module name,
// the job that module builds from data as its payload, at the time now. ok
// is false when the module has nothing to print.
// is false when the module has nothing to print. A *FallbackError comes
// with the job that prints in its place.
func previewJob(ctx context.Context, cfg *config.Config, data []byte, module string) (job receipt.Job, ok bool, err error) {
if module == "" {
job, err := receipt.DecodeJob(data)
@@ -127,12 +135,17 @@ func previewJob(ctx context.Context, cfg *config.Config, data []byte, module str
return job, false, err
}
job, err = m.Build(ctx, data, env())
var pe *modules.PayloadError
var (
pe *modules.PayloadError
fe *modules.FallbackError
)
switch {
case errors.Is(err, modules.ErrSkip):
return job, false, nil
case errors.As(err, &pe):
return job, false, fmt.Errorf("invalid payload for module %q:\n %s", module, strings.Join(pe.Problems, "\n "))
case errors.As(err, &fe):
return job, true, err
case err != nil:
return job, false, fmt.Errorf("module %s: %w", module, err)
}
+70 -1
View File
@@ -135,6 +135,75 @@ func TestPreviewCommandModule(t *testing.T) {
}
}
// urgentNtfy is an ntfy message of priority 5, with the time it was sent.
const urgentNtfy = `{"id":"Fb2xQm81kTz0","time":1764450245,"event":"message","topic":"backups",` +
`"title":"Backup FAILED on nas01","message":"Job nightly-offsite exited with code 2 after 3h12m. ` +
`Last good run: 2 days ago.","priority":5,"tags":["rotating_light","nas01"]}`
// The ntfy module previews as the server's /api/v1/preview/ntfy does, with
// the [ntfy] tables of the config applied.
func TestPreviewCommandNtfy(t *testing.T) {
tests := []struct {
name, config string
want []string
}{
{"defaults", "[format]\ntimezone = \"UTC\"\n", []string{
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
"╔════════════════════════════════════════╗",
"║ (!) Backup FAILED on nas01 ║",
"╠════════════════════════════════════════╣",
"║ Job nightly-offsite exited with code 2 ║",
"║ after 3h12m. Last good run: 2 days ║",
"║ ago. ║",
"║ ║",
"║ Tags: nas01 ║",
"╚══════════════ backups · 29 Nov 21:04 ══╝",
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
" - - - - - - - partial cut - - - - - - - -",
}},
{"compact, with markers", "[format]\ntimezone = \"UTC\"\n[ntfy.format]\nstyle = \"compact\"\n" +
"[ntfy.markers]\nrotating_light = \"/!\\\\\"\nnas01 = \"\"\n", []string{
"── URGENT · backups · 29 Nov 21:04 ───────",
"/!\\ Backup FAILED on nas01",
"Job nightly-offsite exited with code 2",
"after 3h12m. Last good run: 2 days ago.",
" - - - - - - - partial cut - - - - - - - -",
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := newRootCommand(BuildInfo{})
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
cmd.SetIn(strings.NewReader(urgentNtfy))
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, tt.config), "--module", "ntfy"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
want := strings.Join(tt.want, "\n") + "\n"
if out.String() != want || errOut.Len() != 0 {
t.Errorf("output:\n%s\nwant:\n%s\nstandard error: %q", out.String(), want, errOut.String())
}
})
}
t.Run("keepalive", func(t *testing.T) {
cmd := newRootCommand(BuildInfo{})
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
cmd.SetIn(strings.NewReader(`{"id":"x","time":1764450245,"event":"keepalive","topic":"backups"}`))
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, ""), "--module", "ntfy"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if out.Len() != 0 || errOut.String() != "module ntfy has nothing to print\n" {
t.Errorf("output %q, standard error %q", out.String(), errOut.String())
}
})
}
// The note's stamp is the time now in format.timezone and time_layout.
func TestPreviewCommandModuleStamp(t *testing.T) {
cmd := newRootCommand(BuildInfo{})
@@ -157,7 +226,7 @@ func TestPreviewCommandModuleErrors(t *testing.T) {
tests := []struct {
name, module, payload, want string
}{
{"unknown module", "notx", `{}`, `unknown module "notx"; the modules are: note`},
{"unknown module", "notx", `{}`, `unknown module "notx"; the modules are: note, notify, ntfy`},
{"invalid payload", "note", `{"title":"x","items":["a"],"done":[1,2]}`,
"invalid payload for module \"note\":\n text: required\n done[0]: index 1 is out of range\n done[1]: index 2 is out of range"},
{"not an object", "note", `[]`, "invalid payload for module \"note\":\n body: expected a JSON object, got array"},
+1 -1
View File
@@ -103,7 +103,7 @@ level = "error"
return resp.StatusCode == http.StatusOK
})
token, err := signToken([]byte(secret), "test", 0, time.Now())
token, err := signToken([]byte(secret), tokenSpec{subject: "test"}, time.Now())
if err != nil {
t.Fatal(err)
}
+125 -4
View File
@@ -1,15 +1,88 @@
package server
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"github.com/gofiber/fiber/v3"
"github.com/golang-jwt/jwt/v5"
"uberbringer/internal/pkg/receipt"
)
// requireBearerToken rejects requests without a valid HS256 bearer token.
// Tokens are only read from the Authorization header: query-string tokens
// end up in proxy and access logs.
// TokenClaims are the claims of a bearer token that Überbringer reads.
// Claims other than these, such as user_id, are ignored.
type TokenClaims struct {
jwt.RegisteredClaims
// Modules, when present, limits the token to the routes of these
// modules, job status and the module list.
Modules []string `json:"mod,omitempty"`
// Raw lets the token print jobs with raw elements.
Raw bool `json:"raw,omitempty"`
}
// scopeClaims are the claims that set what a token may do.
var scopeClaims = []string{"mod", "raw"}
// UnmarshalJSON decodes the claims and refuses a scope claim that could be
// read as absent: mod given as null, and a scope claim written in another
// letter case, which encoding/json would match too.
func (c *TokenClaims) UnmarshalJSON(data []byte) error {
var fields map[string]json.RawMessage
if err := json.Unmarshal(data, &fields); err != nil {
return err
}
for name := range fields {
for _, claim := range scopeClaims {
if name != claim && strings.EqualFold(name, claim) {
return fmt.Errorf("claim %q: the %q claim is written in lower case", name, claim)
}
}
}
if mod, ok := fields["mod"]; ok && string(bytes.TrimSpace(mod)) == "null" {
return errors.New(`claim "mod" is null`)
}
type claims TokenClaims // without this method, so that it decodes as a plain struct
return json.Unmarshal(data, (*claims)(c))
}
// tokenScope is what the request's token allows.
type tokenScope struct {
// limited is set for a token with a mod claim, which may use only the
// routes of modules.
limited bool
modules []string
// raw is set for a token that may print raw ESC/POS.
raw bool
}
// tokenScopeKey stores the request's tokenScope in fiber Locals.
type tokenScopeKey struct{}
// routeScope says which tokens limited to modules may use a route.
type routeScope int
const (
// scopeFull routes take only tokens without a mod claim.
scopeFull routeScope = iota
// scopeAny routes take every valid token.
scopeAny
// scopeModule routes take a token whose mod claim names the module in
// the path, and tokens without one.
scopeModule
)
// requireBearerToken rejects requests without a valid HS256 bearer token,
// and keeps what the token allows for the routes to check. Tokens are only
// read from the Authorization header: query-string tokens end up in proxy
// and access logs.
func requireBearerToken(secret []byte) fiber.Handler {
parser := jwt.NewParser(jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
keyFunc := func(*jwt.Token) (any, error) { return secret, nil }
@@ -20,14 +93,62 @@ func requireBearerToken(secret []byte) fiber.Handler {
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer"`)
return newAPIError(codeUnauthorized.withMessage("missing bearer token"))
}
if _, err := parser.Parse(token, keyFunc); err != nil {
var claims TokenClaims
if _, err := parser.ParseWithClaims(token, &claims, keyFunc); err != nil {
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer", error="invalid_token"`)
return newAPIError(codeUnauthorized.withMessage("invalid or expired token"))
}
c.Locals(tokenScopeKey{}, tokenScope{limited: claims.Modules != nil, modules: claims.Modules, raw: claims.Raw})
return c.Next()
}
}
// scopeFrom returns what the request's token allows. A request that
// passed no token check allows nothing.
func scopeFrom(c fiber.Ctx) tokenScope {
scope, ok := c.Locals(tokenScopeKey{}).(tokenScope)
if !ok {
return tokenScope{limited: true}
}
return scope
}
// checkScope refuses a token limited to modules on a route its scope does
// not include.
func checkScope(c fiber.Ctx, route routeScope) error {
scope := scopeFrom(c)
if !scope.limited || route == scopeAny {
return nil
}
if route == scopeModule && slices.Contains(scope.modules, c.Params("module")) {
return nil
}
msg := "token is limited to job status and the module list"
if len(scope.modules) > 0 {
msg = "token is limited to modules " + strings.Join(scope.modules, ", ")
}
return newAPIError(codeTokenScope.withMessage(msg))
}
// checkRaw refuses a job with raw elements unless the token may print raw
// ESC/POS. The details name the raw elements.
func checkRaw(c fiber.Ctx, job receipt.Job) error {
if scopeFrom(c).raw {
return nil
}
var raw []string
for i, el := range job.Elements {
if el.Type == receipt.TypeRaw {
raw = append(raw, fmt.Sprintf("elements[%d] (raw)", i))
}
}
if len(raw) == 0 {
return nil
}
msg := "token may not print raw ESC/POS; issue one with uberbringer token --raw"
return newAPIError(codeTokenScope.withMessage(msg), raw...)
}
// bearerToken extracts the token from an Authorization header value. The
// scheme is case-insensitive (RFC 7235).
func bearerToken(header string) (string, bool) {
@@ -0,0 +1,250 @@
package server
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/golang-jwt/jwt/v5"
"uberbringer/internal/pkg/printqueue"
)
// ntfyMessage is an ntfy message as the ntfy command line client passes it
// in $NTFY_RAW.
const ntfyMessage = `{"id":"sPs71M8A2Tq9","time":1764450245,"event":"message","topic":"alerts","title":"Disk almost full",` +
`"message":"/var is at 94% on nas01","priority":4,"tags":["warning","nas01"]}`
// rawJob is a job with a raw element.
const rawJob = `{"elements":[{"type":"text","text":"Hello"},{"type":"raw","hex":"1B 61 01"}]}`
// tokenWith returns a token with claims.
func tokenWith(t *testing.T, claims jwt.MapClaims) string {
t.Helper()
return token(t, testSecret, jwt.SigningMethodHS256, claims)
}
// request returns a request to target with the token, and with body when
// it is not empty.
func request(t *testing.T, method, target, body, tok string) *http.Request {
t.Helper()
req := httptest.NewRequest(method, target, strings.NewReader(body))
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Authorization", "Bearer "+tok)
return req
}
func TestScopedToken(t *testing.T) {
id := newJobID(t)
ntfyOnly := tokenWith(t, jwt.MapClaims{"sub": "ntfy-cli", "mod": []string{"ntfy", "notify"}})
tests := []struct {
name, method, target, body string
status int
code, message string
}{
{"print through ntfy", http.MethodPost, "/api/v1/print/ntfy", ntfyMessage, http.StatusAccepted, "", ""},
{"print through notify", http.MethodPost, "/api/v1/print/notify", `{"message":"Back at 3"}`, http.StatusAccepted, "", ""},
{"preview through ntfy", http.MethodPost, "/api/v1/preview/ntfy", ntfyMessage, http.StatusOK, "", ""},
{"keepalive", http.MethodPost, "/api/v1/print/ntfy", `{"id":"x","time":1764450245,"event":"keepalive","topic":"alerts"}`,
http.StatusNoContent, "", ""},
{"job status", http.MethodGet, "/api/v1/jobs/" + id.String(), "", http.StatusOK, "", ""},
{"module list", http.MethodGet, "/api/v1/modules", "", http.StatusOK, "", ""},
{"print", http.MethodPost, "/api/v1/print", validJob, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
{"preview", http.MethodPost, "/api/v1/preview", validJob, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
{"another module", http.MethodPost, "/api/v1/print/note", shoppingNote, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
{"another module's preview", http.MethodPost, "/api/v1/preview/note", shoppingNote, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
{"an unknown module", http.MethodPost, "/api/v1/print/notx", `{}`, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t), statuses: map[printqueue.JobID]printqueue.Status{
id: {ID: id, State: printqueue.StateDone, Source: "module:ntfy"},
}}
s := newTestServer(t, jobs, &fakePrinter{})
resp, body := send(t, s, request(t, tt.method, tt.target, tt.body, ntfyOnly))
if tt.code != "" {
e := expectError(t, resp, body, tt.status, tt.code)
if e.Error != tt.message {
t.Errorf("error %q, want %q", e.Error, tt.message)
}
if len(jobs.submitted) != 0 {
t.Error("a refused job was queued")
}
return
}
if resp.StatusCode != tt.status {
t.Fatalf("status = %d, want %d (%s)", resp.StatusCode, tt.status, body)
}
})
}
t.Run("the queued job's source", func(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, &fakePrinter{})
if resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print/ntfy", ntfyMessage, ntfyOnly)); resp.StatusCode != http.StatusAccepted {
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
}
if len(jobs.metas) != 1 || jobs.metas[0] != (printqueue.Meta{Source: "module:ntfy", Ref: "req_test"}) {
t.Errorf("meta %+v", jobs.metas)
}
})
t.Run("no modules", func(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print/ntfy", ntfyMessage, tokenWith(t, jwt.MapClaims{"mod": []string{}})))
if e := expectError(t, resp, body, http.StatusForbidden, "token_scope"); e.Error != "token is limited to job status and the module list" {
t.Errorf("error %q", e.Error)
}
})
}
// A token without a mod claim keeps every route, and a module route
// records its module as the job's source.
func TestUnscopedToken(t *testing.T) {
for _, tt := range []struct{ target, body, source string }{
{"/api/v1/print", validJob, "print"},
{"/api/v1/print/note", shoppingNote, "module:note"},
{"/api/v1/print/ntfy", ntfyMessage, "module:ntfy"},
} {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, &fakePrinter{})
resp, body := send(t, s, request(t, http.MethodPost, tt.target, tt.body, validToken(t)))
if resp.StatusCode != http.StatusAccepted {
t.Errorf("%s: status = %d (%s)", tt.target, resp.StatusCode, body)
continue
}
if len(jobs.metas) != 1 || jobs.metas[0] != (printqueue.Meta{Source: tt.source, Ref: "req_test"}) {
t.Errorf("%s: meta %+v", tt.target, jobs.metas)
}
}
}
func TestRawNeedsRawToken(t *testing.T) {
tests := []struct {
name string
claims jwt.MapClaims
target string
status int
}{
{"a token without raw", jwt.MapClaims{"user_id": "uberbringer"}, "/api/v1/print", http.StatusForbidden},
{"raw false", jwt.MapClaims{"raw": false}, "/api/v1/print", http.StatusForbidden},
{"raw true", jwt.MapClaims{"raw": true}, "/api/v1/print", http.StatusAccepted},
{"a preview", jwt.MapClaims{"user_id": "uberbringer"}, "/api/v1/preview", http.StatusOK},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, &fakePrinter{})
resp, body := send(t, s, request(t, http.MethodPost, tt.target, rawJob, tokenWith(t, tt.claims)))
if tt.status != http.StatusForbidden {
if resp.StatusCode != tt.status {
t.Fatalf("status = %d, want %d (%s)", resp.StatusCode, tt.status, body)
}
return
}
e := expectError(t, resp, body, http.StatusForbidden, "token_scope")
if e.Error != "token may not print raw ESC/POS; issue one with uberbringer token --raw" ||
strings.Join(e.Details, ";") != "elements[1] (raw)" {
t.Errorf("error %+v", e)
}
if len(jobs.submitted) != 0 {
t.Error("the job was queued")
}
})
}
t.Run("an invalid job is refused as invalid first", func(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print", `{"elements":[{"type":"raw"}]}`, validToken(t)))
expectError(t, resp, body, http.StatusBadRequest, "invalid_job")
})
}
// /api/v1/preview/ntfy shows the card the command line's preview --module
// ntfy shows for the same message.
func TestPreviewNtfy(t *testing.T) {
message := `{"id":"Fb2xQm81kTz0","time":1764450245,"event":"message","topic":"backups",` +
`"title":"Backup FAILED on nas01","message":"Job nightly-offsite exited with code 2 after 3h12m. ` +
`Last good run: 2 days ago.","priority":5,"tags":["rotating_light","nas01"]}`
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/preview/ntfy", message, validToken(t)))
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
}
want := strings.Join([]string{
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
"╔════════════════════════════════════════╗",
"║ (!) Backup FAILED on nas01 ║",
"╠════════════════════════════════════════╣",
"║ Job nightly-offsite exited with code 2 ║",
"║ after 3h12m. Last good run: 2 days ║",
"║ ago. ║",
"║ ║",
"║ Tags: nas01 ║",
"╚══════════════ backups · 29 Nov 21:04 ══╝",
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
" - - - - - - - partial cut - - - - - - - -",
}, "\n") + "\n"
if string(body) != want {
t.Errorf("preview:\n%s\nwant:\n%s", body, want)
}
}
// Claims of the wrong type make the token invalid rather than unscoped.
func TestMalformedScopeClaims(t *testing.T) {
payloads := []string{
`{"mod":"ntfy"}`,
`{"mod":[1]}`,
`{"raw":"yes"}`,
`{"mod":null}`,
`{"mod":["ntfy"],"Mod":null}`,
`{"MOD":["ntfy"]}`,
`{"Raw":true}`,
`{"mod":["ntfy"],"mod":null}`,
}
for _, payload := range payloads {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print", validJob, signedPayload(t, payload)))
if resp.StatusCode != http.StatusUnauthorized {
t.Errorf("%s: status %d, want 401 (%s)", payload, resp.StatusCode, body)
}
}
}
// signedPayload returns an HS256 token with payload, as written, for its
// claims: unlike a claims value, it can repeat a name.
func signedPayload(t *testing.T, payload string) string {
t.Helper()
enc := base64.RawURLEncoding
unsigned := enc.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`)) + "." + enc.EncodeToString([]byte(payload))
mac := hmac.New(sha256.New, testSecret)
mac.Write([]byte(unsigned))
return unsigned + "." + enc.EncodeToString(mac.Sum(nil))
}
// A request ID the client sends stays the job's reference after the
// request: fasthttp reuses the buffer it was read from for later requests.
func TestClientRequestIDOutlivesTheRequest(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, &fakePrinter{})
first := strings.Repeat("A", 40)
req := request(t, http.MethodPost, "/api/v1/print", validJob, validToken(t))
req.Header.Set("X-Request-ID", first)
if resp, body := send(t, s, req); resp.StatusCode != http.StatusAccepted {
t.Fatalf("status %d (%s)", resp.StatusCode, body)
}
for i := range 20 {
req := request(t, http.MethodPost, "/api/v1/preview", validJob, validToken(t))
req.Header.Set("X-Request-ID", strings.Repeat(string(rune('B'+i%20)), 40))
send(t, s, req)
}
if len(jobs.metas) != 1 || jobs.metas[0].Ref != first {
t.Errorf("the job's reference became %+v, want %q", jobs.metas, first)
}
}
@@ -29,6 +29,7 @@ var (
codeInvalidQuery = errorCode{fiber.StatusBadRequest, "invalid_query", "invalid query parameter"}
codeUnknownPrinter = errorCode{fiber.StatusBadRequest, "unknown_printer", "unknown printer"}
codeUnauthorized = errorCode{fiber.StatusUnauthorized, "unauthorized", "missing or invalid bearer token"}
codeTokenScope = errorCode{fiber.StatusForbidden, "token_scope", "the token does not allow this request"}
codeNotFound = errorCode{fiber.StatusNotFound, "not_found", "not found"}
codeJobNotFound = errorCode{fiber.StatusNotFound, "job_not_found", "job not found"}
codeModuleNotFound = errorCode{fiber.StatusNotFound, "module_not_found", "module not found"}
+14 -5
View File
@@ -9,6 +9,7 @@ import (
"time"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/requestid"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/printer"
@@ -66,13 +67,21 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
if err != nil {
return err
}
return s.submit(c, job)
if err := checkRaw(c, job); err != nil {
return err
}
return s.submit(c, job, "print")
}
// submit queues a validated job and answers 202 with its status and a
// Location header, or refuses it when the queue is full or closed.
func (s *Server) submit(c fiber.Ctx, job receipt.Job) error {
status, err := s.jobs.Submit(job)
// submit queues a validated job, from source, and answers 202 with its
// status and a Location header, or refuses it when the queue is full or
// closed. The request ID is the job's reference at its source. It is
// cloned, as is source, because the queue keeps them after the request:
// an ID the client sent points into a buffer fasthttp reuses for the next
// request.
func (s *Server) submit(c fiber.Ctx, job receipt.Job, source string) error {
meta := printqueue.Meta{Source: strings.Clone(source), Ref: strings.Clone(requestid.FromContext(c))}
status, err := s.jobs.Submit(job, meta)
switch {
case errors.Is(err, printqueue.ErrQueueFull):
c.Set(fiber.HeaderRetryAfter, "10")
@@ -54,7 +54,7 @@ func (s *Server) handlePrintModule(c fiber.Ctx) error {
case skip:
return c.SendStatus(fiber.StatusNoContent)
}
return s.submit(c, job)
return s.submit(c, job, "module:"+c.Params("module"))
}
// handlePreviewModule builds a job as handlePrintModule does and answers
@@ -88,13 +88,19 @@ func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error)
}
job, err = module.Build(c.Context(), c.Body(), s.moduleEnv())
var payloadErr *modules.PayloadError
var (
payloadErr *modules.PayloadError
fallbackErr *modules.FallbackError
)
switch {
case errors.Is(err, modules.ErrSkip):
return receipt.Job{}, true, nil
case errors.As(err, &payloadErr):
msg := fmt.Sprintf("invalid payload for module %q", name)
return job, false, newAPIError(codeInvalidPayload.withMessage(msg), payloadErr.Problems...)
case errors.As(err, &fallbackErr):
// The plain receipt still prints; the fault is reported once.
s.reportModuleFallback(c, name, fallbackErr)
case err != nil:
return job, false, fmt.Errorf("module %s: %w", name, err)
}
@@ -159,3 +165,20 @@ func (s *Server) reportModuleBug(c fiber.Ctx, name string, problems int) {
)
hubFrom(c).CaptureException(fmt.Errorf("module %s built an invalid receipt (%d problems)", name, problems))
}
// reportModuleFallback logs and reports a module that could not lay out
// its receipt and built the plain fallback instead, which still prints.
// The error never quotes the payload.
func (s *Server) reportModuleFallback(c fiber.Ctx, name string, fallbackErr *modules.FallbackError) {
attrs := []slog.Attr{
slog.String("module", name),
slog.String("err", fallbackErr.Error()),
slog.String("path", c.Path()),
slog.String("request_id", requestid.FromContext(c)),
}
if fallbackErr.Stack != "" {
attrs = append(attrs, slog.String("stack", fallbackErr.Stack))
}
s.logger.LogAttrs(c.Context(), slog.LevelError, "module printed its fallback receipt", attrs...)
hubFrom(c).CaptureException(fmt.Errorf("module %s: %w", name, fallbackErr))
}
@@ -3,6 +3,7 @@ package server
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
@@ -15,9 +16,9 @@ import (
"uberbringer/internal/pkg/receipt"
)
// fakeModule answers according to its body: "skip", "payload", "invalid"
// and "fail" give those outcomes, and any other body prints as one line of
// text with the build time.
// fakeModule answers according to its body: "skip", "payload", "invalid",
// "fail" and "fallback" give those outcomes, and any other body prints as
// one line of text with the build time.
type fakeModule struct{}
func (fakeModule) Name() string { return "fake" }
@@ -33,6 +34,9 @@ func (fakeModule) Build(_ context.Context, body []byte, env modules.Env) (receip
return receipt.Job{Elements: []receipt.Element{{Type: "box"}, {Type: "kv"}}}, nil
case "fail":
return receipt.Job{}, errors.New("module broke")
case "fallback":
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: "plain"}}},
&modules.FallbackError{Cause: "panic: layout bug", Stack: "goroutine 1"}
}
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: string(body) + " at " + env.Stamp()}}}, nil
}
@@ -149,6 +153,37 @@ func TestModuleRefusals(t *testing.T) {
}
}
// A module that falls back to its plain receipt still prints it, and the
// fault is logged once at ERROR, with its stack, and reported once.
func TestModuleFallback(t *testing.T) {
for _, tt := range []struct {
target string
status int
}{{"/api/v1/print/fake", http.StatusAccepted}, {"/api/v1/preview/fake", http.StatusOK}} {
t.Run(tt.target, func(t *testing.T) {
events := captureSentryEvents(t)
jobs := &fakeJobs{nextID: newJobID(t)}
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
resp, raw := send(t, s, moduleRequest(t, tt.target, "fallback"))
if resp.StatusCode != tt.status {
t.Fatalf("status %d, want %d (%s)", resp.StatusCode, tt.status, raw)
}
if tt.status == http.StatusAccepted && (len(jobs.submitted) != 1 || jobs.submitted[0].Elements[0].Text != "plain") {
t.Errorf("queued %+v, want the plain receipt", jobs.submitted)
}
failures := errorLines(logs.lines(t))
if len(failures) != 1 || failures[0]["msg"] != "module printed its fallback receipt" ||
failures[0]["module"] != "fake" || failures[0]["stack"] != "goroutine 1" ||
!strings.Contains(fmt.Sprint(failures[0]["err"]), "panic: layout bug") {
t.Errorf("error lines = %v, want one for the fallback", failures)
}
if n := events.count(); n != 1 {
t.Errorf("%d Sentry events, want 1", n)
}
})
}
}
// A module that builds a job validation refuses has a bug: the client gets
// 422 with the problems, and the bug is logged and reported once, without
// the problems, which can quote the payload.
@@ -231,7 +266,9 @@ func TestModuleList(t *testing.T) {
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
}
want := `[{"name":"fake","description":"Prints its body"},{"name":"note","description":"Boxed note with an optional checklist"}]`
want := `[{"name":"fake","description":"Prints its body"},{"name":"note","description":"Boxed note with an optional checklist"},` +
`{"name":"notify","description":"Notification card from title, message, priority and tags"},` +
`{"name":"ntfy","description":"One ntfy message object, e.g. the CLI's $NTFY_RAW"}]`
if string(body) != want {
t.Errorf("body = %s, want %s", body, want)
}
+26 -7
View File
@@ -45,6 +45,8 @@ type Route struct {
// errors are the codes the handler answers with itself;
// DocumentedErrors adds those of the middleware.
errors []errorCode
// scope says which tokens limited to modules may use the route.
scope routeScope
handle func(*Server, fiber.Ctx) error
}
@@ -99,6 +101,9 @@ func (r Route) DocumentedErrors() []ErrorDoc {
if r.Request != nil {
codes = append(codes, codeBodyTooLarge)
}
if r.Auth && r.scope != scopeAny {
codes = append(codes, codeTokenScope)
}
if r.Auth {
codes = append(codes, codeUnauthorized, codeRateLimited)
}
@@ -183,7 +188,8 @@ func Routes() []Route {
Summary: "Queue a print job",
Description: "Validates the whole job and queues it. The worker renders it in full before anything " +
"is sent to the printer, and fetches its images then, so a broken image URL shows up as a " +
"failed job.",
"failed job. A job with raw elements needs a token issued with uberbringer token --raw, " +
"and a token limited to modules cannot use this route.",
Tag: "print",
Auth: true,
Request: receipt.Job{},
@@ -192,6 +198,7 @@ func Routes() []Route {
Headers: []Header{{Name: fiber.HeaderLocation, Description: "The job's URL, which answers with " +
"its status."}}}},
errors: []errorCode{codeInvalidJob, codeQueueFull, codeShuttingDown},
scope: scopeFull,
handle: (*Server).handlePrint,
},
{
@@ -212,6 +219,7 @@ func Routes() []Route {
{MediaType: mediaJSON, Body: previewResponse{}},
}}},
errors: []errorCode{codeInvalidJob, codeTooManyLines},
scope: scopeFull,
handle: (*Server).handlePreview,
},
{
@@ -227,6 +235,7 @@ func Routes() []Route {
Responses: []Response{{Status: http.StatusOK, Description: "The job's status",
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}}}},
errors: []errorCode{codeJobNotFound},
scope: scopeAny,
handle: (*Server).handleJob,
},
{
@@ -234,10 +243,11 @@ func Routes() []Route {
Path: BasePath + "/print/{module}",
OperationID: "printModule",
Summary: "Queue the receipt a module builds from its payload",
Description: "The module named in the path builds a receipt from the body, its own payload, " +
"which is decoded strictly: an unknown field or one of the wrong type is refused, with " +
"every problem listed. The receipt is then validated and queued as on /api/v1/print. A " +
"module with nothing to print answers 204.",
Description: "The module named in the path builds a receipt from the body, its own payload. " +
"note and notify decode it strictly: an unknown field or one of the wrong type is refused, " +
"with every problem listed; ntfy ignores the fields it does not know. The receipt is then " +
"validated and queued as on /api/v1/print. A module with nothing to print answers 204. A " +
"token limited to modules (uberbringer token --modules) may use only the modules it names.",
Tag: "modules",
Auth: true,
Request: modulePayload{},
@@ -251,6 +261,7 @@ func Routes() []Route {
},
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
codeModuleFailed, codeQueueFull, codeShuttingDown},
scope: scopeModule,
handle: (*Server).handlePrintModule,
},
{
@@ -275,6 +286,7 @@ func Routes() []Route {
},
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
codeModuleFailed, codeTooManyLines},
scope: scopeModule,
handle: (*Server).handlePreviewModule,
},
{
@@ -287,6 +299,7 @@ func Routes() []Route {
Auth: true,
Responses: []Response{{Status: http.StatusOK, Description: "The modules",
Content: []Content{{MediaType: mediaJSON, Body: moduleList{}}}}},
scope: scopeAny,
handle: (*Server).handleModules,
},
}
@@ -313,14 +326,20 @@ func fiberPath(path string) string {
// registerRoutes adds every route of the table to the app. api is the group
// at BasePath that holds the bearer token, rate limit and no-store
// middleware.
// middleware; its routes refuse the tokens their scope leaves out.
func (s *Server) registerRoutes(api fiber.Router) {
for _, r := range Routes() {
handler := func(c fiber.Ctx) error { return r.handle(s, c) }
path := fiberPath(r.Path)
switch {
case r.Auth:
api.Add([]string{r.Method}, strings.TrimPrefix(path, BasePath), handler)
scoped := func(c fiber.Ctx) error {
if err := checkScope(c, r.scope); err != nil {
return err
}
return handler(c)
}
api.Add([]string{r.Method}, strings.TrimPrefix(path, BasePath), scoped)
case r.NoStore:
s.app.Add([]string{r.Method}, path, noStore, handler)
default:
+1 -1
View File
@@ -27,7 +27,7 @@ const shutdownTimeout = 10 * time.Second
// Jobs is the print queue as seen by the HTTP handlers.
type Jobs interface {
Submit(job receipt.Job) (printqueue.Status, error)
Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error)
Status(id printqueue.JobID) (printqueue.Status, error)
Pending() int
}
@@ -33,20 +33,22 @@ var testSecret = []byte("0123456789abcdef0123456789abcdef")
type fakeJobs struct {
mu sync.Mutex
submitted []receipt.Job
metas []printqueue.Meta
submitErr error
statusErr error
statuses map[printqueue.JobID]printqueue.Status
nextID printqueue.JobID
}
func (f *fakeJobs) Submit(job receipt.Job) (printqueue.Status, error) {
func (f *fakeJobs) Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.submitErr != nil {
return printqueue.Status{}, f.submitErr
}
f.submitted = append(f.submitted, job)
st := printqueue.Status{ID: f.nextID, State: printqueue.StateQueued, CreatedAt: time.Now()}
f.metas = append(f.metas, meta)
st := printqueue.Status{ID: f.nextID, State: printqueue.StateQueued, Source: meta.Source, CreatedAt: time.Now()}
f.statuses[f.nextID] = st
return st, nil
}
@@ -136,7 +138,7 @@ func newServer(t *testing.T, jobs *fakeJobs, p Printer, logger *slog.Logger, opt
for _, opt := range opts {
opt(&cfg)
}
registry, err := modules.NewRegistry(fakeModule{}, modules.Note())
registry, err := modules.NewRegistry(fakeModule{}, modules.Note(), modules.Notify(), modules.Ntfy())
if err != nil {
t.Fatal(err)
}
@@ -583,7 +585,7 @@ func TestPrintQueueRefusals(t *testing.T) {
func TestJobStatus(t *testing.T) {
id := newJobID(t)
jobs := &fakeJobs{statuses: map[printqueue.JobID]printqueue.Status{
id: {ID: id, State: printqueue.StateDone, Attempts: 1},
id: {ID: id, State: printqueue.StateDone, Source: "module:ntfy", Attempts: 1},
}}
s := newTestServer(t, jobs, &fakePrinter{})
get := func(path, auth string) *http.Request {
@@ -596,7 +598,7 @@ func TestJobStatus(t *testing.T) {
auth := "Bearer " + validToken(t)
resp, body := do(t, s, get("/api/v1/jobs/"+id.String(), auth))
if resp.StatusCode != http.StatusOK || body["status"] != "done" {
if resp.StatusCode != http.StatusOK || body["status"] != "done" || body["source"] != "module:ntfy" {
t.Errorf("GET known job = %d %v", resp.StatusCode, body)
}
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
+130 -6
View File
@@ -14,6 +14,7 @@ import (
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/go-viper/mapstructure/v2"
"github.com/pelletier/go-toml/v2"
@@ -45,6 +46,7 @@ type Config struct {
API APIConfig `mapstructure:"api"`
Printer PrinterConfig `mapstructure:"printer"`
Format FormatConfig `mapstructure:"format"`
Ntfy NtfyConfig `mapstructure:"ntfy"`
Queue QueueConfig `mapstructure:"queue"`
Images ImagesConfig `mapstructure:"images"`
Sentry SentryConfig `mapstructure:"sentry"`
@@ -127,6 +129,48 @@ type FormatConfig struct {
TimeLayout string `mapstructure:"time_layout"`
}
// Values of NtfyFormatConfig's settings.
var (
NtfyStyles = []string{"auto", "box", "compact"}
NtfyQRModes = []string{"all", "first", "none"}
)
// Limits of the ntfy settings: the largest ntfy.format.max_lines, and the
// most characters in a marker.
const (
MaxNtfyLines = 400
MaxMarker = 16
)
// NtfyConfig configures how notifications print, from the notify and ntfy
// modules.
type NtfyConfig struct {
Format NtfyFormatConfig `mapstructure:"format"`
// Markers override the markers printed for tags, by tag: an empty
// marker hides the tag.
Markers map[string]string `mapstructure:"markers"`
}
// NtfyFormatConfig configures the layout of a notification.
type NtfyFormatConfig struct {
// Style is auto, which picks the form from the priority, box or
// compact.
Style string `mapstructure:"style"`
// MaxLines is how many lines of a message print, as written.
MaxLines int `mapstructure:"max_lines"`
// QR is all, first or none: which links print as QR codes.
QR string `mapstructure:"qr"`
// Images prints attached images.
Images bool `mapstructure:"images"`
// Markdown lays out markdown messages.
Markdown bool `mapstructure:"markdown"`
}
// QueueConfig configures the print queue.
type QueueConfig struct {
// Size is the number of jobs that may wait to be printed.
@@ -203,6 +247,15 @@ func Default() Config {
Timezone: "Local",
TimeLayout: "02 Jan 15:04",
},
Ntfy: NtfyConfig{
Format: NtfyFormatConfig{
Style: "auto",
MaxLines: 40,
QR: "all",
Images: true,
Markdown: true,
},
},
Queue: QueueConfig{
Size: 100,
History: 1000,
@@ -240,7 +293,7 @@ func Load(path string) (*Config, error) {
var envSet []string
bound := map[string]bool{PathEnvVar: true}
for _, key := range slices.Sorted(maps.Keys(keys)) {
if keys[key] != setting {
if keys[key] == section {
continue
}
name := envVar(key)
@@ -290,6 +343,7 @@ func Load(path string) (*Config, error) {
viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
durations(),
stringToList(),
stringToTable(),
refuseFractions(),
stringToNumberOrFlag(),
)),
@@ -363,12 +417,14 @@ func readFile(path string) (map[string]any, error) {
return table, nil
}
// keyKind tells a setting from a section that holds settings.
// keyKind tells a setting from a section that holds settings, and from a
// table setting, whose keys are the user's own.
type keyKind int
const (
setting keyKind = iota + 1
section
tableSetting
)
// registerDefaults sets every field of the config struct rv as a Viper
@@ -385,13 +441,18 @@ func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys map[
key = prefix + "." + tag
}
field := rv.Field(i)
if field.Kind() == reflect.Struct {
switch field.Kind() {
case reflect.Struct:
keys[key] = section
registerDefaults(v, key, field, keys)
continue
case reflect.Map:
// A default table would merge with the file's instead of
// giving way to it; the table settings default to empty.
keys[key] = tableSetting
default:
v.SetDefault(key, field.Interface())
keys[key] = setting
}
v.SetDefault(key, field.Interface())
keys[key] = setting
}
}
@@ -428,6 +489,10 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
u, c := checkKeys(sub, path, key, keys)
unknown = append(unknown, u...)
clashes = append(clashes, c...)
case isTable && kind == tableSetting:
u, c := checkTable(sub, path)
unknown = append(unknown, u...)
clashes = append(clashes, c...)
case !isTable && kind == setting:
default:
unknown = append(unknown, path)
@@ -436,6 +501,26 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
return unknown, clashes
}
// checkTable checks the entries of a table setting at path, whose names are
// the user's own. Like checkKeys, it returns as unknown a name with a dot
// and an entry that is itself a table, and the names that differ only in
// case.
func checkTable(entries map[string]any, path string) (unknown, clashes []string) {
seen := make(map[string]string, len(entries))
for _, name := range slices.Sorted(maps.Keys(entries)) {
entry := path + "." + displayKey(name)
if other, ok := seen[strings.ToLower(name)]; ok {
clashes = append(clashes, other+" and "+entry)
continue
}
seen[strings.ToLower(name)] = entry
if _, isTable := entries[name].(map[string]any); isTable || strings.Contains(name, ".") {
unknown = append(unknown, entry)
}
}
return unknown, clashes
}
// displayKey quotes a key name that TOML would need quoted, so that spaces,
// dots and empty names show in messages.
func displayKey(name string) string {
@@ -546,6 +631,35 @@ func stringToList() mapstructure.DecodeHookFunc {
}
}
// stringToTable reads a table setting from a string, such as an
// environment variable: entries name=value, separated by commas, with the
// spaces around each trimmed, so "a=[A], b=" sets a to "[A]" and b to "". A
// value cannot hold a comma.
func stringToTable() mapstructure.DecodeHookFunc {
return func(from, to reflect.Type, data any) (any, error) {
if from.Kind() != reflect.String || to.Kind() != reflect.Map {
return data, nil
}
entries := make(map[string]string)
raw := strings.TrimSpace(data.(string))
if raw == "" {
return entries, nil
}
for item := range strings.SplitSeq(raw, ",") {
name, value, ok := strings.Cut(item, "=")
name = strings.ToLower(strings.TrimSpace(name))
if !ok || name == "" {
return nil, errors.New("expected entries name=value separated by commas, e.g. backup=[B],skull=")
}
if _, dup := entries[name]; dup {
return nil, fmt.Errorf("%q is given twice", name)
}
entries[name] = strings.TrimSpace(value)
}
return entries, nil
}
}
// Validate reports every problem with the configuration.
func (c *Config) Validate() error {
var errs []error
@@ -591,6 +705,16 @@ func (c *Config) Validate() error {
check(showsTime(c.Format.TimeLayout),
`format.time_layout: %q shows no date or time; write it in Go's layout, such as "02 Jan 15:04"`, c.Format.TimeLayout)
nf := c.Ntfy.Format
check(slices.Contains(NtfyStyles, nf.Style), "ntfy.format.style: %q must be one of %s", nf.Style, strings.Join(NtfyStyles, ", "))
check(nf.MaxLines >= 1 && nf.MaxLines <= MaxNtfyLines, "ntfy.format.max_lines must be 1-%d", MaxNtfyLines)
check(slices.Contains(NtfyQRModes, nf.QR), "ntfy.format.qr: %q must be one of %s", nf.QR, strings.Join(NtfyQRModes, ", "))
for _, tag := range slices.Sorted(maps.Keys(c.Ntfy.Markers)) {
check(strings.TrimSpace(tag) != "", "ntfy.markers: a tag name is empty")
check(utf8.RuneCountInString(c.Ntfy.Markers[tag]) <= MaxMarker,
"ntfy.markers.%s: %q is longer than %d characters", tag, c.Ntfy.Markers[tag], MaxMarker)
}
check(c.Queue.Size > 0, "queue.size must be positive")
check(c.Queue.History >= 0, "queue.history must not be negative")
+133 -1
View File
@@ -300,6 +300,66 @@ func TestLoadErrors(t *testing.T) {
body: "\xff\xfe[\x00a\x00p\x00i\x00]\x00",
wantErr: "the file is UTF-16; save it as UTF-8",
},
{
name: "ntfy style",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nstyle = \"fancy\"\n",
wantErr: `ntfy.format.style: "fancy" must be one of auto, box, compact`,
},
{
name: "ntfy max lines zero",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nmax_lines = 0\n",
wantErr: "ntfy.format.max_lines must be 1-400",
},
{
name: "ntfy max lines too many",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nmax_lines = 401\n",
wantErr: "ntfy.format.max_lines must be 1-400",
},
{
name: "ntfy qr",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nqr = \"some\"\n",
wantErr: `ntfy.format.qr: "some" must be one of all, first, none`,
},
{
name: "ntfy images not a flag",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.format]\nimages = \"yes\"\n",
wantErr: "'ntfy.format.images' expected true or false",
},
{
name: "unknown ntfy key",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy]\nserver = \"https://ntfy.sh\"\n",
wantErr: "unknown keys: ntfy.server",
},
{
name: "marker too long",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\nbackup = \"[a very long marker]\"\n",
wantErr: `ntfy.markers.backup: "[a very long marker]" is longer than 16 characters`,
},
{
name: "marker that is not a string",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\nbackup = 1\n",
wantErr: "ntfy.markers",
},
{
name: "marker table",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers.backup]\nmarker = \"[B]\"\n",
wantErr: "unknown keys: ntfy.markers.backup",
},
{
name: "marker name with a dot",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\n\"a.b\" = \"[B]\"\n",
wantErr: `unknown keys: ntfy.markers."a.b"`,
},
{
name: "markers that differ only in case",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\nbackup = \"[b]\"\nBackup = \"[B]\"\n",
wantErr: "keys that differ only in case: ntfy.markers.Backup and ntfy.markers.backup",
},
{
name: "markers as a value",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy]\nmarkers = \"backup=[B]\"\n",
wantErr: "unknown keys: ntfy.markers",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -326,11 +386,74 @@ func TestExampleConfigLoads(t *testing.T) {
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model ||
cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing ||
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout {
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout ||
cfg.Ntfy.Format != def.Ntfy.Format || len(cfg.Ntfy.Markers) != 0 {
t.Error("example config values drifted from the defaults it documents")
}
}
func TestLoadNtfy(t *testing.T) {
def := config.Default().Ntfy.Format
if def != (config.NtfyFormatConfig{Style: "auto", MaxLines: 40, QR: "all", Images: true, Markdown: true}) {
t.Errorf("defaults %+v", def)
}
cfg, err := config.Load(writeConfig(t, `
[api]
secret = "`+validSecret+`"
[printer]
address = "p"
[ntfy.format]
style = "compact"
max_lines = 400
qr = "first"
images = false
markdown = false
[ntfy.markers]
backup = "[B]"
skull = ""
"+1" = "+1"
`))
if err != nil {
t.Fatal(err)
}
want := config.NtfyFormatConfig{Style: "compact", MaxLines: 400, QR: "first", Images: false, Markdown: false}
if cfg.Ntfy.Format != want {
t.Errorf("format %+v, want %+v", cfg.Ntfy.Format, want)
}
if m := cfg.Ntfy.Markers; len(m) != 3 || m["backup"] != "[B]" || m["skull"] != "" || m["+1"] != "+1" {
t.Errorf("markers %q", m)
}
t.Run("environment", func(t *testing.T) {
t.Setenv("UBERBRINGER_API_SECRET", validSecret)
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "p")
t.Setenv("UBERBRINGER_NTFY_FORMAT_STYLE", "box")
t.Setenv("UBERBRINGER_NTFY_MARKERS", " Backup = [B] , skull= ")
cfg, err := config.Load("")
if err != nil {
t.Fatal(err)
}
if cfg.Ntfy.Format.Style != "box" {
t.Errorf("style %q", cfg.Ntfy.Format.Style)
}
if m := cfg.Ntfy.Markers; len(m) != 2 || m["backup"] != "[B]" || m["skull"] != "" {
t.Errorf("markers %q", m)
}
})
t.Run("environment wins over the file", func(t *testing.T) {
t.Setenv("UBERBRINGER_NTFY_MARKERS", "tada=\\o/")
cfg, err := config.Load(writeConfig(t, "[api]\nsecret = \""+validSecret+"\"\n[printer]\naddress = \"p\"\n[ntfy.markers]\nbackup = \"[B]\"\n"))
if err != nil {
t.Fatal(err)
}
if m := cfg.Ntfy.Markers; len(m) != 1 || m["tada"] != `\o/` {
t.Errorf("markers %q", m)
}
})
}
func TestLoadEnvironmentOverridesFile(t *testing.T) {
path := writeConfig(t, `
[api]
@@ -485,6 +608,10 @@ func TestLoadEnvironmentErrors(t *testing.T) {
{"trailing comma", "UBERBRINGER_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1,", "a list item is empty"},
{"number for a flag", "UBERBRINGER_SENTRY_DEBUG", "1", "expected true or false"},
{"unknown time zone", "UBERBRINGER_FORMAT_TIMEZONE", "Mars/Olympus", "format.timezone"},
{"marker without a value", "UBERBRINGER_NTFY_MARKERS", "backup", "expected entries name=value separated by commas"},
{"marker without a name", "UBERBRINGER_NTFY_MARKERS", "=[B]", "expected entries name=value separated by commas"},
{"marker given twice", "UBERBRINGER_NTFY_MARKERS", "backup=[B],Backup=[b]", `"backup" is given twice`},
{"ntfy style", "UBERBRINGER_NTFY_FORMAT_QR", "every", "ntfy.format.qr"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -509,6 +636,7 @@ func TestLoadMissingFile(t *testing.T) {
func TestValue(t *testing.T) {
cfg := config.Default()
cfg.Images.AllowedHosts = []string{"a.lan", "b.lan"}
cfg.Ntfy.Markers = map[string]string{"skull": "", "backup": "[B]"}
tests := []struct {
key, want, wantErr string
}{
@@ -520,6 +648,10 @@ func TestValue(t *testing.T) {
{key: "images.allow_private_networks", want: "false"},
{key: "format.timezone", want: "Local"},
{key: "format.time_layout", want: "02 Jan 15:04"},
{key: "ntfy.format.style", want: "auto"},
{key: "ntfy.format.images", want: "true"},
{key: "ntfy.markers", want: "backup=[B],skull="},
{key: "ntfy.format", wantErr: `"ntfy.format" is a section`},
{key: "printer", wantErr: `"printer" is a section`},
{key: "printer.adress", wantErr: `unknown key "printer.adress"`},
{key: "printer.port.x", wantErr: `unknown key "printer.port.x"`},
+10 -1
View File
@@ -2,14 +2,17 @@ package config
import (
"fmt"
"maps"
"reflect"
"slices"
"strings"
"time"
)
// Value returns the setting at the dotted key, such as "webserver.port", in
// the form a config file or an environment variable gives it: durations such
// as "15s", lists comma-separated. Key names match case-insensitively.
// as "15s", lists comma-separated, and tables as name=value entries, sorted
// and comma-separated. Key names match case-insensitively.
func (c *Config) Value(key string) (string, error) {
v := reflect.ValueOf(*c)
for part := range strings.SplitSeq(key, ".") {
@@ -27,6 +30,12 @@ func (c *Config) Value(key string) (string, error) {
return value.String(), nil
case []string:
return strings.Join(value, ","), nil
case map[string]string:
entries := make([]string, 0, len(value))
for _, name := range slices.Sorted(maps.Keys(value)) {
entries = append(entries, name+"="+value[name])
}
return strings.Join(entries, ","), nil
default:
return fmt.Sprint(value), nil
}
+29
View File
@@ -471,3 +471,32 @@ func TestLookupProfile(t *testing.T) {
t.Errorf("unknown model err = %v", err)
}
}
func TestQRModules(t *testing.T) {
tests := []struct {
n int
level escpos.QRCorrection
want int
}{
{1, escpos.QRCorrectionM, 21},
{14, escpos.QRCorrectionM, 21},
{15, escpos.QRCorrectionM, 25},
{213, escpos.QRCorrectionM, 57},
{504, escpos.QRCorrectionM, 85},
{505, escpos.QRCorrectionM, 89},
{17, escpos.QRCorrectionL, 21},
{7, escpos.QRCorrectionH, 21},
{2953, escpos.QRCorrectionL, 177},
{2954, escpos.QRCorrectionL, 177},
{2331, escpos.QRCorrectionM, 177},
{1663, escpos.QRCorrectionQ, 177},
{1273, escpos.QRCorrectionH, 177},
{1274, escpos.QRCorrectionH, 177},
{10, escpos.QRCorrection(0), 0},
}
for _, tt := range tests {
if got := escpos.QRModules(tt.n, tt.level); got != tt.want {
t.Errorf("QRModules(%d, %d) = %d, want %d", tt.n, tt.level, got, tt.want)
}
}
}
+34
View File
@@ -24,6 +24,40 @@ const (
MaxQRModuleSize = 16
)
// qrByteCapacity holds, for each QR version from 1 to 40, how many bytes a
// code of that version holds in byte mode at correction levels L, M, Q and
// H (ISO/IEC 18004).
var qrByteCapacity = [40][4]int{
{17, 14, 11, 7}, {32, 26, 20, 14}, {53, 42, 32, 24}, {78, 62, 46, 34},
{106, 84, 60, 44}, {134, 106, 74, 58}, {154, 122, 86, 64}, {192, 152, 108, 84},
{230, 180, 130, 98}, {271, 213, 151, 119}, {321, 251, 177, 137}, {367, 287, 203, 155},
{425, 331, 241, 177}, {458, 362, 258, 194}, {520, 412, 292, 220}, {586, 450, 322, 250},
{644, 504, 364, 280}, {718, 560, 394, 310}, {792, 624, 442, 338}, {858, 666, 482, 382},
{929, 711, 509, 403}, {1003, 779, 565, 439}, {1091, 857, 611, 461}, {1171, 911, 661, 511},
{1273, 997, 715, 535}, {1367, 1059, 751, 593}, {1465, 1125, 805, 625}, {1528, 1190, 868, 658},
{1628, 1264, 908, 698}, {1732, 1370, 982, 742}, {1840, 1452, 1030, 790}, {1952, 1538, 1112, 842},
{2068, 1628, 1168, 898}, {2188, 1722, 1228, 958}, {2303, 1809, 1283, 983}, {2431, 1911, 1351, 1051},
{2563, 1989, 1423, 1093}, {2699, 2099, 1499, 1139}, {2809, 2213, 1579, 1219}, {2953, 2331, 1663, 1273},
}
// QRModules returns how many modules wide a QR code holding n bytes at
// level is at most, or 0 for a level that is not one. It assumes byte mode,
// the least dense, so the printer's own code is never wider; data that
// only a denser mode holds, such as thousands of digits, counts as the
// largest version, 177 modules.
func QRModules(n int, level QRCorrection) int {
if level < QRCorrectionL || level > QRCorrectionH {
return 0
}
column := int(level - QRCorrectionL)
for v, capacity := range qrByteCapacity {
if n <= capacity[column] {
return 17 + 4*(v+1)
}
}
return 17 + 4*len(qrByteCapacity)
}
// ParseQRCorrection returns the correction level named by name: L, M, Q or H.
func ParseQRCorrection(name string) (QRCorrection, error) {
switch strings.ToUpper(strings.TrimSpace(name)) {
+412
View File
@@ -0,0 +1,412 @@
package modules
import (
"errors"
"fmt"
"runtime/debug"
"strings"
"unicode/utf8"
"uberbringer/internal/pkg/receipt"
)
// Card styles and QR modes of CardOptions.
const (
StyleAuto = "auto"
StyleBox = "box"
StyleCompact = "compact"
QRAll = "all"
QRFirst = "first"
QRNone = "none"
)
// Card layout.
const (
// DefaultCardLines is how many lines of a message a card prints when
// CardOptions.MaxLines is 0.
DefaultCardLines = 40
// maxLinks is how many links a card prints.
maxLinks = 3
// maxQRLink is the longest link, in bytes, printed as a QR code; a
// longer one prints as text. At correction M it is QR version 17, 85
// modules, which the renderer narrows to fit the paper.
maxQRLink = 500
// qrSize and qrCorrection are the module size and error correction of
// a link's QR code.
qrSize = 5
qrCorrection = "M"
// imageWidth is the width, in dots, an attached image prints at; the
// renderer shrinks it to a narrower paper.
imageWidth = 384
)
// CardOptions shapes the cards of notifications. The zero value is the
// default.
type CardOptions struct {
// Style is auto, box or compact. auto chooses the form from the
// priority: urgent and high get double boxes, default a single box,
// and low and min a rule with no box. box and compact force those forms
// for every priority. "" means auto.
Style string
// MaxLines is how many lines of the message print, as written, before
// "... N more lines". 0 means DefaultCardLines.
MaxLines int
// QR is all, to print every link as a QR code, first, for only the
// first, or none. "" means all.
QR string
// NoImages prints attached images as file rows.
NoImages bool
// NoMarkdown prints a markdown message as written.
NoMarkdown bool
// Markers are the tag markers; nil means the built-in ones.
Markers Markers
}
// FallbackError reports that a card could not be laid out, and that the
// plain fallback receipt was built in its place. The job returned with it
// still prints. Its message never quotes the notification.
type FallbackError struct {
// Cause says what went wrong.
Cause string
// Stack is the stack of the panic that stopped the layout, if one did.
Stack string
}
// Error implements error.
func (e *FallbackError) Error() string {
return "the card fell back to the plain receipt: " + e.Cause
}
// form is the layout of a card.
type form int
const (
formUrgent form = iota
formHigh
formNormal
formCompact
)
// formFor returns the layout of a card of priority under style.
func formFor(priority int, style string) form {
switch {
case strings.EqualFold(style, StyleCompact):
return formCompact
case priority == maxPriority:
return formUrgent
case priority == highPriority:
return formHigh
case priority == defaultPriority || strings.EqualFold(style, StyleBox):
return formNormal
}
return formCompact
}
// cardFault runs at the start of building a card. Tests set it to make
// the build fail.
var cardFault = func() {}
// Card lays out n as a receipt. The priority picks the form: a dark rule
// "URGENT" and a double box for 5, a double box headed "HIGH" for 4, a
// single box with the title in its border for 3, and a rule with the topic
// and time over the title and message for 1 and 2. Tag markers go in front
// of the title, the other tags on a row of their own, and the topic and
// time in the bottom border. Links print as QR codes after the box, then
// the attached image. Text longer than the notice limits is cut.
//
// The job always prints: if laying out the card goes wrong, Card returns
// the plain fallback receipt with a *FallbackError, so that the caller can
// report the fault.
func Card(n Notice, o CardOptions, env Env) (job receipt.Job, err error) {
defer func() {
if r := recover(); r != nil {
job = fallback(n, env)
err = &FallbackError{Cause: fmt.Sprintf("panic: %v", r), Stack: string(debug.Stack())}
}
}()
job = card(n, o, env)
if verr := job.Validate(); verr != nil {
problems := 1
var ve *receipt.ValidationError
if errors.As(verr, &ve) {
problems = len(ve.Problems)
}
return fallback(n, env), &FallbackError{Cause: fmt.Sprintf("the card failed validation with %d problems", problems)}
}
return job, nil
}
// card is Card without the fallback.
func card(n Notice, o CardOptions, env Env) receipt.Job {
cardFault()
markers := o.Markers
if markers == nil {
markers = NewMarkers(nil)
}
priority := n.priority()
f := formFor(priority, o.Style)
titleMarkers, tagText := markers.sortTags(n.Tags)
head := strings.Join(append(titleMarkers, noticeTitle(n, markers.clean)), " ")
if n.Updated {
head += " (updated)"
}
stamp := env.Format(n.Time)
if topic := cut(strings.TrimSpace(markers.clean(n.Topic)), MaxTopic); topic != "" {
stamp = topic + " · " + stamp
}
body, links := cardBody(n, o, markers)
var extra []receipt.Element
if len(tagText) > 0 {
extra = append(extra, receipt.Element{Type: receipt.TypeText, Text: "Tags: " + strings.Join(tagText, ", ")})
}
image, file := cardAttachment(n, o, env)
if file = strings.TrimSpace(markers.clean(file)); file != "" {
extra = append(extra, receipt.Element{Type: receipt.TypeKV, Pairs: []receipt.Pair{{Key: "File", Value: file}}})
}
content := body
if len(extra) > 0 {
if len(content) > 0 {
content = append(content, receipt.Element{Type: receipt.TypeFeed})
}
content = append(content, extra...)
}
var elements []receipt.Element
switch f {
case formUrgent:
children := []receipt.Element{{Type: receipt.TypeText, Text: head, Bold: true, Invert: true}}
if len(content) > 0 {
children = append(children, receipt.Element{Type: receipt.TypeRule, Style: "double"})
children = append(children, content...)
}
elements = []receipt.Element{
{Type: receipt.TypeRule, Style: "dark", Text: "URGENT", Bold: true},
{Type: receipt.TypeBox, Style: "double", Footer: stamp, Children: children},
{Type: receipt.TypeRule, Style: "dark"},
}
case formHigh:
children := []receipt.Element{{Type: receipt.TypeText, Text: head, Bold: true}}
if len(content) > 0 {
children = append(children, receipt.Element{Type: receipt.TypeRule})
children = append(children, content...)
}
elements = []receipt.Element{
{Type: receipt.TypeBox, Style: "double", Title: "HIGH", TitleBold: true, Footer: stamp, Children: children},
}
case formNormal:
if len(content) == 0 {
content = []receipt.Element{{Type: receipt.TypeText}}
}
elements = []receipt.Element{
{Type: receipt.TypeBox, Title: head, TitleBold: true, Footer: stamp, Children: content},
}
default:
switch priority {
case maxPriority:
stamp = "URGENT · " + stamp
case highPriority:
stamp = "HIGH · " + stamp
}
elements = append([]receipt.Element{
{Type: receipt.TypeRule, Text: stamp, Align: "left"},
{Type: receipt.TypeText, Text: head, Bold: true},
}, content...)
}
elements = append(elements, linkElements(mergeLinks(n.Links, links), o, markers)...)
if image != "" {
elements = append(elements,
receipt.Element{Type: receipt.TypeFeed},
receipt.Element{Type: receipt.TypeImage, URL: image, Width: imageWidth, Align: "center", Optional: true})
}
return receipt.Job{Elements: elements}
}
// noticeTitle is n's title as clean leaves it, or else its topic, or else
// "Notification", cut to MaxTitle.
func noticeTitle(n Notice, clean func(string) string) string {
for _, s := range []string{n.Title, n.Topic} {
if s = strings.TrimSpace(clean(s)); s != "" {
return cut(s, MaxTitle)
}
}
return "Notification"
}
// cut returns s, or its first limit characters with "..." in place of the
// last three when it is longer.
func cut(s string, limit int) string {
if utf8.RuneCountInString(s) <= limit {
return s
}
r := []rune(s)
return string(r[:max(limit-3, 0)]) + "..."
}
// cutBytes returns s, or its first bytes up to limit, ending on a whole
// character, with "..." in place of the rest when it is longer.
func cutBytes(s string, limit int) string {
if len(s) <= limit {
return s
}
end := max(limit-3, 0)
for end > 0 && !utf8.RuneStart(s[end]) {
end--
}
return s[:end] + "..."
}
// cardBody lays out n's message, its first lines up to the limit, as
// markdown when it is written in it, and returns the links it names.
func cardBody(n Notice, o CardOptions, markers Markers) ([]receipt.Element, []Link) {
text, more := capLines(markers.clean(cutBytes(n.Message, MaxMessage)), o.MaxLines)
var (
body []receipt.Element
links []Link
)
switch {
case strings.TrimSpace(text) == "":
case n.Markdown && !o.NoMarkdown:
body, links = markdownBody(text)
default:
body = []receipt.Element{{Type: receipt.TypeText, Text: text}}
}
if more > 0 {
noun := "lines"
if more == 1 {
noun = "line"
}
body = append(body, receipt.Element{Type: receipt.TypeText, Text: fmt.Sprintf("... %d more %s", more, noun)})
}
return body, links
}
// capLines returns the first limit lines of text, without the empty lines
// at its end, and how many lines it left out. A limit of 0 means
// DefaultCardLines.
func capLines(text string, limit int) (string, int) {
if limit <= 0 {
limit = DefaultCardLines
}
text = strings.ReplaceAll(text, "\r\n", "\n")
lines := strings.Split(strings.TrimRight(text, " \t\n"), "\n")
if len(lines) <= limit {
return strings.Join(lines, "\n"), 0
}
return strings.Join(lines[:limit], "\n"), len(lines) - limit
}
// cardAttachment returns the URL of the image the card prints, if any,
// and the text of its file row, if any.
func cardAttachment(n Notice, o CardOptions, env Env) (image, file string) {
if n.Image != "" && len(n.Image) <= MaxURL {
if o.NoImages {
file = cut(fileName(n.Image), MaxFileName)
} else {
image = n.Image
}
}
if f := n.File; f != nil {
if !o.NoImages && image == "" && webURL(f.URL) && len(f.URL) <= MaxURL && f.printableImage() && !f.expired(env.Now) {
return f.URL, file
}
name := strings.TrimSpace(f.Name)
if name == "" {
name = fileName(f.URL)
}
name = cut(name, MaxFileName)
if f.Size > 0 {
name += " (" + fileSize(f.Size) + ")"
}
file = name
}
return image, file
}
// fileSize is n bytes in B, KB or MB, as 980 B, 33 KB or 1.4 MB.
func fileSize(n int64) string {
const kb, mb = 1024, 1024 * 1024
switch {
case n < kb:
return fmt.Sprintf("%d B", n)
case n < mb:
return fmt.Sprintf("%d KB", (n+kb/2)/kb)
}
return fmt.Sprintf("%.1f MB", float64(n)/mb)
}
// mergeLinks returns the http and https links of first, then of more, with
// each URL once, at most maxLinks. A URL given twice keeps the first label
// it was given. A URL longer than MaxURL is left out.
func mergeLinks(first, more []Link) []Link {
var links []Link
index := make(map[string]int)
for _, l := range append(append([]Link(nil), first...), more...) {
if !webURL(l.URL) || len(l.URL) > MaxURL {
continue
}
if i, ok := index[l.URL]; ok {
if links[i].Label == "" {
links[i].Label = l.Label
}
continue
}
if len(links) == maxLinks {
continue
}
index[l.URL] = len(links)
links = append(links, l)
}
return links
}
// linkElements prints links after the card: each as a centred QR code with
// its label, or host and path, below it in the small font, or as a line
// "» label" and the URL, as o.QR chooses.
func linkElements(links []Link, o CardOptions, markers Markers) []receipt.Element {
var elements []receipt.Element
// Each QR code has an empty line before it; a run of text links has
// one before the first.
textRun := false
for i, l := range links {
label := cut(strings.TrimSpace(markers.clean(l.Label)), MaxLabel)
qr := len(l.URL) <= maxQRLink &&
(o.QR == "" || strings.EqualFold(o.QR, QRAll) || (strings.EqualFold(o.QR, QRFirst) && i == 0))
if !qr {
if !textRun {
elements = append(elements, receipt.Element{Type: receipt.TypeFeed})
textRun = true
}
if label == "" {
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: "» " + l.URL})
continue
}
elements = append(elements,
receipt.Element{Type: receipt.TypeText, Text: "» " + label},
receipt.Element{Type: receipt.TypeText, Text: l.URL})
continue
}
if label == "" {
label = shortURL(l.URL)
}
textRun = false
elements = append(elements,
receipt.Element{Type: receipt.TypeFeed},
receipt.Element{Type: receipt.TypeQR, Data: l.URL, Size: qrSize, Correction: qrCorrection, Align: "center"},
receipt.Element{Type: receipt.TypeText, Text: label, Font: "b", Align: "center"})
}
return elements
}
+803
View File
@@ -0,0 +1,803 @@
package modules_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"unicode/utf8"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/ntfy"
"uberbringer/internal/pkg/receipt"
)
// TestNtfyBuildsThePaperJobs checks that the ntfy module still builds the
// jobs whose printed result was checked on the TM-T88IV, and whose bytes
// the receipt package pins: the four messages in testdata/paper, built on
// a host at UTC-6 with the default card options.
func TestNtfyBuildsThePaperJobs(t *testing.T) {
for _, name := range []string{"high", "urgent", "default", "min"} {
t.Run(name, func(t *testing.T) {
body, err := os.ReadFile(filepath.Join("testdata", "paper", "ntfy-"+name+".json"))
if err != nil {
t.Fatal(err)
}
env := modules.Env{
Now: time.Unix(1796063393, 0),
Location: time.FixedZone("UTC-6", -6*60*60),
TimeLayout: "02 Jan 15:04",
}
job, err := modules.Ntfy().Build(context.Background(), body, env)
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join("..", "receipt", "testdata", "paper", "ntfy-"+name+".json"))
if err != nil {
t.Fatal(err)
}
paper, err := receipt.DecodeJob(data)
if err != nil {
t.Fatal(err)
}
got, err := json.Marshal(job)
if err != nil {
t.Fatal(err)
}
want, err := json.Marshal(paper)
if err != nil {
t.Fatal(err)
}
if string(got) != string(want) {
t.Errorf("the module builds\n%s\nbut the job checked on paper is\n%s", got, want)
}
})
}
}
// ntfyEnv is the time the example ntfy messages were sent, 29 Nov 2025
// 21:04:05 UTC, in Europe/London, which is on GMT then.
func ntfyEnv(t *testing.T) modules.Env {
t.Helper()
env := fixedEnv(t)
env.Now = time.Unix(1764450245, 0)
return env
}
// checkGolden compares got with the file at path, or rewrites the file
// with -update.
func checkGolden(t *testing.T, path, got string) {
t.Helper()
if *update {
if err := os.WriteFile(path, []byte(got), 0o644); err != nil {
t.Fatal(err)
}
return
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("%v (run go test -run %s -update)", err, strings.Split(t.Name(), "/")[0])
}
if got != string(want) {
t.Errorf("preview differs from %s:\ngot:\n%s\nwant:\n%s", path, got, want)
}
}
// buildGoldens builds each payload in testdata/DIR/*.json with module and
// compares its preview with NAME.txt.
func buildGoldens(t *testing.T, dir string, module modules.Module, env modules.Env) {
t.Helper()
paths, err := filepath.Glob(filepath.Join("testdata", dir, "*.json"))
if err != nil {
t.Fatal(err)
}
if len(paths) == 0 {
t.Fatalf("no payloads in testdata/%s", dir)
}
for _, path := range paths {
name := strings.TrimSuffix(filepath.Base(path), ".json")
t.Run(name, func(t *testing.T) {
body, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
job, err := module.Build(context.Background(), body, env)
if err != nil {
t.Fatalf("Build: %v", err)
}
if err := job.Validate(); err != nil {
t.Fatalf("built an invalid job: %v", err)
}
checkGolden(t, filepath.Join("testdata", dir, name+".txt"), previewText(t, job))
})
}
}
// TestNtfyGoldens previews each testdata/ntfy/*.json message at the time
// it was sent. Run with -update to rewrite the .txt files, then review the
// diff.
func TestNtfyGoldens(t *testing.T) {
buildGoldens(t, "ntfy", modules.Ntfy(), ntfyEnv(t))
}
// TestNotifyGoldens previews each testdata/notify/*.json payload.
func TestNotifyGoldens(t *testing.T) {
buildGoldens(t, "notify", modules.Notify(), fixedEnv(t))
}
// TestCardStyles previews the example message at every priority in every
// style, in testdata/card/p<priority>-<style>.txt.
func TestCardStyles(t *testing.T) {
for _, style := range []string{modules.StyleAuto, modules.StyleBox, modules.StyleCompact} {
for priority := 1; priority <= 5; priority++ {
name := fmt.Sprintf("p%d-%s", priority, style)
t.Run(name, func(t *testing.T) {
n := modules.Notice{
Topic: "alerts",
Title: "Disk almost full",
Message: "/var is at 94% on nas01",
Priority: priority,
Tags: []string{"warning", "nas01"},
Links: []modules.Link{{Label: "Open dashboard", URL: "https://grafana.lan/d/disk"}},
}
job, _ := modules.Card(n, modules.CardOptions{Style: style}, fixedEnv(t))
checkGolden(t, filepath.Join("testdata", "card", name+".txt"), previewText(t, job))
})
}
}
}
// TestNtfyPriorities pins the card of an example message at priorities 5,
// 4, 3 and 1: the four forms.
func TestNtfyPriorities(t *testing.T) {
tests := []struct {
file string
want []string
}{
{"priority-high", []string{
"╔═ HIGH ═════════════════════════════════╗",
"║ [!] Disk almost full ║",
"╟────────────────────────────────────────╢",
"║ /var is at 94% on nas01 ║",
"║ ║",
"║ Tags: nas01 ║",
"╚═══════════════ alerts · 29 Nov 21:04 ══╝",
"",
"[qr: https://grafana.lan/d/disk]",
" Open dashboard",
"",
"[image 384 dots: sPs71M8A2Tq9.png]",
" - - - - - - - partial cut - - - - - - - -",
}},
{"priority-urgent", []string{
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
"╔════════════════════════════════════════╗",
"║ (!) Backup FAILED on nas01 ║",
"╠════════════════════════════════════════╣",
"║ Job nightly-offsite exited with code 2 ║",
"║ after 3h12m. Last good run: 2 days ║",
"║ ago. ║",
"╚══════════════ backups · 29 Nov 21:04 ══╝",
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
" - - - - - - - partial cut - - - - - - - -",
}},
{"priority-default", []string{
"┌─ [√] Nightly backup ───────────────────┐",
"│ restic: 2.1 GB added in 14m 02s, 0 │",
"│ errors. │",
"│ │",
"│ Tags: restic │",
"└────────────── backups · 29 Nov 03:12 ──┘",
" - - - - - - - partial cut - - - - - - - -",
}},
{"priority-min", []string{
"── backups · 29 Nov 03:12 ────────────────",
"Prune finished",
"41 snapshots kept, 3 removed.",
" - - - - - - - partial cut - - - - - - - -",
}},
}
for _, tt := range tests {
t.Run(tt.file, func(t *testing.T) {
body, err := os.ReadFile(filepath.Join("testdata", "ntfy", tt.file+".json"))
if err != nil {
t.Fatal(err)
}
job, err := modules.Ntfy().Build(context.Background(), body, ntfyEnv(t))
if err != nil {
t.Fatal(err)
}
want := strings.Join(tt.want, "\n") + "\n"
if got := previewText(t, job); got != want {
t.Errorf("preview:\n%s\nwant:\n%s", got, want)
}
})
}
}
// TestCardTitleStyles checks how each form styles the title: the title row of
// a high card is bold, of an urgent card bold and inverted, and the title
// in a default card's border is bold, as is the title line of a low card.
func TestCardTitleStyles(t *testing.T) {
tests := []struct {
priority int
check func(job receipt.Job) bool
}{
{5, func(j receipt.Job) bool { c := j.Elements[1].Children[0]; return c.Bold && c.Invert }},
{4, func(j receipt.Job) bool { c := j.Elements[0].Children[0]; return c.Bold && !c.Invert }},
{3, func(j receipt.Job) bool { return j.Elements[0].TitleBold }},
{1, func(j receipt.Job) bool { return j.Elements[1].Bold }},
}
for _, tt := range tests {
job, _ := modules.Card(modules.Notice{Title: "T", Message: "m", Priority: tt.priority}, modules.CardOptions{}, fixedEnv(t))
if !tt.check(job) {
t.Errorf("priority %d: title styled wrongly: %+v", tt.priority, job.Elements)
}
}
}
func TestMarkers(t *testing.T) {
tests := []struct {
name string
overrides map[string]string
tags []string
head string // the title row of a high card
tagRow string // "" for none
}{
{"built in", nil, []string{"warning", "nas01"}, "[!] T", "Tags: nas01"},
{"two markers at most", nil, []string{"warning", "fire", "tada"}, "[!] (!) T", "Tags: tada"},
{"a marker once", nil, []string{"fire", "boom", "rotating_light"}, "(!) T", ""},
{"case", nil, []string{"Warning"}, "[!] T", ""},
{"override", map[string]string{"backup": "[B]", "warning": "/!\\"}, []string{"backup", "warning"}, "[B] /!\\ T", ""},
{"hidden", map[string]string{"nas01": ""}, []string{"warning", "nas01"}, "[!] T", ""},
{"hide a built-in", map[string]string{"warning": ""}, []string{"warning"}, "T", ""},
{"unmapped", nil, []string{"backup", "nas01", " "}, "T", "Tags: backup, nas01"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
o := modules.CardOptions{Markers: modules.NewMarkers(tt.overrides)}
job, _ := modules.Card(modules.Notice{Title: "T", Message: "m", Priority: 4, Tags: tt.tags}, o, fixedEnv(t))
children := job.Elements[0].Children
if got := children[0].Text; got != tt.head {
t.Errorf("title row %q, want %q", got, tt.head)
}
last := children[len(children)-1]
gotRow := ""
if strings.HasPrefix(last.Text, "Tags: ") {
gotRow = last.Text
}
if gotRow != tt.tagRow {
t.Errorf("tag row %q, want %q", gotRow, tt.tagRow)
}
})
}
}
func TestTypedEmoji(t *testing.T) {
n := modules.Notice{Title: "⚠\uFE0F Disk ✅ done ❌ 🚨 👍", Message: "🎉 Party\nBackup 🎉 done\nDone 🎉\n👨\u200D👩\u200D👧 family 🇬🇧 flag 1\uFE0F\u20E3 ■ → ✓", Priority: 4}
job, _ := modules.Card(n, modules.CardOptions{}, fixedEnv(t))
children := job.Elements[0].Children
if got, want := children[0].Text, "[!] Disk [√] done [x] (!) (+1)"; got != want {
t.Errorf("title %q, want %q", got, want)
}
if got, want := children[2].Text, "Party\nBackup done\nDone\nfamily flag 1 ■ → ✓"; got != want {
t.Errorf("message %q, want %q", got, want)
}
hidden := modules.CardOptions{Markers: modules.NewMarkers(map[string]string{"warning": ""})}
job, _ = modules.Card(modules.Notice{Title: "⚠\uFE0F Disk", Message: "m", Priority: 4}, hidden, fixedEnv(t))
if got := job.Elements[0].Children[0].Text; got != "Disk" {
t.Errorf("hidden marker: title %q, want %q", got, "Disk")
}
}
func TestCardLinks(t *testing.T) {
links := []modules.Link{
{URL: "https://a.example.com/x"},
{Label: "A", URL: "https://a.example.com/x"},
{Label: "Mail", URL: "mailto:someone@example.com"},
{Label: "B", URL: "https://b.example.com/"},
{Label: "C", URL: "http://c.example.com/c"},
{Label: "D", URL: "https://d.example.com/d"},
}
n := modules.Notice{Title: "T", Message: "m", Priority: 3, Links: links}
tests := []struct {
qr string
want []string
}{
{"all", []string{
"", "[qr: https://a.example.com/x]", " A",
"", "[qr: https://b.example.com/]", " B",
"", "[qr: http://c.example.com/c]", " C",
}},
{"first", []string{
"", "[qr: https://a.example.com/x]", " A",
"", "» B", "https://b.example.com/", "» C", "http://c.example.com/c",
}},
{"none", []string{
"", "» A", "https://a.example.com/x", "» B", "https://b.example.com/", "» C", "http://c.example.com/c",
}},
}
for _, tt := range tests {
t.Run(tt.qr, func(t *testing.T) {
job, _ := modules.Card(n, modules.CardOptions{QR: tt.qr}, fixedEnv(t))
lines := strings.Split(previewText(t, job), "\n")
// The card is a box of three lines; the cut and a final empty
// string follow the links.
got := lines[3 : len(lines)-2]
if strings.Join(got, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("links:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(tt.want, "\n"))
}
})
}
t.Run("caption without a label", func(t *testing.T) {
job, _ := modules.Card(modules.Notice{Message: "m", Links: []modules.Link{{URL: "https://grafana.lan/d/disk/?from=now"}}},
modules.CardOptions{}, fixedEnv(t))
last := job.Elements[len(job.Elements)-1]
if last.Text != "grafana.lan/d/disk" || last.Font != "b" || last.Align != "center" {
t.Errorf("caption %+v", last)
}
})
t.Run("a long link prints as text", func(t *testing.T) {
long := "https://example.com/" + strings.Repeat("x", 600)
job, _ := modules.Card(modules.Notice{Message: "m", Links: []modules.Link{{URL: long}}}, modules.CardOptions{}, fixedEnv(t))
for _, el := range job.Elements {
if el.Type == receipt.TypeQR {
t.Fatal("a 620-byte link printed as a QR code")
}
}
})
}
// TestNtfyActionsNeverPrint checks that nothing of an http, broadcast or
// copy action reaches the receipt: their URLs, headers, bodies and values
// can hold secrets.
func TestNtfyActionsNeverPrint(t *testing.T) {
body, err := os.ReadFile(filepath.Join("testdata", "ntfy", "actions-private.json"))
if err != nil {
t.Fatal(err)
}
job, err := modules.Ntfy().Build(context.Background(), body, ntfyEnv(t))
if err != nil {
t.Fatal(err)
}
encoded, err := json.Marshal(job)
if err != nil {
t.Fatal(err)
}
preview := previewText(t, job)
for _, secret := range []string{"SECRET", "hooks.example.com", "Close door", "Tasker", "Copy code"} {
if strings.Contains(preview, secret) || strings.Contains(string(encoded), secret) {
t.Errorf("%q from an action that is not a view action reached the receipt", secret)
}
}
if !strings.Contains(preview, "[qr: https://cam.example.com/garage]") {
t.Errorf("the view action did not print:\n%s", preview)
}
}
func TestCardBodyCap(t *testing.T) {
lines := make([]string, 45)
for i := range lines {
lines[i] = fmt.Sprint("line ", i+1)
}
tests := []struct {
maxLines int
message string
last string
}{
{0, strings.Join(lines, "\n"), "... 5 more lines"},
{44, strings.Join(lines, "\n"), "... 1 more line"},
{45, strings.Join(lines, "\n"), "line 45"},
{2, "a\nb\n\n\n", "b"},
}
for _, tt := range tests {
job, _ := modules.Card(modules.Notice{Message: tt.message, Priority: 3}, modules.CardOptions{MaxLines: tt.maxLines}, fixedEnv(t))
children := job.Elements[0].Children
text := children[len(children)-1].Text
rows := strings.Split(text, "\n")
if got := rows[len(rows)-1]; got != tt.last {
t.Errorf("max_lines %d: last line %q, want %q", tt.maxLines, got, tt.last)
}
}
}
func TestCardAttachments(t *testing.T) {
env := ntfyEnv(t)
image := &modules.File{Name: "graph.png", Type: "image/png", Size: 33848, URL: "https://ntfy.example.com/file/g.png"}
tests := []struct {
name string
n modules.Notice
o modules.CardOptions
image string
fileValue string
}{
{"image", modules.Notice{File: image}, modules.CardOptions{}, image.URL, ""},
{"images off", modules.Notice{File: image}, modules.CardOptions{NoImages: true}, "", "graph.png (33 KB)"},
{"expired", modules.Notice{File: &modules.File{Name: "a.png", Type: "image/png", URL: image.URL, Expires: env.Now}},
modules.CardOptions{}, "", "a.png"},
{"not yet expired", modules.Notice{File: &modules.File{Name: "a.png", Type: "image/png", URL: image.URL, Expires: env.Now.Add(time.Second)}},
modules.CardOptions{}, image.URL, ""},
{"no type, image name", modules.Notice{File: &modules.File{Name: "door.JPG", URL: "https://x.example.com/f/abc"}},
modules.CardOptions{}, "https://x.example.com/f/abc", ""},
{"no type, image URL", modules.Notice{File: &modules.File{Name: "door", URL: "https://x.example.com/f/abc.webp"}},
modules.CardOptions{}, "https://x.example.com/f/abc.webp", ""},
{"an image the printer cannot decode", modules.Notice{File: &modules.File{Name: "logo.svg", Type: "image/svg+xml", Size: 2048, URL: "https://x.example.com/logo.svg"}},
modules.CardOptions{}, "", "logo.svg (2 KB)"},
{"another file", modules.Notice{File: &modules.File{Name: "report.pdf", Type: "application/pdf", Size: 1468006, URL: "https://x.example.com/r.pdf"}},
modules.CardOptions{}, "", "report.pdf (1.4 MB)"},
{"a small file", modules.Notice{File: &modules.File{Name: "a.txt", Size: 980, URL: "https://x.example.com/a.txt"}},
modules.CardOptions{}, "", "a.txt (980 B)"},
{"notify image", modules.Notice{Image: "https://x.example.com/i.png"}, modules.CardOptions{}, "https://x.example.com/i.png", ""},
{"notify image, images off", modules.Notice{Image: "https://x.example.com/i.png"}, modules.CardOptions{NoImages: true}, "", "i.png"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.n.Message, tt.n.Priority = "m", 3
job, _ := modules.Card(tt.n, tt.o, env)
var gotImage, gotFile string
for _, el := range job.Elements {
if el.Type == receipt.TypeImage {
gotImage = el.URL
if !el.Optional || el.Width != 384 || el.Align != "center" {
t.Errorf("image %+v, want optional, 384 dots and centred", el)
}
}
}
for _, el := range job.Elements[0].Children {
if el.Type == receipt.TypeKV && el.Pairs[0].Key == "File" {
gotFile = el.Pairs[0].Value
}
}
if gotImage != tt.image || gotFile != tt.fileValue {
t.Errorf("image %q and file row %q, want %q and %q", gotImage, gotFile, tt.image, tt.fileValue)
}
})
}
}
func TestFromNtfy(t *testing.T) {
tests := []struct {
name string
body string
skip bool
want func(modules.Notice) bool
}{
{"unknown fields are ignored", `{"event":"message","message":"x","colour":"red","attachment":{"url":"https://a/b.png","name":"b.png","new":1}}`,
false, func(n modules.Notice) bool { return n.Message == "x" && n.File != nil }},
{"no priority is 3", `{"event":"message","message":"x"}`, false, func(n modules.Notice) bool { return n.Priority == 3 }},
{"priority 0 is 3", `{"event":"message","message":"x","priority":0}`, false, func(n modules.Notice) bool { return n.Priority == 3 }},
{"priority out of range is 3", `{"event":"message","message":"x","priority":9}`, false, func(n modules.Notice) bool { return n.Priority == 3 }},
{"no event is a message", `{"message":"x","priority":5}`, false, func(n modules.Notice) bool { return n.Priority == 5 }},
{"markdown", `{"event":"message","message":"x","content_type":"text/markdown"}`, false, func(n modules.Notice) bool { return n.Markdown }},
{"time", `{"event":"message","message":"x","time":1764450245}`, false,
func(n modules.Notice) bool { return n.Time.Equal(time.Unix(1764450245, 0)) }},
{"file placeholder", `{"event":"message","message":"You received a file: a.pdf","attachment":{"name":"a.pdf","url":"https://a/a.pdf"}}`,
false, func(n modules.Notice) bool { return n.Message == "" && n.File.Name == "a.pdf" }},
{"other text stays", `{"event":"message","message":"See a.pdf","attachment":{"name":"a.pdf","url":"https://a/a.pdf"}}`,
false, func(n modules.Notice) bool { return n.Message == "See a.pdf" }},
{"sequence id equal to id", `{"id":"a","sequence_id":"a","event":"message","message":"x"}`, false, func(n modules.Notice) bool { return !n.Updated }},
// A publisher may choose the sequence ID, so one message cannot
// tell the first of its sequence from a replacement.
{"sequence id other than id", `{"id":"b","sequence_id":"a","event":"message","message":"x"}`, false, func(n modules.Notice) bool { return !n.Updated }},
{"view actions and click are links", `{"event":"message","message":"x","click":"https://c/",` +
`"actions":[{"action":"view","label":"V","url":"https://v/"},{"action":"http","label":"H","url":"https://h/"}]}`,
false, func(n modules.Notice) bool {
return len(n.Links) == 2 && n.Links[0].URL == "https://c/" && n.Links[1] == modules.Link{Label: "V", URL: "https://v/"}
}},
{"open", `{"id":"x","time":1,"event":"open","topic":"alerts"}`, true, nil},
{"keepalive", `{"id":"x","time":1,"event":"keepalive","topic":"alerts"}`, true, nil},
{"poll request", `{"event":"poll_request","message":"New message"}`, true, nil},
{"delete", `{"event":"message_delete","sequence_id":"a"}`, true, nil},
{"clear", `{"event":"message_clear","sequence_id":"a"}`, true, nil},
{"base64", `{"event":"message","message":"iVBORw0KGgo=","encoding":"base64"}`, true, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var m ntfy.Message
if err := json.Unmarshal([]byte(tt.body), &m); err != nil {
t.Fatal(err)
}
n, err := modules.FromNtfy(m)
if tt.skip {
if !errors.Is(err, modules.ErrSkip) {
t.Errorf("err = %v, want ErrSkip", err)
}
return
}
if err != nil {
t.Fatal(err)
}
if !tt.want(n) {
t.Errorf("notice %+v", n)
}
})
}
}
func TestNtfyBuild(t *testing.T) {
ctx := context.Background()
if _, err := modules.Ntfy().Build(ctx, []byte(`{"event":"keepalive","time":1}`), ntfyEnv(t)); !errors.Is(err, modules.ErrSkip) {
t.Errorf("keepalive: err = %v, want ErrSkip", err)
}
sequence := []byte(`{"id":"b","sequence_id":"a","event":"message","title":"Disk","message":"x","priority":4}`)
job, err := modules.Ntfy().Build(ctx, sequence, ntfyEnv(t))
if err != nil {
t.Fatal(err)
}
if got := job.Elements[0].Children[0].Text; got != "Disk" {
t.Errorf("a message of a sequence: title %q, want it unmarked", got)
}
// A notice known to replace an earlier one, as the subscriber can
// tell, is marked.
job, _ = modules.Card(modules.Notice{Title: "Disk", Message: "x", Priority: 4, Updated: true}, modules.CardOptions{}, ntfyEnv(t))
if got := job.Elements[0].Children[0].Text; got != "Disk (updated)" {
t.Errorf("an update: title %q", got)
}
problems := []struct{ body, want string }{
{``, "body: empty; expected a JSON object"},
{`null`, "body: expected a JSON object, got null"},
{`[1]`, "body: expected a JSON object, got array"},
{`{"message":"x"} {}`, "body: trailing data after the payload"},
{`{"priority":"high"}`, "priority: expected a whole number"},
{`{"attachment":{"size":"big"}}`, "attachment.size: expected a whole number"},
}
for _, p := range problems {
_, err := modules.Ntfy().Build(ctx, []byte(p.body), ntfyEnv(t))
var pe *modules.PayloadError
if !errors.As(err, &pe) || strings.Join(pe.Problems, "; ") != p.want {
t.Errorf("%s: err = %v, want the problem %q", p.body, err, p.want)
}
}
}
func TestNotifyPayloadProblems(t *testing.T) {
tests := []struct {
name, body string
want []string
}{
{"unknown field", `{"message":"x","colour":"red"}`, []string{"colour: unknown field"}},
{"wrong types", `{"message":1,"tags":"a","markdown":"yes","actions":{}}`,
[]string{"actions: expected an array", "markdown: expected true or false", "message: expected a string", "tags: expected an array of strings"}},
{"missing message", `{"title":"T"}`, []string{"message: required"}},
{"long message", `{"message":"` + strings.Repeat("x", modules.MaxMessage+1) + `"}`, []string{"message: 4097 bytes, limit is 4096"}},
{"long title and topic", `{"message":"x","title":"` + strings.Repeat("é", modules.MaxTitle+1) + `","topic":"` + strings.Repeat("t", modules.MaxTopic+1) + `"}`,
[]string{"title: 251 characters, limit is 250", "topic: 65 characters, limit is 64"}},
{"too many tags", `{"message":"x","tags":[` + strings.Repeat(`"a",`, modules.MaxTags) + `"b"]}`, []string{"tags: 21 tags, limit is 20"}},
{"long tag", `{"message":"x","tags":["a","` + strings.Repeat("t", modules.MaxTag+1) + `"]}`, []string{"tags[1]: 65 characters, limit is 64"}},
{"long label and URLs", `{"message":"x","click":"https://a/` + strings.Repeat("x", modules.MaxURL) + `","image":"https://i/` + strings.Repeat("x", modules.MaxURL) +
`","actions":[{"label":"` + strings.Repeat("l", modules.MaxLabel+1) + `","url":"https://b/` + strings.Repeat("x", modules.MaxURL) + `"}]}`,
[]string{"click: 2010 bytes, limit is 2000", "image: 2010 bytes, limit is 2000",
"actions[0].label: 65 characters, limit is 64", "actions[0].url: 2010 bytes, limit is 2000"}},
{"priority number", `{"message":"x","priority":6}`, []string{"priority: must be 1-5, or min, low, default, high, max or urgent"}},
{"priority fraction", `{"message":"x","priority":2.5}`, []string{"priority: must be 1-5, or min, low, default, high, max or urgent"}},
{"priority name", `{"message":"x","priority":"loud"}`, []string{"priority: must be 1-5, or min, low, default, high, max or urgent"}},
{"priority type", `{"message":"x","priority":true}`, []string{"priority: must be 1-5, or min, low, default, high, max or urgent"}},
{"time", `{"message":"x","time":"yesterday"}`, []string{"time: must be Unix seconds or an RFC 3339 time, e.g. 2026-11-29T21:04:05Z"}},
{"negative time", `{"message":"x","time":-5}`, []string{"time: must be Unix seconds or an RFC 3339 time, e.g. 2026-11-29T21:04:05Z"}},
{"click", `{"message":"x","click":"mailto:a@example.com"}`, []string{"click: must be an http or https URL"}},
{"image", `{"message":"x","image":"/local.png"}`, []string{"image: must be an http or https URL"}},
{"too many actions", `{"message":"x","actions":[{"url":"https://a/"},{"url":"https://b/"},{"url":"https://c/"},{"url":"https://d/"}]}`,
[]string{"actions: 4 actions, limit is 3"}},
{"action problems", `{"message":"x","actions":[{"label":"A"},{"url":"ftp://x/"},{"url":"https://x/","lable":"B"},"https://y/"]}`,
[]string{"actions: 4 actions, limit is 3", "actions[0].url: required", "actions[1].url: must be an http or https URL",
"actions[2].lable: unknown field", "actions[3]: expected a JSON object, got string"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := modules.Notify().Build(context.Background(), []byte(tt.body), fixedEnv(t))
var pe *modules.PayloadError
if !errors.As(err, &pe) {
t.Fatalf("err = %v, want *PayloadError", err)
}
if strings.Join(pe.Problems, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("problems:\n%s\nwant:\n%s", strings.Join(pe.Problems, "\n"), strings.Join(tt.want, "\n"))
}
})
}
}
func TestNotifyPriorityAndTime(t *testing.T) {
tests := []struct {
body string
priority int // 5: an URGENT rule first, 4: a HIGH box, 3: a box, 1 and 2: a rule
stamp string
}{
{`{"message":"x"}`, 3, "29 Nov 21:04"},
{`{"message":"x","priority":"urgent"}`, 5, ""},
{`{"message":"x","priority":"MAX"}`, 5, ""},
{`{"message":"x","priority":"high"}`, 4, ""},
{`{"message":"x","priority":"default"}`, 3, ""},
{`{"message":"x","priority":"low"}`, 2, ""},
{`{"message":"x","priority":"min"}`, 1, ""},
{`{"message":"x","priority":"4"}`, 4, ""},
{`{"message":"x","priority":1}`, 1, ""},
{`{"message":"x","time":1764450245}`, 3, "29 Nov 21:04"},
{`{"message":"x","time":"2026-07-01T12:30:00+02:00"}`, 3, "01 Jul 11:30"},
}
for _, tt := range tests {
job, err := modules.Notify().Build(context.Background(), []byte(tt.body), fixedEnv(t))
if err != nil {
t.Errorf("%s: %v", tt.body, err)
continue
}
first := job.Elements[0]
var got int
switch {
case first.Type == receipt.TypeRule && first.Text == "URGENT":
got = 5
case first.Type == receipt.TypeBox && first.Title == "HIGH":
got = 4
case first.Type == receipt.TypeBox:
got = 3
default:
got = 1
}
want := tt.priority
if want <= 2 {
want = 1
}
if got != want {
t.Errorf("%s: printed as priority %d, want %d", tt.body, got, tt.priority)
}
if tt.stamp != "" && !strings.HasSuffix(first.Footer, tt.stamp) {
t.Errorf("%s: footer %q, want the time %s", tt.body, first.Footer, tt.stamp)
}
}
}
// TestCardFallback checks that a card that fails to lay out still prints:
// the plain fallback receipt, which passes validation.
func TestCardFallback(t *testing.T) {
restore := modules.SetCardFault(func() { panic("layout bug") })
defer restore()
n := modules.Notice{Topic: "alerts", Title: "Disk 🎉", Message: "/var is at 94%", Priority: 5}
job, err := modules.Card(n, modules.CardOptions{}, fixedEnv(t))
var fallbackErr *modules.FallbackError
if !errors.As(err, &fallbackErr) || !strings.Contains(fallbackErr.Cause, "layout bug") || fallbackErr.Stack == "" {
t.Errorf("err = %#v, want a *FallbackError with the panic and its stack", err)
}
if strings.Contains(fmt.Sprint(err), "94%") {
t.Error("the error quotes the notification")
}
if err := job.Validate(); err != nil {
t.Fatalf("fallback is invalid: %v", err)
}
// The module returns the fallback with the error, for its caller to
// report.
built, err := modules.Notify().Build(context.Background(), []byte(`{"message":"x"}`), fixedEnv(t))
if !errors.As(err, &fallbackErr) || len(built.Elements) == 0 || built.Validate() != nil {
t.Errorf("notify: job %+v, err %v; want the fallback and a *FallbackError", built, err)
}
want := "Disk\n/var is at 94%\nalerts · 29 Nov 21:04\n - - - - - - - partial cut - - - - - - - -\n"
if got := previewText(t, job); got != want {
t.Errorf("fallback:\n%s\nwant:\n%s", got, want)
}
if !job.Elements[0].Bold {
t.Error("the fallback's title is not bold")
}
}
// TestCardsAreValid builds cards from awkward notices, which must all pass
// validation without falling back.
func TestCardsAreValid(t *testing.T) {
many := make([]string, 300)
for i := range many {
many[i] = "- item"
}
notices := []modules.Notice{
{},
{Message: " \n "},
{Message: "x", Priority: -1},
{Message: "x", Priority: 3, Tags: []string{"", "warning", "x", "tada", "skull"}},
{Message: strings.Join(many, "\n"), Markdown: true, Priority: 3},
{Message: "```\nunclosed fence", Markdown: true},
{Message: "- 🎉\n# \n> \n---", Markdown: true, Priority: 1},
{Title: "\u001b@", Message: "\u0007\u001bd", Topic: "\t"},
{Message: "x", Links: []modules.Link{{URL: "https://a/"}, {URL: "https://b/"}, {URL: "https://c/"}, {URL: "https://d/"}}},
}
for _, o := range []modules.CardOptions{{}, {MaxLines: 400}, {Style: "compact", QR: "none"}, {Style: "box", QR: "first"}} {
for i, n := range notices {
job, err := modules.Card(n, o, fixedEnv(t))
if err != nil {
t.Errorf("notice %d, options %+v: %v", i, o, err)
}
if err := job.Validate(); err != nil {
t.Errorf("notice %d, options %+v: %v", i, o, err)
}
// A card starts with a box or a rule; the fallback with text.
if job.Elements[0].Type == receipt.TypeText {
t.Errorf("notice %d, options %+v: fell back to the plain receipt", i, o)
}
}
}
}
// TestCardLimits builds a card from a notice far over every limit, as an
// ntfy message may be: it is cut to a length that prints well inside
// format.max_lines, even on 58 mm paper.
func TestCardLimits(t *testing.T) {
long := strings.Repeat("word ", 20_000)
tags := make([]string, 9000)
for i := range tags {
tags[i] = fmt.Sprint("tag", i, strings.Repeat("x", 100))
}
n := modules.Notice{
Title: long,
Topic: long,
Message: strings.Repeat("x", 1_000_000),
Priority: 5,
Tags: tags,
Links: []modules.Link{
{Label: long, URL: "https://a.example.com/" + strings.Repeat("x", 300)},
{URL: "https://b.example.com/" + strings.Repeat("x", 5000)},
},
File: &modules.File{Name: long, URL: "https://f.example.com/report.pdf"},
}
job, err := modules.Card(n, modules.CardOptions{}, fixedEnv(t))
if err != nil {
t.Fatal(err)
}
for _, model := range []string{"tm-t88", "generic-58mm"} {
profile, err := escpos.LookupProfile(model)
if err != nil {
t.Fatal(err)
}
r := receipt.NewRenderer(receipt.Options{
Profile: profile, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000, MaxLines: 2000,
}, noFetch{})
p, err := r.Preview(context.Background(), job)
if err != nil {
t.Fatalf("%s: %v", model, err)
}
if p.LineCount > 400 {
t.Errorf("%s: the card prints %d lines", model, p.LineCount)
}
}
box := job.Elements[1]
if head := box.Children[0].Text; utf8.RuneCountInString(head) > modules.MaxTitle+4 || !strings.HasSuffix(head, "...") {
t.Errorf("title row of %d characters", utf8.RuneCountInString(head))
}
for _, el := range job.Elements {
if el.Type == receipt.TypeQR && len(el.Data) > 1000 {
t.Errorf("a %d-byte link printed", len(el.Data))
}
}
}
// TestCardTitleFallback checks that a title or tags that cleaning leaves
// empty fall back as a missing title does, and leave no empty tag.
func TestCardTitleFallback(t *testing.T) {
tests := []struct {
n modules.Notice
head string
row string
}{
{modules.Notice{Title: "🎉🎉", Topic: "alerts", Tags: []string{"warning"}}, "[!] alerts", ""},
{modules.Notice{Title: "🎉", Topic: "🎉"}, "Notification", ""},
{modules.Notice{Title: "T", Tags: []string{"🎉", "a", " ", "🧺"}}, "T", "Tags: a"},
{modules.Notice{Title: "T", Tags: []string{"🎉"}}, "T", ""},
}
for _, tt := range tests {
tt.n.Message, tt.n.Priority = "m", 4
job, _ := modules.Card(tt.n, modules.CardOptions{}, fixedEnv(t))
children := job.Elements[0].Children
row := ""
if last := children[len(children)-1].Text; strings.HasPrefix(last, "Tags:") {
row = last
}
if children[0].Text != tt.head || row != tt.row {
t.Errorf("%q with tags %q: title row %q and tags row %q, want %q and %q",
tt.n.Title, tt.n.Tags, children[0].Text, row, tt.head, tt.row)
}
}
}
+12
View File
@@ -0,0 +1,12 @@
package modules
// SetCardFault makes every card run fault first, and returns a func that
// undoes it.
func SetCardFault(fault func()) (restore func()) {
old := cardFault
cardFault = fault
return func() { cardFault = old }
}
// MarkdownBody exposes markdownBody to the tests.
var MarkdownBody = markdownBody
+23
View File
@@ -0,0 +1,23 @@
package modules
import (
"strings"
"uberbringer/internal/pkg/receipt"
)
// fallback is the plain receipt Card returns when laying out a card goes
// wrong: the title in bold, the message as written, then the topic and
// time, each cut to the notice limits.
func fallback(n Notice, env Env) receipt.Job {
elements := []receipt.Element{{Type: receipt.TypeText, Text: noticeTitle(n, receipt.StripEmoji), Bold: true}}
if message := strings.TrimSpace(receipt.StripEmoji(cutBytes(n.Message, MaxMessage))); message != "" {
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: message})
}
stamp := env.Format(n.Time)
if topic := cut(strings.TrimSpace(receipt.StripEmoji(n.Topic)), MaxTopic); topic != "" {
stamp = topic + " · " + stamp
}
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: stamp})
return receipt.Job{Elements: elements}
}
+263
View File
@@ -0,0 +1,263 @@
package modules
import (
"regexp"
"strings"
"uberbringer/internal/pkg/receipt"
)
// Line-level markdown: headings, bullet and numbered items, quotes, code
// fences and thematic breaks.
var (
mdHeading = regexp.MustCompile(`^\s{0,3}#{1,6}\s+(.*?)(\s+#+)?\s*$`)
mdBreak = regexp.MustCompile(`^\s{0,3}([-*_])(\s*([-*_])){2,}\s*$`)
mdBullet = regexp.MustCompile(`^\s*[-*+]\s+(\S.*)$`)
mdNumbered = regexp.MustCompile(`^\s*\d{1,9}[.)]\s+(\S.*)$`)
mdQuote = regexp.MustCompile(`^\s{0,3}>\s?(.*)$`)
mdFence = regexp.MustCompile("^\\s{0,3}(```|~~~)")
)
// Inline markdown, applied in this order: images, links, code spans and
// bare URLs, which are kept as written, then emphasis and strikethrough.
var (
mdImage = regexp.MustCompile(`!\[([^\]]*)\]\(([^)\s]*)(\s+"[^"]*")?\)`)
mdLink = regexp.MustCompile(`\[([^\]]+)\]\(([^)\s]+)(\s+"[^"]*")?\)`)
mdCode = regexp.MustCompile("`([^`]+)`")
mdURL = regexp.MustCompile("\\b(?:https?|ftp)://[^\\s<>`\\x{E100}-\\x{E7FF}]+")
mdStrong = regexp.MustCompile(`\*\*([^\s*](?:.*?[^\s*])?)\*\*`)
mdStrongU = regexp.MustCompile(`\b__([^\s_](?:.*?[^\s_])?)__\b`)
mdStrike = regexp.MustCompile(`~~([^\s~](?:.*?[^\s~])?)~~`)
mdEmphasis = regexp.MustCompile(`\*([^\s*](?:[^*]*?[^\s*])?)\*`)
mdEmphasisU = regexp.MustCompile(`(^|[^\pL\pN_])_([^\s_](?:[^_]*?[^\s_])?)_($|[^\pL\pN_])`)
mdEscape = regexp.MustCompile("\\\\([\\\\`*_{}\\[\\]()#+\\-.!>~|])")
)
// escapeBase is where markdownInline sets aside escaped ASCII characters,
// in the private use area: '*' is escapeBase+'*'. keptBase is where it
// numbers the code spans and URLs it keeps as written, up to maxKept.
const (
escapeBase = rune(0xE000)
keptBase = rune(0xE100)
maxKept = 0x700
)
// markdownBody lays out text written in a subset of markdown as elements
// that fit inside a box as well as on their own:
//
// - #, ## and ### headings print as bold lines;
// - -, * and + items as a dot list, and 1. items as a numbered list;
// - > quotes with "│ " in front;
// - lines between ``` fences as written;
// - --- as a divider;
// - **bold**, __bold__, *italic*, _italic_, `code` and ~~struck~~ text
// without the marks;
// - [text](url) as its text, with url added to links;
// - ![alt](url) as [image: alt].
//
// Every other line prints as written, and a run of empty lines as one.
func markdownBody(text string) (elements []receipt.Element, links []Link) {
var (
para []string
list *receipt.Element
fence []string
inFence bool
blankRun bool
)
flushPara := func() {
if len(para) > 0 {
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: strings.Join(para, "\n")})
para = nil
}
}
flushList := func() {
if list != nil {
elements = append(elements, *list)
list = nil
}
}
flush := func() {
flushPara()
flushList()
}
inline := func(s string) string {
s, found := markdownInline(s)
links = append(links, found...)
return s
}
addItem := func(bullet, item string) {
item = inline(item)
if strings.TrimSpace(item) == "" {
return
}
if list != nil && (list.Bullet != bullet || len(list.Items) == receipt.MaxItems) {
flushList()
}
flushPara()
if list == nil {
list = &receipt.Element{Type: receipt.TypeList, Bullet: bullet}
}
list.Items = append(list.Items, item)
}
for _, line := range strings.Split(text, "\n") {
if inFence {
if mdFence.MatchString(line) {
inFence = false
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: strings.Join(fence, "\n"), Wrap: boolPtr(false)})
fence = nil
continue
}
fence = append(fence, line)
continue
}
if strings.TrimSpace(line) == "" {
flush()
if !blankRun && len(elements) > 0 {
elements = append(elements, receipt.Element{Type: receipt.TypeFeed})
}
blankRun = true
continue
}
blankRun = false
switch {
case mdFence.MatchString(line):
flush()
inFence = true
case mdBreak.MatchString(line):
flush()
elements = append(elements, receipt.Element{Type: receipt.TypeRule})
case mdHeading.MatchString(line):
flush()
heading := inline(mdHeading.FindStringSubmatch(line)[1])
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: heading, Bold: true})
case mdBullet.MatchString(line):
addItem("dot", mdBullet.FindStringSubmatch(line)[1])
case mdNumbered.MatchString(line):
addItem("number", mdNumbered.FindStringSubmatch(line)[1])
case mdQuote.MatchString(line):
flushList()
para = append(para, "│ "+inline(mdQuote.FindStringSubmatch(line)[1]))
default:
flushList()
para = append(para, inline(line))
}
}
if inFence && len(fence) > 0 {
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: strings.Join(fence, "\n"), Wrap: boolPtr(false)})
}
flush()
// A trailing empty line prints nothing useful.
for len(elements) > 0 && elements[len(elements)-1].Type == receipt.TypeFeed {
elements = elements[:len(elements)-1]
}
return elements, links
}
// markdownInline removes the inline marks from s and returns the http and
// https links it names.
func markdownInline(s string) (string, []Link) {
// The characters that number what is kept as written are dropped from
// the text first, so that none is taken for a number; no code page
// prints them.
s = strings.Map(func(r rune) rune {
if r >= keptBase && r < keptBase+maxKept {
return -1
}
return r
}, s)
// Escaped characters are set aside, so that they are not read as marks.
s = mdEscape.ReplaceAllStringFunc(s, func(m string) string {
return string(escapeBase + rune(m[1]))
})
s = mdImage.ReplaceAllStringFunc(s, func(m string) string {
alt := strings.TrimSpace(mdImage.FindStringSubmatch(m)[1])
if alt == "" {
return "[image]"
}
return "[image: " + alt + "]"
})
var links []Link
s = mdLink.ReplaceAllStringFunc(s, func(m string) string {
parts := mdLink.FindStringSubmatch(m)
text, target := parts[1], parts[2]
if webURL(target) {
links = append(links, Link{Label: restoreEscapes(text), URL: target})
}
return text
})
// Code spans, without their backticks, and bare URLs are set aside,
// so that marks inside them, as in __init__.py, print as written.
var kept []string
keep := func(text string) string {
if len(kept) == maxKept {
return text
}
kept = append(kept, text)
return string(keptBase + rune(len(kept)-1))
}
s = mdCode.ReplaceAllStringFunc(s, func(m string) string { return keep(m[1 : len(m)-1]) })
s = mdURL.ReplaceAllStringFunc(s, func(m string) string {
url, rest := trimURL(m)
return keep(url) + rest
})
s = mdStrong.ReplaceAllString(s, "$1")
s = mdStrongU.ReplaceAllString(s, "$1")
s = mdStrike.ReplaceAllString(s, "$1")
s = mdEmphasis.ReplaceAllString(s, "$1")
// Twice: a match takes the character after it, which the next one
// may need before it.
for range 2 {
s = mdEmphasisU.ReplaceAllString(s, "$1$2$3")
}
return restoreEscapes(restoreKept(s, kept)), links
}
// trimURL splits the punctuation that ends a sentence, or closes emphasis,
// off the end of a bare URL, as GitHub's autolinks do: trailing . , : ; !
// ? ' " _ * and ~, and a ) that has no ( in the URL to close. The same
// marks inside the URL stay part of it. It returns the URL and what
// followed it.
func trimURL(m string) (url, rest string) {
url = m
for url != "" {
last := url[len(url)-1]
switch {
case strings.IndexByte(".,:;!?'\"_*~", last) >= 0:
case last == ')' && strings.Count(url, ")") > strings.Count(url, "("):
default:
return url, m[len(url):]
}
url = url[:len(url)-1]
}
return url, m
}
// restoreKept puts back the code spans and URLs markdownInline set aside
// in kept.
func restoreKept(s string, kept []string) string {
if len(kept) == 0 {
return s
}
var b strings.Builder
for _, r := range s {
if i := int(r - keptBase); r >= keptBase && i < len(kept) {
b.WriteString(kept[i])
continue
}
b.WriteRune(r)
}
return b.String()
}
// restoreEscapes puts back the characters markdownInline set aside.
func restoreEscapes(s string) string {
return strings.Map(func(r rune) rune {
if r >= escapeBase && r < escapeBase+0x80 {
return r - escapeBase
}
return r
}, s)
}
func boolPtr(b bool) *bool { return &b }
+197
View File
@@ -0,0 +1,197 @@
package modules_test
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
"unicode/utf8"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
// markdownBox lays out text as markdown inside a box, as a card does.
func markdownBox(text string) (receipt.Job, []modules.Link) {
body, links := modules.MarkdownBody(text)
if len(body) == 0 {
body = []receipt.Element{{Type: receipt.TypeText}}
}
return receipt.Job{Elements: []receipt.Element{{Type: receipt.TypeBox, Children: body}}}, links
}
// TestMarkdownGoldens previews testdata/markdown/*.md inside a box.
func TestMarkdownGoldens(t *testing.T) {
paths, err := filepath.Glob(filepath.Join("testdata", "markdown", "*.md"))
if err != nil {
t.Fatal(err)
}
if len(paths) == 0 {
t.Fatal("no texts in testdata/markdown")
}
for _, path := range paths {
name := strings.TrimSuffix(filepath.Base(path), ".md")
t.Run(name, func(t *testing.T) {
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
text := string(data)
job, links := markdownBox(text)
got := previewText(t, job)
for _, l := range links {
got += "link: " + l.Label + " -> " + l.URL + "\n"
}
checkGolden(t, filepath.Join("testdata", "markdown", name+".txt"), got)
})
}
}
func TestMarkdownInline(t *testing.T) {
tests := []struct{ in, want string }{
{"**/var** is at *94%* on nas01", "/var is at 94% on nas01"},
{"__bold__ and _it_ and ~~gone~~ and `code`", "bold and it and gone and code"},
{"snake_case_name and 2 * 3 * 4", "snake_case_name and 2 * 3 * 4"},
{"_a_ _b_", "a b"},
{`\*not italic\* and \_kept\_`, "*not italic* and _kept_"},
{"see [docs](https://example.com/docs) and [local](/x)", "see docs and local"},
{"![chart](https://example.com/c.png) and ![](x.png)", "[image: chart] and [image]"},
{"** not bold **", "** not bold **"},
// Code spans and bare URLs keep their marks.
{"run `__init__.py` and `**/*.go`", "run __init__.py and **/*.go"},
{"see https://host/__debug__/ or *now*", "see https://host/__debug__/ or now"},
{"`a` **b** `c_d_e` _f_", "a b c_d_e f"},
// A URL ends before the marks and punctuation that follow it.
{"**https://example.com/status**", "https://example.com/status"},
{"**Down: https://status.lan**", "Down: https://status.lan"},
{"*https://example.com*", "https://example.com"},
{"_https://example.com/x_", "https://example.com/x"},
{"~~https://old.example.com~~ moved", "https://old.example.com moved"},
{"Run https://ci.example.com/job/`nightly` now", "Run https://ci.example.com/job/nightly now"},
{"see https://example.com/a_(b) and (https://example.com/c).", "see https://example.com/a_(b) and (https://example.com/c)."},
{"Is it https://example.com?", "Is it https://example.com?"},
// Marks inside a URL stay part of it.
{"Home: https://example.com/~bob/__init__.py", "Home: https://example.com/~bob/__init__.py"},
{"https://example.com/~alice/_drafts_/post", "https://example.com/~alice/_drafts_/post"},
{"https://example.com/a*b*c", "https://example.com/a*b*c"},
{"Logs: https://kibana.lan/app/discover#/?_a=(index:'logs-*',query:(language:kuery,query:'host:*'))",
"Logs: https://kibana.lan/app/discover#/?_a=(index:'logs-*',query:(language:kuery,query:'host:*'))"},
{"\uE100 literal", " literal"},
}
for _, tt := range tests {
body, _ := modules.MarkdownBody(tt.in)
if len(body) != 1 || body[0].Text != tt.want {
t.Errorf("%q: %+v, want the text %q", tt.in, body, tt.want)
}
}
_, links := modules.MarkdownBody("[docs](https://example.com/docs) [local](/x) [mail](mailto:a@b)")
if len(links) != 1 || links[0] != (modules.Link{Label: "docs", URL: "https://example.com/docs"}) {
t.Errorf("links %+v, want only the https one", links)
}
}
func TestMarkdownLines(t *testing.T) {
tests := []struct {
in string
want []receipt.Element
}{
{"# H1\n## H2\n### H3 ###", []receipt.Element{
{Type: "text", Text: "H1", Bold: true}, {Type: "text", Text: "H2", Bold: true}, {Type: "text", Text: "H3", Bold: true}}},
{"- a\n* b\n+ c", []receipt.Element{{Type: "list", Bullet: "dot", Items: []string{"a", "b", "c"}}}},
{"1. a\n2) b\n10. c", []receipt.Element{{Type: "list", Bullet: "number", Items: []string{"a", "b", "c"}}}},
{"- a\n1. b", []receipt.Element{
{Type: "list", Bullet: "dot", Items: []string{"a"}}, {Type: "list", Bullet: "number", Items: []string{"b"}}}},
{"> one\n> two", []receipt.Element{{Type: "text", Text: "│ one\n│ two"}}},
{"---\n***\n- - -", []receipt.Element{{Type: "rule"}, {Type: "rule"}, {Type: "rule"}}},
{"a\n\n\n\nb\n\n", []receipt.Element{{Type: "text", Text: "a"}, {Type: "feed"}, {Type: "text", Text: "b"}}},
{"\n\na", []receipt.Element{{Type: "text", Text: "a"}}},
{"plain\nlines", []receipt.Element{{Type: "text", Text: "plain\nlines"}}},
{"-not a list\n#not a heading", []receipt.Element{{Type: "text", Text: "-not a list\n#not a heading"}}},
}
for _, tt := range tests {
got, _ := modules.MarkdownBody(tt.in)
if !sameElements(got, tt.want) {
t.Errorf("%q:\n got %+v\nwant %+v", tt.in, got, tt.want)
}
}
fence, _ := modules.MarkdownBody("```sh\n**kept** as written\n- not a list\n```")
if len(fence) != 1 || fence[0].Text != "**kept** as written\n- not a list" || fence[0].Wrap == nil || *fence[0].Wrap {
t.Errorf("fence: %+v", fence)
}
}
func sameElements(a, b []receipt.Element) bool {
if len(a) != len(b) {
return false
}
for i := range a {
x, y := a[i], b[i]
if x.Type != y.Type || x.Text != y.Text || x.Bold != y.Bold || x.Bullet != y.Bullet ||
strings.Join(x.Items, "|") != strings.Join(y.Items, "|") {
return false
}
}
return true
}
// FuzzMarkdown lays out any text as markdown in a box: it must never
// panic, always build a valid job, and every line it prints must fit the
// paper.
func FuzzMarkdown(f *testing.F) {
for _, seed := range []string{
"# H\n- a\n1. b\n> q\n---\n```\ncode\n```\n**b** _i_ [l](https://x/) ![a](u)",
"```\nunclosed",
"- \n#\n>\n- [ ] task",
strings.Repeat("- item\n", 250),
"\\*\\_\\`\\\\",
"\uE02A literal private use",
"**https://example.com/status** ~~https://old.example.com~~ Run https://ci.example.com/job/`nightly` (https://example.com/c).",
} {
f.Add(seed)
}
profile, err := escpos.LookupProfile("tm-t88")
if err != nil {
f.Fatal(err)
}
renderer := receipt.NewRenderer(receipt.Options{
Profile: profile, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000,
}, noFetch{})
columns := profile.Columns(escpos.FontA)
env := modules.Env{Now: time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC), Location: time.UTC, TimeLayout: "02 Jan 15:04"}
f.Fuzz(func(t *testing.T, text string) {
modules.MarkdownBody(text)
for _, priority := range []int{1, 3, 5} {
n := modules.Notice{Title: "T", Message: text, Markdown: true, Priority: priority}
job, _ := modules.Card(n, modules.CardOptions{MaxLines: 400}, env)
if job.Elements[0].Type == receipt.TypeText {
t.Fatalf("priority %d: the card fell back to the plain receipt", priority)
}
p, err := renderer.Preview(context.Background(), job)
if err != nil {
t.Fatalf("priority %d: Preview: %v", priority, err)
}
for _, line := range p.Lines {
if line.Kind != escpos.LineText || smallFont(line) {
continue
}
if utf8.RuneCountInString(line.Text) > columns {
t.Fatalf("priority %d: line %q is longer than %d columns", priority, line.Text, columns)
}
}
}
})
}
// smallFont reports whether line prints in Font B, whose lines are longer.
func smallFont(line escpos.PreviewLine) bool {
for _, r := range line.Runs {
if r.Font == escpos.FontB {
return true
}
}
return false
}
+112
View File
@@ -0,0 +1,112 @@
package modules
import (
"maps"
"strings"
"uberbringer/internal/pkg/receipt"
)
// maxTitleMarkers is how many tag markers go in front of a title.
const maxTitleMarkers = 2
// tagMarkers are the markers printed for ntfy's emoji tags, by tag. Every
// glyph prints on CP437.
var tagMarkers = map[string]string{
"warning": "[!]",
"rotating_light": "(!)",
"fire": "(!)",
"boom": "(!)",
"white_check_mark": "[√]",
"heavy_check_mark": "[√]",
"ballot_box_with_check": "[√]",
"x": "[x]",
"negative_squared_cross_mark": "[x]",
"no_entry": "[x]",
"no_entry_sign": "[x]",
"information_source": "(i)",
"question": "(?)",
"+1": "(+1)",
"thumbsup": "(+1)",
"-1": "(-1)",
"thumbsdown": "(-1)",
"loudspeaker": "<!>",
"mega": "<!>",
"tada": `\o/`,
"skull": "x_x",
"hourglass": "(...)",
}
// typedEmoji are emoji typed into a text that print as the marker of a
// tag. A variation selector after one is removed with the other emoji.
var typedEmoji = []struct{ emoji, tag string }{
{"⚠", "warning"},
{"✅", "white_check_mark"},
{"❌", "x"},
{"🚨", "rotating_light"},
{"👍", "+1"},
}
// Markers maps tags to the markers printed for them. A tag with an empty
// marker is hidden.
type Markers map[string]string
// NewMarkers returns the built-in markers with overrides applied. A key of
// overrides is a tag; an empty value hides it.
func NewMarkers(overrides map[string]string) Markers {
m := maps.Clone(tagMarkers)
for tag, marker := range overrides {
m[strings.ToLower(tag)] = marker
}
return m
}
// lookup returns the marker for tag, matched in lower case, and whether
// the tag has one: an empty marker hides the tag.
func (m Markers) lookup(tag string) (string, bool) {
marker, ok := m[strings.ToLower(tag)]
return marker, ok
}
// clean prepares text from a notification for the card: the typed emoji
// that have markers become them, and the other emoji are removed, those
// whose tag is hidden too.
func (m Markers) clean(s string) string {
for _, e := range typedEmoji {
if !strings.Contains(s, e.emoji) {
continue
}
if marker, _ := m.lookup(e.tag); marker != "" {
s = strings.ReplaceAll(s, e.emoji, marker)
}
}
return receipt.StripEmoji(s)
}
// sortTags splits the first MaxTags tags into the markers for the title,
// at most maxTitleMarkers of them and each once, and the tags printed as
// text: those without a marker and those with one when the title has no
// room for it, cleaned and cut to MaxTag. Hidden tags, and tags that
// cleaning leaves empty, appear in neither.
func (m Markers) sortTags(tags []string) (markers, text []string) {
seen := make(map[string]bool)
for _, tag := range tags[:min(len(tags), MaxTags)] {
tag = strings.TrimSpace(tag)
if tag == "" {
continue
}
marker, ok := m.lookup(tag)
switch {
case ok && marker == "":
case ok && seen[marker]:
case ok && len(markers) < maxTitleMarkers:
seen[marker] = true
markers = append(markers, marker)
default:
if tag = cut(strings.TrimSpace(m.clean(tag)), MaxTag); tag != "" {
text = append(text, tag)
}
}
}
return markers, text
}
+3 -3
View File
@@ -20,7 +20,7 @@ import (
"uberbringer/internal/pkg/receipt"
)
var update = flag.Bool("update", false, "rewrite testdata/note/*.txt from the current output")
var update = flag.Bool("update", false, "rewrite the golden previews in testdata/*/*.txt from the current output")
// fixedEnv is 29 Nov 2026 21:04:05 UTC in Europe/London, which is on GMT
// then.
@@ -117,8 +117,8 @@ func TestNoteGoldens(t *testing.T) {
}
}
// TestNoteMockup pins the note the formatters plan shows as mockup 5.
func TestNoteMockup(t *testing.T) {
// TestNoteShoppingList pins the preview of a titled note with a checklist.
func TestNoteShoppingList(t *testing.T) {
body := `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
job, err := modules.Note().Build(context.Background(), []byte(body), fixedEnv(t))
if err != nil {
+171
View File
@@ -0,0 +1,171 @@
package modules
import (
"net/url"
"path"
"strings"
"time"
)
// Priorities of a Notice.
const (
minPriority = 1
defaultPriority = 3
highPriority = 4
maxPriority = 5
)
// Notice limits. notify refuses a payload over them, and a card cuts what
// is longer, so that a notification from any source prints at a bounded
// length. Lengths are in characters, except where they say bytes.
const (
MaxTitle = 250
MaxTopic = 64 // as ntfy's topic names
MaxTags = 20
MaxTag = 64
MaxLabel = 64
MaxFileName = 128
MaxMessage = 4096 // bytes, as ntfy's default message limit
MaxURL = 2000 // bytes
)
// priorityNames are the names a priority may be given by, as ntfy takes
// them.
var priorityNames = map[string]int{
"min": 1,
"low": 2,
"default": 3,
"high": 4,
"max": 5,
"urgent": 5,
}
// Notice is a notification to print: what the notify module takes, and
// what an ntfy message carries.
type Notice struct {
// ID is the notification's ID at its source, if it has one.
ID string
Topic string
Title string
Message string
// Markdown is set when Message is written in markdown.
Markdown bool
// Priority is 1-5; any other value counts as 3.
Priority int
Tags []string
// Time is when the notification was sent. The zero time means the
// time the card is built.
Time time.Time
// Links are the URLs the notification points to, in order.
Links []Link
// Image is the URL of an image to print.
Image string
// File is an attached file. An image the printer can print is printed;
// any other file is named.
File *File
// Updated is set when the notification is known to replace one printed
// before; its title is then marked "(updated)". One message on its own
// cannot tell, so the notify and ntfy modules never set it.
Updated bool
}
// Link is a URL a notification points to, with its label if it has one.
type Link struct {
Label string
URL string
}
// File is a file attached to a notification.
type File struct {
Name string
// Type is the media type, e.g. image/png; it may be empty.
Type string
// Size is in bytes; 0 when unknown.
Size int64
URL string
// Expires is when the file stops being available; the zero time means
// never.
Expires time.Time
}
// priority returns n's priority, with a value outside 1-5 counted as the
// default.
func (n Notice) priority() int {
if n.Priority < minPriority || n.Priority > maxPriority {
return defaultPriority
}
return n.Priority
}
// printableImageTypes are the media types the renderer decodes, and
// printableImageExts the file name extensions it takes as them.
var (
printableImageTypes = []string{"image/png", "image/jpeg", "image/gif", "image/webp"}
printableImageExts = []string{".png", ".jpg", ".jpeg", ".gif", ".webp"}
)
// printableImage reports whether f is an image the renderer can print:
// its type says so, or it has no type and its name or URL ends in an image
// extension.
func (f File) printableImage() bool {
if f.Type != "" {
media, _, _ := strings.Cut(strings.ToLower(f.Type), ";")
return containsFold(printableImageTypes, strings.TrimSpace(media))
}
for _, name := range []string{f.Name, urlPath(f.URL)} {
if containsFold(printableImageExts, path.Ext(name)) {
return true
}
}
return false
}
// expired reports whether f is no longer available at now.
func (f File) expired(now time.Time) bool {
return !f.Expires.IsZero() && !now.Before(f.Expires)
}
// webURL reports whether s is an absolute http or https URL.
func webURL(s string) bool {
u, err := url.Parse(s)
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != ""
}
// urlPath returns the path of the URL s, or "" if it is not one.
func urlPath(s string) string {
u, err := url.Parse(s)
if err != nil {
return ""
}
return u.Path
}
// shortURL is the host and path of the URL s, without a trailing slash,
// e.g. grafana.lan/d/disk.
func shortURL(s string) string {
u, err := url.Parse(s)
if err != nil || u.Host == "" {
return s
}
return strings.TrimSuffix(u.Host+u.Path, "/")
}
// fileName is the last path segment of the URL s, or its host.
func fileName(s string) string {
if name := path.Base(urlPath(s)); name != "." && name != "/" && name != "" {
return name
}
return shortURL(s)
}
+230
View File
@@ -0,0 +1,230 @@
package modules
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"strconv"
"strings"
"time"
"unicode/utf8"
"uberbringer/internal/pkg/receipt"
)
// Notify payload limits, besides the notice limits.
const (
// MaxNotifyActions is how many actions a notification may have. With
// click, at most maxLinks links print in all.
MaxNotifyActions = 3
// maxUnixSeconds is the last second of the year 9999.
maxUnixSeconds = 253402300799
)
// Notify returns the notify module: a notification card from a title,
// message, priority and tags, for scripts, cron jobs and phone shortcuts.
func Notify() Module {
return notify{}
}
type notify struct{}
// notifyPayload is the body of a notification. priority and time take a
// number or a string, so they are checked after decoding.
type notifyPayload struct {
Title string `json:"title"`
Message string `json:"message"`
Priority any `json:"priority"`
Tags []string `json:"tags"`
Topic string `json:"topic"`
Click string `json:"click"`
Markdown bool `json:"markdown"`
Time any `json:"time"`
Actions []json.RawMessage `json:"actions"`
Image string `json:"image"`
}
// notifyAction is a link of a notification.
type notifyAction struct {
Label string `json:"label"`
URL string `json:"url"`
}
func (notify) Name() string { return "notify" }
func (notify) Description() string {
return "Notification card from title, message, priority and tags"
}
// Build lays the notification out as a card.
func (notify) Build(_ context.Context, body []byte, env Env) (receipt.Job, error) {
var p notifyPayload
if err := DecodeStrict(body, &p); err != nil {
return receipt.Job{}, err
}
n, problems := p.notice()
if len(problems) > 0 {
return receipt.Job{}, &PayloadError{Problems: problems}
}
return noticeJob(n, env)
}
// notice checks the payload and turns it into a Notice.
func (p notifyPayload) notice() (Notice, []string) {
n := Notice{
Topic: p.Topic,
Title: p.Title,
Message: p.Message,
Markdown: p.Markdown,
Tags: p.Tags,
Image: p.Image,
}
var problems []string
switch size := len(p.Message); {
case strings.TrimSpace(p.Message) == "":
problems = append(problems, "message: required")
case size > MaxMessage:
problems = append(problems, fmt.Sprintf("message: %d bytes, limit is %d", size, MaxMessage))
}
problems = append(problems, tooLong("title", p.Title, MaxTitle)...)
problems = append(problems, tooLong("topic", p.Topic, MaxTopic)...)
if count := len(p.Tags); count > MaxTags {
problems = append(problems, fmt.Sprintf("tags: %d tags, limit is %d", count, MaxTags))
}
for i, tag := range p.Tags {
problems = append(problems, tooLong(fmt.Sprintf("tags[%d]", i), tag, MaxTag)...)
}
var err error
if n.Priority, err = parsePriority(p.Priority); err != nil {
problems = append(problems, "priority: "+err.Error())
}
if n.Time, err = parseTime(p.Time); err != nil {
problems = append(problems, "time: "+err.Error())
}
if p.Click != "" {
if problem := urlProblem("click", p.Click); problem != "" {
problems = append(problems, problem)
} else {
n.Links = append(n.Links, Link{URL: p.Click})
}
}
if p.Image != "" {
if problem := urlProblem("image", p.Image); problem != "" {
problems = append(problems, problem)
}
}
if count := len(p.Actions); count > MaxNotifyActions {
problems = append(problems, fmt.Sprintf("actions: %d actions, limit is %d", count, MaxNotifyActions))
}
for i, raw := range p.Actions {
field := fmt.Sprintf("actions[%d]", i)
var a notifyAction
if err := DecodeStrict(raw, &a); err != nil {
problems = append(problems, nestedProblems(field, err)...)
continue
}
problems = append(problems, tooLong(field+".label", a.Label, MaxLabel)...)
if a.URL == "" {
problems = append(problems, field+".url: required")
} else if problem := urlProblem(field+".url", a.URL); problem != "" {
problems = append(problems, problem)
} else {
n.Links = append(n.Links, Link(a))
}
}
return n, problems
}
// tooLong returns a problem for field when s is longer than limit
// characters.
func tooLong(field, s string, limit int) []string {
if n := utf8.RuneCountInString(s); n > limit {
return []string{fmt.Sprintf("%s: %d characters, limit is %d", field, n, limit)}
}
return nil
}
// urlProblem returns the problem with field's URL s, or "".
func urlProblem(field, s string) string {
switch {
case !webURL(s):
return field + ": must be an http or https URL"
case len(s) > MaxURL:
return fmt.Sprintf("%s: %d bytes, limit is %d", field, len(s), MaxURL)
}
return ""
}
// nestedProblems prefixes each problem of a nested object's *PayloadError
// with field, the object's place in the payload.
func nestedProblems(field string, err error) []string {
var pe *PayloadError
if !errors.As(err, &pe) {
return []string{field + ": " + err.Error()}
}
problems := make([]string, len(pe.Problems))
for i, problem := range pe.Problems {
if rest, ok := strings.CutPrefix(problem, "body: "); ok {
problems[i] = field + ": " + rest
continue
}
problems[i] = field + "." + problem
}
return problems
}
// parsePriority reads a priority given as 1-5 or by name. nil is the
// default priority.
func parsePriority(v any) (int, error) {
bad := fmt.Errorf("must be 1-5, or min, low, default, high, max or urgent")
switch p := v.(type) {
case nil:
return defaultPriority, nil
case float64:
if p != math.Trunc(p) || p < minPriority || p > maxPriority {
return 0, bad
}
return int(p), nil
case string:
s := strings.ToLower(strings.TrimSpace(p))
if n, ok := priorityNames[s]; ok {
return n, nil
}
if n, err := strconv.Atoi(s); err == nil && n >= minPriority && n <= maxPriority {
return n, nil
}
}
return 0, bad
}
// parseTime reads a time given as Unix seconds or in RFC 3339. nil is the
// zero time, which stands for the time the card is built.
func parseTime(v any) (time.Time, error) {
bad := fmt.Errorf("must be Unix seconds or an RFC 3339 time, e.g. 2026-11-29T21:04:05Z")
switch t := v.(type) {
case nil:
return time.Time{}, nil
case float64:
if t != math.Trunc(t) || t <= 0 || t > maxUnixSeconds {
return time.Time{}, bad
}
return time.Unix(int64(t), 0), nil
case string:
parsed, err := time.Parse(time.RFC3339, strings.TrimSpace(t))
if err == nil {
return parsed, nil
}
}
return time.Time{}, bad
}
// noticeJob lays out n as a card with the options in env. A *FallbackError
// comes with the plain receipt, which still prints.
func noticeJob(n Notice, env Env) (receipt.Job, error) {
return Card(n, env.Card, env)
}
+124
View File
@@ -0,0 +1,124 @@
package modules
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"time"
"uberbringer/internal/pkg/ntfy"
"uberbringer/internal/pkg/receipt"
)
// Ntfy returns the ntfy module: the card of one ntfy message, as the ntfy
// command line client passes it to a command in $NTFY_RAW.
func Ntfy() Module {
return ntfyModule{}
}
type ntfyModule struct{}
func (ntfyModule) Name() string { return "ntfy" }
func (ntfyModule) Description() string {
return "One ntfy message object, e.g. the CLI's $NTFY_RAW"
}
// Build lays out the message as a card. The body is decoded leniently:
// fields it does not know are ignored, so that messages from newer ntfy
// versions still print. Events other than message, and messages with a
// binary body, give ErrSkip.
func (ntfyModule) Build(_ context.Context, body []byte, env Env) (receipt.Job, error) {
m, err := decodeNtfy(body)
if err != nil {
return receipt.Job{}, err
}
n, err := FromNtfy(m)
if err != nil {
return receipt.Job{}, err
}
return noticeJob(n, env)
}
// decodeNtfy decodes body, one JSON object, as an ntfy message, ignoring
// unknown fields. A problem is returned as a *PayloadError.
func decodeNtfy(body []byte) (ntfy.Message, error) {
var (
object map[string]json.RawMessage
m ntfy.Message
)
dec := json.NewDecoder(bytes.NewReader(body))
if err := dec.Decode(&object); err != nil {
return m, &PayloadError{Problems: []string{bodyProblem(err)}}
}
if object == nil {
return m, &PayloadError{Problems: []string{"body: expected a JSON object, got null"}}
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return m, &PayloadError{Problems: []string{"body: trailing data after the payload"}}
}
if err := json.Unmarshal(body, &m); err != nil {
var typeErr *json.UnmarshalTypeError
if errors.As(err, &typeErr) && typeErr.Field != "" {
return m, &PayloadError{Problems: []string{fmt.Sprintf("%s: expected %s", typeErr.Field, describe(typeErr.Type))}}
}
return m, &PayloadError{Problems: []string{"body: " + err.Error()}}
}
return m, nil
}
// FromNtfy turns an ntfy message into a Notice. It returns ErrSkip for an
// event other than message, such as open or keepalive, and for a message
// whose body is binary (encoding base64). A message without an event
// counts as a message.
//
// The links are the click URL and the view actions' URLs; the other
// actions are left out, since their headers, bodies and values can hold
// secrets. The text ntfy gives a file sent without a message is dropped,
// since the file prints on its own. The notice is never marked as an
// update: a publisher may choose a message's sequence ID, so one message
// cannot tell the first of its sequence from one that replaces it.
func FromNtfy(m ntfy.Message) (Notice, error) {
switch m.Event {
case "", ntfy.EventMessage:
default:
return Notice{}, ErrSkip
}
if strings.EqualFold(m.Encoding, ntfy.EncodingBase64) {
return Notice{}, ErrSkip
}
n := Notice{
ID: m.ID,
Topic: m.Topic,
Title: m.Title,
Message: m.Message,
Markdown: strings.EqualFold(m.ContentType, ntfy.ContentTypeMarkdown),
Priority: m.Priority(),
Tags: m.Tags,
}
if m.Time > 0 {
n.Time = time.Unix(m.Time, 0)
}
if m.Click != "" {
n.Links = append(n.Links, Link{URL: m.Click})
}
for _, a := range m.Actions {
if strings.EqualFold(a.Action, ntfy.ActionView) {
n.Links = append(n.Links, Link{Label: a.Label, URL: a.URL})
}
}
if a := m.Attachment; a != nil && a.URL != "" {
if n.Message == fmt.Sprintf(ntfy.AttachmentMessage, a.Name) {
n.Message = ""
}
n.File = &File{Name: a.Name, Type: a.Type, Size: a.Size, URL: a.URL}
if a.Expires > 0 {
n.File.Expires = time.Unix(a.Expires, 0)
}
}
return n, nil
}
+19 -4
View File
@@ -32,8 +32,9 @@ func (e *PayloadError) Error() string {
return "invalid payload: " + strings.Join(e.Problems, "; ")
}
// Env is what a module may know about the time a receipt is built at. A
// module never reads the clock itself, so that its output is reproducible.
// Env is what a module may know when it builds a receipt: the time it is
// built at, how times print and how notifications are laid out. A module
// never reads the clock itself, so that its output is reproducible.
type Env struct {
// Now is the time the receipt is built at.
Now time.Time
@@ -44,15 +45,27 @@ type Env struct {
// TimeLayout is the Go time layout times are printed in, e.g.
// "02 Jan 15:04".
TimeLayout string
// Card shapes the cards of the notification modules.
Card CardOptions
}
// Stamp returns Now in Location, formatted with TimeLayout.
func (e Env) Stamp() string {
return e.Format(e.Now)
}
// Format returns t in Location, formatted with TimeLayout. The zero time
// stands for Now.
func (e Env) Format(t time.Time) string {
if t.IsZero() {
t = e.Now
}
loc := e.Location
if loc == nil {
loc = time.Local
}
return e.Now.In(loc).Format(e.TimeLayout)
return t.In(loc).Format(e.TimeLayout)
}
// Module builds a receipt from its own payload format.
@@ -67,7 +80,9 @@ type Module interface {
// Build turns body into a job. It returns a *PayloadError for a body
// that is not a valid payload, and ErrSkip for one that asks for
// nothing to be printed. The job it returns is expected to pass
// Job.Validate; one that does not is a bug in the module.
// Job.Validate; one that does not is a bug in the module. A
// *FallbackError comes with a plain job that still prints: the module
// met a bug of its own and printed what it could.
Build(ctx context.Context, body []byte, env Env) (receipt.Job, error)
}
+9
View File
@@ -0,0 +1,9 @@
── alerts · 29 Nov 21:04 ─────────────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
┌─ [!] Disk almost full ─────────────────┐
│ /var is at 94% on nas01 │
│ │
│ Tags: nas01 │
└─────────────── alerts · 29 Nov 21:04 ──┘
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
── alerts · 29 Nov 21:04 ─────────────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
── alerts · 29 Nov 21:04 ─────────────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
┌─ [!] Disk almost full ─────────────────┐
│ /var is at 94% on nas01 │
│ │
│ Tags: nas01 │
└─────────────── alerts · 29 Nov 21:04 ──┘
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
── alerts · 29 Nov 21:04 ─────────────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
┌─ [!] Disk almost full ─────────────────┐
│ /var is at 94% on nas01 │
│ │
│ Tags: nas01 │
└─────────────── alerts · 29 Nov 21:04 ──┘
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
┌─ [!] Disk almost full ─────────────────┐
│ /var is at 94% on nas01 │
│ │
│ Tags: nas01 │
└─────────────── alerts · 29 Nov 21:04 ──┘
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
── alerts · 29 Nov 21:04 ─────────────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+11
View File
@@ -0,0 +1,11 @@
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+11
View File
@@ -0,0 +1,11 @@
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
── HIGH · alerts · 29 Nov 21:04 ──────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+13
View File
@@ -0,0 +1,13 @@
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
╔════════════════════════════════════════╗
║ [!] Disk almost full ║
╠════════════════════════════════════════╣
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+13
View File
@@ -0,0 +1,13 @@
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
╔════════════════════════════════════════╗
║ [!] Disk almost full ║
╠════════════════════════════════════════╣
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
── URGENT · alerts · 29 Nov 21:04 ────────
[!] Disk almost full
/var is at 94% on nas01
Tags: nas01
[qr: https://grafana.lan/d/disk]
Open dashboard
- - - - - - - partial cut - - - - - - - -
+22
View File
@@ -0,0 +1,22 @@
# Deployed
The **web** and __api__ services are *live* on ~~staging~~ production.
## Changes
- Faster `search`
* New [status page](https://status.example.com)
+ Fixed _login_ loop in snake_case_name, a long item that wraps onto a second line
1. Drain
2. Migrate
3. Restart
> Rollback with make rollback if anything breaks, quoted on two lines
> of its own.
---
```
$ kubectl get pods
web-7d9f-very-long-pod-name-that-is-longer-than-the-box 1/1 Running
```
![chart](https://example.com/chart.png)
Escaped \*stars\* stay.
+29
View File
@@ -0,0 +1,29 @@
┌────────────────────────────────────────┐
│ Deployed │
│ The web and api services are live on │
│ staging production. │
│ │
│ Changes │
│ · Faster search │
│ · New status page │
│ · Fixed login loop in snake_case_name, │
│ a long item that wraps onto a second │
│ line │
│ │
│ 1. Drain │
│ 2. Migrate │
│ 3. Restart │
│ │
│ │ Rollback with make rollback if │
│ anything breaks, quoted on two lines │
│ │ of its own. │
│ │
├────────────────────────────────────────┤
│ $ kubectl get pods │
│ web-7d9f-very-long-pod-name-that-is-lo │
│ nger-than-the-box 1/1 Running │
│ [image: chart] │
│ Escaped *stars* stay. │
└────────────────────────────────────────┘
- - - - - - - partial cut - - - - - - - -
link: status page -> https://status.example.com
+4
View File
@@ -0,0 +1,4 @@
{"title":"Disk almost full","message":"/var is at 94% on nas01","priority":"high","tags":["warning","nas01"],
"topic":"alerts","click":"https://grafana.lan/d/disk","markdown":false,"time":"2025-11-29T21:04:05Z",
"actions":[{"label":"Open dashboard","url":"https://grafana.lan/d/disk"},{"label":"Runbook","url":"https://wiki.lan/runbooks/disk-full"}],
"image":"https://grafana.lan/render/disk.png"}
+16
View File
@@ -0,0 +1,16 @@
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
[qr: https://grafana.lan/d/disk]
Open dashboard
[qr: https://wiki.lan/runbooks/disk-full]
Runbook
[image 384 dots: disk.png]
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title":"Log tail","topic":"logs","priority":3,"message":"line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11\nline 12\nline 13\nline 14\nline 15\nline 16\nline 17\nline 18\nline 19\nline 20\nline 21\nline 22\nline 23\nline 24\nline 25\nline 26\nline 27\nline 28\nline 29\nline 30\nline 31\nline 32\nline 33\nline 34\nline 35\nline 36\nline 37\nline 38\nline 39\nline 40\nline 41\nline 42\nline 43\n\n"}
+44
View File
@@ -0,0 +1,44 @@
┌─ Log tail ─────────────────────────────┐
│ line 1 │
│ line 2 │
│ line 3 │
│ line 4 │
│ line 5 │
│ line 6 │
│ line 7 │
│ line 8 │
│ line 9 │
│ line 10 │
│ line 11 │
│ line 12 │
│ line 13 │
│ line 14 │
│ line 15 │
│ line 16 │
│ line 17 │
│ line 18 │
│ line 19 │
│ line 20 │
│ line 21 │
│ line 22 │
│ line 23 │
│ line 24 │
│ line 25 │
│ line 26 │
│ line 27 │
│ line 28 │
│ line 29 │
│ line 30 │
│ line 31 │
│ line 32 │
│ line 33 │
│ line 34 │
│ line 35 │
│ line 36 │
│ line 37 │
│ line 38 │
│ line 39 │
│ line 40 │
│ ... 3 more lines │
└───────────────── logs · 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title":"Shopping","message":"## Today\n- milk\n- **eggs**\n\nSee [the list](https://lists.example.com/shopping)","markdown":true,"priority":2,"time":1764450245}
+11
View File
@@ -0,0 +1,11 @@
── 29 Nov 21:04 ──────────────────────────
Shopping
Today
· milk
· eggs
See the list
[qr: https://lists.example.com/shopping]
the list
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"message":"Back at 3"}
+4
View File
@@ -0,0 +1,4 @@
┌─ Notification ─────────────────────────┐
│ Back at 3 │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,6 @@
{"id":"Act0Private1","time":1764450245,"event":"message","topic":"home","title":"Garage open","message":"The garage door has been open for 10 minutes.","priority":4,
"actions":[
{"id":"a1","action":"http","label":"Close door","url":"https://hooks.example.com/garage/close-SECRETPATH","method":"POST","headers":{"Authorization":"Bearer SECRETHEADER"},"body":"SECRETBODY","clear":true},
{"id":"a2","action":"broadcast","label":"Tasker","intent":"io.example.SECRETINTENT","extras":{"cmd":"SECRETEXTRA"},"clear":false},
{"id":"a3","action":"copy","label":"Copy code","value":"SECRETVALUE","clear":false},
{"id":"a4","action":"view","label":"Camera","url":"https://cam.example.com/garage","clear":false}]}
+10
View File
@@ -0,0 +1,10 @@
╔═ HIGH ═════════════════════════════════╗
║ Garage open ║
╟────────────────────────────────────────╢
║ The garage door has been open for 10 ║
║ minutes. ║
╚═════════════════ home · 29 Nov 21:04 ══╝
[qr: https://cam.example.com/garage]
Camera
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,2 @@
{"id":"Att0Expired1","time":1764400000,"event":"message","topic":"cams","title":"Doorbell","message":"Someone is at the door",
"attachment":{"name":"door.jpg","size":980,"expires":1764410000,"url":"https://ntfy.example.com/file/Att0Expired1.jpg"}}
@@ -0,0 +1,6 @@
┌─ Doorbell ─────────────────────────────┐
│ Someone is at the door │
│ │
│ File ................ door.jpg (980 B) │
└───────────────── cams · 29 Nov 07:06 ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,3 @@
{"id":"Att0File0001","time":1764450245,"event":"message","topic":"reports","priority":3,
"message":"You received a file: report.pdf",
"attachment":{"name":"report.pdf","type":"application/pdf","size":1468006,"expires":1764461045,"url":"https://ntfy.example.com/file/Att0File0001.pdf"}}
@@ -0,0 +1,4 @@
┌─ reports ──────────────────────────────┐
│ File ............. report.pdf (1.4 MB) │
└────────────── reports · 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,2 @@
{"id":"Att0Untyped1","time":1764450245,"event":"message","topic":"cams","title":"Doorbell","message":"Someone is at the door",
"attachment":{"name":"door.jpg","url":"https://ntfy.example.com/file/Att0Untyped1.jpg"}}
@@ -0,0 +1,6 @@
┌─ Doorbell ─────────────────────────────┐
│ Someone is at the door │
└───────────────── cams · 29 Nov 21:04 ──┘
[image 384 dots: Att0Untyped1.jpg]
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"id":"Emoji0000001","time":1764450245,"event":"message","topic":"home","title":"✅ Laundry done 🎉","message":"⚠️ Empty the lint filter 🧺\n👍 Thanks!","priority":3,"tags":["tada","skull","fire","hourglass","custom tag"]}
+7
View File
@@ -0,0 +1,7 @@
┌─ \o/ x_x [√] Laundry done ─────────────┐
│ [!] Empty the lint filter │
│ (+1) Thanks! │
│ │
│ Tags: fire, hourglass, custom tag │
└───────────────── home · 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+2
View File
@@ -0,0 +1,2 @@
{"id":"Md0000000001","time":1764450245,"event":"message","topic":"deploys","title":"Release v2.4.0","content_type":"text/markdown",
"message":"# Deployed\nThe **web** and __api__ services are *live* on ~~staging~~ production.\n\n## Changes\n- Faster `search`\n* New [status page](https://status.example.com)\n+ Fixed _login_ loop in snake_case_name\n\n1. Drain\n2. Migrate\n3. Restart\n\n> Rollback with make rollback\n> if anything breaks.\n\n---\n```\n$ kubectl get pods\nweb-7d9f 1/1 Running\n```\n![chart](https://example.com/chart.png)\nEscaped \\*stars\\* stay.","priority":3}
+27
View File
@@ -0,0 +1,27 @@
┌─ Release v2.4.0 ───────────────────────┐
│ Deployed │
│ The web and api services are live on │
│ staging production. │
│ │
│ Changes │
│ · Faster search │
│ · New status page │
│ · Fixed login loop in snake_case_name │
│ │
│ 1. Drain │
│ 2. Migrate │
│ 3. Restart │
│ │
│ │ Rollback with make rollback │
│ │ if anything breaks. │
│ │
├────────────────────────────────────────┤
│ $ kubectl get pods │
│ web-7d9f 1/1 Running │
│ [image: chart] │
│ Escaped *stars* stay. │
└────────────── deploys · 29 Nov 21:04 ──┘
[qr: https://status.example.com]
status page
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"id":"NoTitle00001","time":1764450245,"event":"message","topic":"alerts","message":"Just a message"}
+4
View File
@@ -0,0 +1,4 @@
┌─ alerts ───────────────────────────────┐
│ Just a message │
└─────────────── alerts · 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,2 @@
{"id":"Kq7vN2pX9aLe","time":1764385920,"event":"message","topic":"backups","title":"Nightly backup",
"message":"restic: 2.1 GB added in 14m 02s, 0 errors.","tags":["white_check_mark","restic"]}
@@ -0,0 +1,7 @@
┌─ [√] Nightly backup ───────────────────┐
│ restic: 2.1 GB added in 14m 02s, 0 │
│ errors. │
│ │
│ Tags: restic │
└────────────── backups · 29 Nov 03:12 ──┘
- - - - - - - partial cut - - - - - - - -
+5
View File
@@ -0,0 +1,5 @@
{"id":"sPs71M8A2Tq9","time":1764450245,"event":"message","topic":"alerts","title":"Disk almost full",
"message":"**/var** is at *94%* on nas01","content_type":"text/markdown","priority":4,"tags":["warning","nas01"],
"click":"https://grafana.lan/d/disk",
"actions":[{"id":"a1","action":"view","label":"Open dashboard","url":"https://grafana.lan/d/disk","clear":false}],
"attachment":{"name":"graph.png","type":"image/png","size":33848,"expires":1764461045,"url":"https://ntfy.example.com/file/sPs71M8A2Tq9.png"}}
+13
View File
@@ -0,0 +1,13 @@
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 94% on nas01 ║
║ ║
║ Tags: nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
[qr: https://grafana.lan/d/disk]
Open dashboard
[image 384 dots: sPs71M8A2Tq9.png]
- - - - - - - partial cut - - - - - - - -
+2
View File
@@ -0,0 +1,2 @@
{"id":"Zp4cW8mR1sYb","time":1764385920,"event":"message","topic":"backups","title":"Prune finished",
"message":"41 snapshots kept, 3 removed.","priority":1}
+4
View File
@@ -0,0 +1,4 @@
── backups · 29 Nov 03:12 ────────────────
Prune finished
41 snapshots kept, 3 removed.
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1,2 @@
{"id":"Fb2xQm81kTz0","time":1764450245,"event":"message","topic":"backups","title":"Backup FAILED on nas01",
"message":"Job nightly-offsite exited with code 2 after 3h12m. Last good run: 2 days ago.","priority":5,"tags":["rotating_light"]}
+10
View File
@@ -0,0 +1,10 @@
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
╔════════════════════════════════════════╗
║ (!) Backup FAILED on nas01 ║
╠════════════════════════════════════════╣
║ Job nightly-offsite exited with code 2 ║
║ after 3h12m. Last good run: 2 days ║
║ ago. ║
╚══════════════ backups · 29 Nov 21:04 ══╝
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"id":"Upd0Second01","sequence_id":"Upd0First001","time":1764450245,"event":"message","topic":"alerts","title":"Disk almost full","message":"/var is at 97% on nas01","priority":4,"tags":["warning"]}
+6
View File
@@ -0,0 +1,6 @@
╔═ HIGH ═════════════════════════════════╗
║ [!] Disk almost full ║
╟────────────────────────────────────────╢
║ /var is at 97% on nas01 ║
╚═══════════════ alerts · 29 Nov 21:04 ══╝
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"id":"Future000001","time":1764450245,"event":"message","topic":"alerts","message":"From a newer ntfy","priority":3,"icon":"https://example.com/icon.png","poll_id":"x","future_field":{"nested":[1,2,3]},"expires":1764536645}
+4
View File
@@ -0,0 +1,4 @@
┌─ alerts ───────────────────────────────┐
│ From a newer ntfy │
└─────────────── alerts · 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"id":"Kq7vN2pX9aLe","time":1796063393,"event":"message","topic":"backups","title":"Nightly backup","message":"restic: 2.1 GB added in 14m 02s, 0 errors.","tags":["white_check_mark","restic"]}
+1
View File
@@ -0,0 +1 @@
{"id":"sPs71M8A2Tq9","time":1796063393,"event":"message","topic":"alerts","title":"Disk almost full","message":"**/var** is at *94%* on nas01","content_type":"text/markdown","priority":4,"tags":["warning","nas01"],"click":"https://grafana.lan/d/disk","actions":[{"id":"a1","action":"view","label":"Open dashboard","url":"https://grafana.lan/d/disk","clear":false}],"attachment":{"name":"graph.png","type":"image/png","size":884,"expires":1796074193,"url":"http://127.0.0.1:8099/graph.png"}}
+1
View File
@@ -0,0 +1 @@
{"id":"Zp4cW8mR1sYb","time":1796063393,"event":"message","topic":"backups","title":"Prune finished","message":"41 snapshots kept, 3 removed.","priority":1}
+1
View File
@@ -0,0 +1 @@
{"id":"Fb2xQm81kTz0","time":1796063393,"event":"message","topic":"backups","title":"Backup FAILED on nas01","message":"Job nightly-offsite exited with code 2 after 3h12m. Last good run: 2 days ago.","priority":5,"tags":["rotating_light"]}
+121
View File
@@ -0,0 +1,121 @@
// Package ntfy holds the wire types of ntfy (https://ntfy.sh), the
// notification service: the message objects its subscribe API streams, one
// JSON object per line.
package ntfy
// Event types of a Message.
const (
EventOpen = "open"
EventKeepalive = "keepalive"
EventMessage = "message"
EventPollRequest = "poll_request"
EventMessageDelete = "message_delete"
EventMessageClear = "message_clear"
)
// Priorities. A message without one has the default priority.
const (
PriorityMin = 1
PriorityLow = 2
PriorityDefault = 3
PriorityHigh = 4
PriorityMax = 5
)
// Content types and encodings of a message body.
const (
ContentTypeMarkdown = "text/markdown"
EncodingBase64 = "base64"
)
// Message is one object of the subscribe API, such as the ntfy command
// line client passes to a command in $NTFY_RAW. Only event "message"
// carries a notification.
type Message struct {
ID string `json:"id"`
// SequenceID groups the messages that update one notification, which a
// later message of the sequence replaces. ntfy leaves it out when it
// equals ID. A publisher may choose it, so the first message of a
// sequence can have a SequenceID that differs from its ID.
SequenceID string `json:"sequence_id,omitempty"`
// Time is when the message was published, in Unix seconds.
Time int64 `json:"time"`
Expires int64 `json:"expires,omitempty"`
Event string `json:"event"`
Topic string `json:"topic"`
Title string `json:"title,omitempty"`
Message string `json:"message,omitempty"`
// RawPriority is 1-5, or 0 when the message has none.
RawPriority int `json:"priority,omitempty"`
Tags []string `json:"tags,omitempty"`
Click string `json:"click,omitempty"`
Icon string `json:"icon,omitempty"`
Actions []Action `json:"actions,omitempty"`
Attachment *Attachment `json:"attachment,omitempty"`
PollID string `json:"poll_id,omitempty"`
// ContentType is empty for plain text, or text/markdown.
ContentType string `json:"content_type,omitempty"`
// Encoding is empty for UTF-8 text, or base64 for a binary body.
Encoding string `json:"encoding,omitempty"`
}
// Priority returns the message's priority, 1-5. A missing or out-of-range
// priority is the default, 3.
func (m Message) Priority() int {
if m.RawPriority < PriorityMin || m.RawPriority > PriorityMax {
return PriorityDefault
}
return m.RawPriority
}
// Action is a button on a notification. View actions open URL; http
// actions send a request with Method, Headers and Body; broadcast actions
// send an Android intent with Extras; copy actions copy Value to the
// clipboard.
type Action struct {
ID string `json:"id"`
Action string `json:"action"`
Label string `json:"label"`
Clear bool `json:"clear"`
URL string `json:"url,omitempty"`
Method string `json:"method,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
Intent string `json:"intent,omitempty"`
Extras map[string]string `json:"extras,omitempty"`
Value string `json:"value,omitempty"`
}
// Action types.
const (
ActionView = "view"
ActionHTTP = "http"
ActionBroadcast = "broadcast"
ActionCopy = "copy"
)
// Attachment is a file attached to a message.
type Attachment struct {
Name string `json:"name"`
// Type is the file's media type, e.g. image/png. It may be empty.
Type string `json:"type,omitempty"`
// Size is in bytes.
Size int64 `json:"size,omitempty"`
// Expires is when the file is deleted from the server, in Unix
// seconds; 0 for a file hosted elsewhere.
Expires int64 `json:"expires,omitempty"`
URL string `json:"url"`
}
// AttachmentMessage is the message ntfy gives a message published with an
// attachment and no text, with the file's name in place of %s.
const AttachmentMessage = "You received a file: %s"
+49
View File
@@ -0,0 +1,49 @@
package ntfy_test
import (
"encoding/json"
"testing"
"uberbringer/internal/pkg/ntfy"
)
func TestPriority(t *testing.T) {
for raw, want := range map[int]int{0: 3, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 3, -1: 3} {
if got := (ntfy.Message{RawPriority: raw}).Priority(); got != want {
t.Errorf("priority %d: Priority() = %d, want %d", raw, got, want)
}
}
}
// A message as ntfy sends it decodes into every field, and unknown fields
// are ignored.
func TestDecodeMessage(t *testing.T) {
raw := `{"id":"sPs71M8A2Tq9","sequence_id":"seq1","time":1764450245,"expires":1764493445,"event":"message",
"topic":"alerts","title":"Disk almost full","message":"**/var** is at *94%*","priority":4,"tags":["warning","nas01"],
"click":"https://grafana.lan/d/disk","icon":"https://example.com/i.png","content_type":"text/markdown","encoding":"",
"poll_id":"p1","future":true,
"actions":[{"id":"a1","action":"view","label":"Open","url":"https://grafana.lan/d/disk","clear":true},
{"id":"a2","action":"http","label":"Close","url":"https://h/","method":"PUT","headers":{"X":"1"},"body":"b"},
{"id":"a3","action":"broadcast","label":"B","intent":"i","extras":{"k":"v"}},
{"id":"a4","action":"copy","label":"C","value":"123456"}],
"attachment":{"name":"graph.png","type":"image/png","size":33848,"expires":1764461045,"url":"https://ntfy.example.com/f.png"}}`
var m ntfy.Message
if err := json.Unmarshal([]byte(raw), &m); err != nil {
t.Fatal(err)
}
if m.ID != "sPs71M8A2Tq9" || m.SequenceID != "seq1" || m.Time != 1764450245 || m.Expires != 1764493445 ||
m.Event != ntfy.EventMessage || m.Topic != "alerts" || m.Title != "Disk almost full" ||
m.Message != "**/var** is at *94%*" || m.Priority() != ntfy.PriorityHigh || len(m.Tags) != 2 ||
m.Click != "https://grafana.lan/d/disk" || m.Icon == "" || m.ContentType != ntfy.ContentTypeMarkdown || m.PollID != "p1" {
t.Errorf("message %+v", m)
}
if len(m.Actions) != 4 || !m.Actions[0].Clear || m.Actions[1].Method != "PUT" || m.Actions[1].Headers["X"] != "1" ||
m.Actions[1].Body != "b" || m.Actions[2].Intent != "i" || m.Actions[2].Extras["k"] != "v" ||
m.Actions[3].Action != ntfy.ActionCopy || m.Actions[3].Value != "123456" {
t.Errorf("actions %+v", m.Actions)
}
if a := m.Attachment; a == nil || a.Name != "graph.png" || a.Type != "image/png" || a.Size != 33848 ||
a.Expires != 1764461045 || a.URL != "https://ntfy.example.com/f.png" {
t.Errorf("attachment %+v", m.Attachment)
}
}
+30 -12
View File
@@ -65,6 +65,9 @@ type Status struct {
ID JobID `json:"id"`
// State is where the job is in its lifecycle.
State State `json:"status" jsonschema:"enum=queued,enum=printing,enum=done,enum=failed"`
// Source says where the job came from: print for POST /api/v1/print,
// or module:<name> for a module route, e.g. module:ntfy.
Source string `json:"source,omitempty"`
// Error says why a failed job failed.
Error string `json:"error,omitempty"`
// Attempts is how many times the job was sent to the printer.
@@ -105,9 +108,22 @@ type Options struct {
OnFailure func(id JobID, err error)
}
// Meta says where a job came from. It is kept with the job's status and
// logged with it; it never holds what the job prints.
type Meta struct {
// Source is the kind of client that sent the job, e.g. print or
// module:ntfy.
Source string
// Ref identifies the job at its source, e.g. the ID of the request
// that sent it.
Ref string
}
type queuedJob struct {
id JobID
job receipt.Job
id JobID
job receipt.Job
meta Meta
}
// Queue runs print jobs on a single worker. It is safe for concurrent use.
@@ -146,9 +162,10 @@ func New(renderer Renderer, sender Sender, logger *slog.Logger, options Options)
}
}
// Submit queues job. The job should already be validated so callers can
// report problems synchronously; it is validated again when rendered.
func (q *Queue) Submit(job receipt.Job) (Status, error) {
// Submit queues job, sent from where meta says. The job should already be
// validated so callers can report problems synchronously; it is validated
// again when rendered.
func (q *Queue) Submit(job receipt.Job, meta Meta) (Status, error) {
id, err := typeid.New[JobID]()
if err != nil {
return Status{}, fmt.Errorf("generating job ID: %w", err)
@@ -160,11 +177,11 @@ func (q *Queue) Submit(job receipt.Job) (Status, error) {
return Status{}, ErrClosed
}
select {
case q.jobs <- queuedJob{id: id, job: job}:
case q.jobs <- queuedJob{id: id, job: job, meta: meta}:
default:
return Status{}, ErrQueueFull
}
status := &Status{ID: id, State: StateQueued, CreatedAt: time.Now().UTC()}
status := &Status{ID: id, State: StateQueued, Source: meta.Source, CreatedAt: time.Now().UTC()}
q.statuses[id] = status
return *status, nil
}
@@ -216,10 +233,10 @@ func (q *Queue) process(ctx context.Context, qj queuedJob) {
now := time.Now().UTC()
s.State, s.StartedAt = StatePrinting, &now
})
logger := q.logger.With("job_id", qj.id.String())
logger := q.logger.With("job_id", qj.id.String(), "source", qj.meta.Source, "ref", qj.meta.Ref)
logger.Info("printing job", "elements", len(qj.job.Elements), "copies", max(qj.job.Copies, 1))
attempts, err := q.print(ctx, jobCtx, qj.job)
attempts, err := q.print(ctx, jobCtx, qj.job, logger)
q.finish(qj.id, attempts, err)
if err != nil {
logger.Error("job failed", "attempts", attempts, "err", err)
@@ -232,8 +249,9 @@ func (q *Queue) process(ctx context.Context, qj queuedJob) {
}
// print renders job once and sends it, retrying failed sends with backoff.
// Retries stop early when runCtx is cancelled.
func (q *Queue) print(runCtx, jobCtx context.Context, job receipt.Job) (int, error) {
// Retries stop early when runCtx is cancelled. logger carries the job's
// fields.
func (q *Queue) print(runCtx, jobCtx context.Context, job receipt.Job, logger *slog.Logger) (int, error) {
data, err := q.renderer.Render(jobCtx, job)
if err != nil {
return 0, fmt.Errorf("rendering: %w", err)
@@ -247,7 +265,7 @@ func (q *Queue) print(runCtx, jobCtx context.Context, job receipt.Job) (int, err
if attempt > q.options.Retries {
return attempt, err
}
q.logger.Warn("send failed, retrying", "attempt", attempt, "retry_in", delay, "err", err)
logger.Warn("send failed, retrying", "attempt", attempt, "retry_in", delay, "err", err)
select {
case <-time.After(delay):
case <-runCtx.Done():
+63 -11
View File
@@ -114,7 +114,7 @@ func TestSubmitAndPrintInOrder(t *testing.T) {
var last printqueue.Status
for _, text := range []string{"one", "two", "three"} {
st, err := q.Submit(job(text))
st, err := q.Submit(job(text), printqueue.Meta{})
if err != nil {
t.Fatal(err)
}
@@ -132,11 +132,63 @@ func TestSubmitAndPrintInOrder(t *testing.T) {
}
}
// lockedBuffer is a log destination safe for the worker and the test.
type lockedBuffer struct {
mu sync.Mutex
buf strings.Builder
}
func (b *lockedBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *lockedBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
func TestMetaInStatusAndLogs(t *testing.T) {
var logs lockedBuffer
// One failed send, so that the retry is logged too.
q := printqueue.New(fakeRenderer{}, &fakeSender{failures: 1}, slog.New(slog.NewTextHandler(&logs, nil)),
printqueue.Options{Size: 1, History: 1, Retries: 1, RetryDelay: time.Millisecond})
startQueue(t, q)
st, err := q.Submit(job("private text"), printqueue.Meta{Source: "module:ntfy", Ref: "req_01kbx4n6m3ex8tq0wq3r5vrzq1"})
if err != nil {
t.Fatal(err)
}
if st.Source != "module:ntfy" {
t.Errorf("submit status source = %q", st.Source)
}
done := waitForState(t, q, st.ID, printqueue.StateDone)
if done.Source != "module:ntfy" {
t.Errorf("done status source = %q", done.Source)
}
lines := strings.Split(strings.TrimSpace(logs.String()), "\n")
if len(lines) != 3 || !strings.Contains(lines[1], "send failed, retrying") {
t.Fatalf("want the printing, retry and printed lines, got:\n%s", logs.String())
}
for _, line := range lines {
for _, want := range []string{"source=module:ntfy", "ref=req_01kbx4n6m3ex8tq0wq3r5vrzq1", "job_id=" + st.ID.String()} {
if !strings.Contains(line, want) {
t.Errorf("log line lacks %s: %s", want, line)
}
}
}
if strings.Contains(logs.String(), "private text") {
t.Error("the job's text reached the logs")
}
}
func TestRetriesThenSucceeds(t *testing.T) {
sender := &fakeSender{failures: 2}
q := newQueue(fakeRenderer{}, sender, printqueue.Options{Retries: 3})
startQueue(t, q)
st, _ := q.Submit(job("x"))
st, _ := q.Submit(job("x"), printqueue.Meta{})
done := waitForState(t, q, st.ID, printqueue.StateDone)
if done.Attempts != 3 {
t.Errorf("attempts = %d, want 3", done.Attempts)
@@ -151,7 +203,7 @@ func TestFailsAfterRetries(t *testing.T) {
OnFailure: func(id printqueue.JobID, _ error) { reported <- id },
})
cancel, wait := startQueue(t, q)
st, _ := q.Submit(job("x"))
st, _ := q.Submit(job("x"), printqueue.Meta{})
failed := waitForState(t, q, st.ID, printqueue.StateFailed)
if failed.Attempts != 3 || !strings.Contains(failed.Error, "printer offline") {
t.Errorf("failed status = %+v", failed)
@@ -176,7 +228,7 @@ func TestRenderFailureIsNotRetried(t *testing.T) {
sender := &fakeSender{}
q := newQueue(fakeRenderer{err: errors.New("image blocked")}, sender, printqueue.Options{Retries: 3})
startQueue(t, q)
st, _ := q.Submit(job("x"))
st, _ := q.Submit(job("x"), printqueue.Meta{})
failed := waitForState(t, q, st.ID, printqueue.StateFailed)
if !strings.Contains(failed.Error, "image blocked") || len(sender.Sent()) != 0 {
t.Errorf("failed status = %+v, sent %v", failed, sender.Sent())
@@ -187,11 +239,11 @@ func TestQueueFull(t *testing.T) {
q := newQueue(fakeRenderer{}, &fakeSender{}, printqueue.Options{Size: 2})
// Not running, so nothing drains the queue.
for range 2 {
if _, err := q.Submit(job("x")); err != nil {
if _, err := q.Submit(job("x"), printqueue.Meta{}); err != nil {
t.Fatal(err)
}
}
if _, err := q.Submit(job("x")); !errors.Is(err, printqueue.ErrQueueFull) {
if _, err := q.Submit(job("x"), printqueue.Meta{}); !errors.Is(err, printqueue.ErrQueueFull) {
t.Errorf("err = %v, want ErrQueueFull", err)
}
if q.Pending() != 2 {
@@ -204,9 +256,9 @@ func TestShutdownFinishesCurrentJobAndFailsWaiting(t *testing.T) {
q := newQueue(fakeRenderer{}, sender, printqueue.Options{})
cancel, wait := startQueue(t, q)
first, _ := q.Submit(job("first"))
first, _ := q.Submit(job("first"), printqueue.Meta{})
waitForState(t, q, first.ID, printqueue.StatePrinting)
second, _ := q.Submit(job("second"))
second, _ := q.Submit(job("second"), printqueue.Meta{})
// Cancel while the first send is still blocked, so Run is shutting down
// by the time that send completes.
@@ -220,7 +272,7 @@ func TestShutdownFinishesCurrentJobAndFailsWaiting(t *testing.T) {
if st, _ := q.Status(second.ID); st.State != printqueue.StateFailed || !strings.Contains(st.Error, "shutting down") {
t.Errorf("waiting job = %+v, want failed with shutting down", st)
}
if _, err := q.Submit(job("late")); !errors.Is(err, printqueue.ErrClosed) {
if _, err := q.Submit(job("late"), printqueue.Meta{}); !errors.Is(err, printqueue.ErrClosed) {
t.Errorf("submit after shutdown err = %v, want ErrClosed", err)
}
}
@@ -231,7 +283,7 @@ func TestHistoryEviction(t *testing.T) {
startQueue(t, q)
var ids []printqueue.JobID
for range 3 {
st, _ := q.Submit(job("x"))
st, _ := q.Submit(job("x"), printqueue.Meta{})
ids = append(ids, st.ID)
waitForState(t, q, st.ID, printqueue.StateDone)
}
@@ -245,7 +297,7 @@ func TestHistoryEviction(t *testing.T) {
func TestParseJobID(t *testing.T) {
q := newQueue(fakeRenderer{}, &fakeSender{}, printqueue.Options{})
st, _ := q.Submit(job("x"))
st, _ := q.Submit(job("x"), printqueue.Meta{})
parsed, err := printqueue.ParseJobID(st.ID.String())
if err != nil || parsed != st.ID {
t.Errorf("ParseJobID(%s) = %v, %v", st.ID, parsed, err)
+15 -4
View File
@@ -68,11 +68,13 @@ var fields = []field{
{"hri", func(e Element) bool { return e.HRI != "" }},
{"url", func(e Element) bool { return e.URL != "" }},
{"base64", func(e Element) bool { return e.Base64 != "" }},
{"optional", func(e Element) bool { return e.Optional }},
{"hex", func(e Element) bool { return e.Hex != "" }},
{"mode", func(e Element) bool { return e.Mode != "" }},
{"children", func(e Element) bool { return e.Children != nil }},
{"title", func(e Element) bool { return e.Title != "" }},
{"title_style", func(e Element) bool { return e.TitleStyle != "" }},
{"title_bold", func(e Element) bool { return e.TitleBold }},
{"footer", func(e Element) bool { return e.Footer != "" }},
{"style", func(e Element) bool { return e.Style != "" }},
{"padding", func(e Element) bool { return e.Padding != nil }},
@@ -86,11 +88,16 @@ var fields = []field{
}
// blockOnly are the fields no other type takes.
var blockOnly = fieldSet("children title title_style footer style padding fit columns pairs leader items bullet done")
var blockOnly = fieldSet("children title title_style title_bold footer style padding fit columns pairs leader items bullet done")
// ownFields maps each field that only one of the other types takes to that
// type. The rest of the other types refuse it, as they refuse the block
// fields.
var ownFields = map[string]string{"optional": TypeImage}
// blockFields are the fields each block takes at the top level.
var blockFields = map[string]map[string]bool{
TypeBox: fieldSet("text bold underline invert align size font children title title_style footer style padding fit columns"),
TypeBox: fieldSet("text bold underline invert align size font children title title_style title_bold footer style padding fit columns"),
TypeRule: fieldSet("text bold align size font style columns"),
TypeKV: fieldSet("pairs leader size font columns"),
TypeList: fieldSet("items bullet done size font columns"),
@@ -118,7 +125,8 @@ func fieldSet(names string) map[string]bool {
// checkFields reports fields set on el that its type does not take. The
// blocks and the children of a box take only their own fields; the other
// types ignore unrelated fields, except the block fields.
// types ignore unrelated fields, except the block fields and the fields
// another type owns.
func (el Element) checkFields(inBox bool) []string {
allowed, strict := blockFields[el.Type]
if inBox {
@@ -138,7 +146,8 @@ func (el Element) checkFields(inBox bool) []string {
problems = append(problems, fmt.Sprintf("%s is inherited from the box", f.name))
case inBox && !allowed[f.name]:
problems = append(problems, fmt.Sprintf("field %q does not apply to %s inside a box", f.name, el.Type))
case strict && !allowed[f.name], !strict && blockOnly[f.name]:
case strict && !allowed[f.name], !strict && blockOnly[f.name],
!strict && ownFields[f.name] != "" && ownFields[f.name] != el.Type:
problems = append(problems, fmt.Sprintf("field %q does not apply to %s", f.name, el.Type))
}
}
@@ -166,6 +175,7 @@ func checkColumns(columns int) error {
type boxSpec struct {
style boxStyle
capped bool
title textStyle
text textStyle
align escpos.Justification
padding int
@@ -177,6 +187,7 @@ type boxSpec struct {
func (el Element) boxSpec() (boxSpec, error) {
s := boxSpec{
title: textStyle{bold: el.TitleBold},
text: textStyle{bold: el.Bold, invert: el.Invert},
padding: defaultPadding,
fit: el.Fit,
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more