From 1335ed0687f38c1a85fd1327317b3b19226b0ceb Mon Sep 17 00:00:00 2001 From: William Gill Date: Mon, 30 Nov 2026 12:37:36 -0600 Subject: [PATCH] Add the notify and ntfy modules and scoped tokens 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 --- CHANGELOG.md | 51 ++ CLAUDE.md | 2 +- README.md | 51 +- configs/config.example.toml | 18 + docs/api.md | 373 +++++++- docs/design.md | 103 ++- docs/plans/formatters.md | 348 +------- docs/swagger.json | 70 +- internal/app/uberbringer/cli.go | 93 +- internal/app/uberbringer/cli_test.go | 60 +- internal/app/uberbringer/modules.go | 20 +- internal/app/uberbringer/preview.go | 19 +- internal/app/uberbringer/preview_test.go | 71 +- internal/app/uberbringer/serve_test.go | 2 +- internal/app/uberbringer/server/auth.go | 129 ++- internal/app/uberbringer/server/auth_test.go | 250 ++++++ internal/app/uberbringer/server/errors.go | 1 + internal/app/uberbringer/server/handlers.go | 19 +- .../uberbringer/server/handlers_modules.go | 27 +- .../server/handlers_modules_test.go | 45 +- internal/app/uberbringer/server/routes.go | 33 +- internal/app/uberbringer/server/server.go | 2 +- .../app/uberbringer/server/server_test.go | 12 +- internal/pkg/config/config.go | 136 ++- internal/pkg/config/config_test.go | 134 ++- internal/pkg/config/value.go | 11 +- internal/pkg/escpos/escpos_test.go | 29 + internal/pkg/escpos/qrcode.go | 34 + internal/pkg/modules/card.go | 412 +++++++++ internal/pkg/modules/card_test.go | 803 ++++++++++++++++++ internal/pkg/modules/export_test.go | 12 + internal/pkg/modules/fallback.go | 23 + internal/pkg/modules/markdown.go | 263 ++++++ internal/pkg/modules/markdown_test.go | 197 +++++ internal/pkg/modules/markers.go | 112 +++ internal/pkg/modules/note_test.go | 6 +- internal/pkg/modules/notice.go | 171 ++++ internal/pkg/modules/notify.go | 230 +++++ internal/pkg/modules/ntfy.go | 124 +++ internal/pkg/modules/registry.go | 23 +- .../pkg/modules/testdata/card/p1-auto.txt | 9 + internal/pkg/modules/testdata/card/p1-box.txt | 9 + .../pkg/modules/testdata/card/p1-compact.txt | 9 + .../pkg/modules/testdata/card/p2-auto.txt | 9 + internal/pkg/modules/testdata/card/p2-box.txt | 9 + .../pkg/modules/testdata/card/p2-compact.txt | 9 + .../pkg/modules/testdata/card/p3-auto.txt | 9 + internal/pkg/modules/testdata/card/p3-box.txt | 9 + .../pkg/modules/testdata/card/p3-compact.txt | 9 + .../pkg/modules/testdata/card/p4-auto.txt | 11 + internal/pkg/modules/testdata/card/p4-box.txt | 11 + .../pkg/modules/testdata/card/p4-compact.txt | 9 + .../pkg/modules/testdata/card/p5-auto.txt | 13 + internal/pkg/modules/testdata/card/p5-box.txt | 13 + .../pkg/modules/testdata/card/p5-compact.txt | 9 + .../pkg/modules/testdata/markdown/subset.md | 22 + .../pkg/modules/testdata/markdown/subset.txt | 29 + .../pkg/modules/testdata/notify/full.json | 4 + internal/pkg/modules/testdata/notify/full.txt | 16 + .../pkg/modules/testdata/notify/long.json | 1 + internal/pkg/modules/testdata/notify/long.txt | 44 + .../pkg/modules/testdata/notify/markdown.json | 1 + .../pkg/modules/testdata/notify/markdown.txt | 11 + .../pkg/modules/testdata/notify/minimal.json | 1 + .../pkg/modules/testdata/notify/minimal.txt | 4 + .../testdata/ntfy/actions-private.json | 6 + .../modules/testdata/ntfy/actions-private.txt | 10 + .../testdata/ntfy/attachment-expired.json | 2 + .../testdata/ntfy/attachment-expired.txt | 6 + .../testdata/ntfy/attachment-file.json | 3 + .../modules/testdata/ntfy/attachment-file.txt | 4 + .../testdata/ntfy/attachment-untyped.json | 2 + .../testdata/ntfy/attachment-untyped.txt | 6 + internal/pkg/modules/testdata/ntfy/emoji.json | 1 + internal/pkg/modules/testdata/ntfy/emoji.txt | 7 + .../pkg/modules/testdata/ntfy/markdown.json | 2 + .../pkg/modules/testdata/ntfy/markdown.txt | 27 + .../pkg/modules/testdata/ntfy/no-title.json | 1 + .../pkg/modules/testdata/ntfy/no-title.txt | 4 + .../testdata/ntfy/priority-default.json | 2 + .../testdata/ntfy/priority-default.txt | 7 + .../modules/testdata/ntfy/priority-high.json | 5 + .../modules/testdata/ntfy/priority-high.txt | 13 + .../modules/testdata/ntfy/priority-min.json | 2 + .../modules/testdata/ntfy/priority-min.txt | 4 + .../testdata/ntfy/priority-urgent.json | 2 + .../modules/testdata/ntfy/priority-urgent.txt | 10 + .../pkg/modules/testdata/ntfy/sequence.json | 1 + .../pkg/modules/testdata/ntfy/sequence.txt | 6 + .../modules/testdata/ntfy/unknown-fields.json | 1 + .../modules/testdata/ntfy/unknown-fields.txt | 4 + .../modules/testdata/paper/ntfy-default.json | 1 + .../pkg/modules/testdata/paper/ntfy-high.json | 1 + .../pkg/modules/testdata/paper/ntfy-min.json | 1 + .../modules/testdata/paper/ntfy-urgent.json | 1 + internal/pkg/ntfy/message.go | 121 +++ internal/pkg/ntfy/message_test.go | 49 ++ internal/pkg/printqueue/queue.go | 42 +- internal/pkg/printqueue/queue_test.go | 74 +- internal/pkg/receipt/block.go | 19 +- internal/pkg/receipt/blocklayout.go | 8 +- internal/pkg/receipt/blocks_test.go | 32 +- internal/pkg/receipt/compat_test.go | 29 +- internal/pkg/receipt/job.go | 10 +- internal/pkg/receipt/normalize.go | 55 ++ internal/pkg/receipt/normalize_test.go | 30 + internal/pkg/receipt/preview.go | 19 +- internal/pkg/receipt/receipt_test.go | 113 +++ internal/pkg/receipt/render.go | 34 +- internal/pkg/receipt/testdata/paper/graph.png | Bin 0 -> 884 bytes .../receipt/testdata/paper/ntfy-default.hex | 10 + .../receipt/testdata/paper/ntfy-default.json | 23 + .../pkg/receipt/testdata/paper/ntfy-high.hex | 336 ++++++++ .../pkg/receipt/testdata/paper/ntfy-high.json | 58 ++ .../pkg/receipt/testdata/paper/ntfy-min.hex | 7 + .../pkg/receipt/testdata/paper/ntfy-min.json | 18 + .../receipt/testdata/paper/ntfy-urgent.hex | 17 + .../receipt/testdata/paper/ntfy-urgent.json | 35 + internal/pkg/receipt/validate_test.go | 14 +- 119 files changed, 5626 insertions(+), 468 deletions(-) create mode 100644 internal/app/uberbringer/server/auth_test.go create mode 100644 internal/pkg/modules/card.go create mode 100644 internal/pkg/modules/card_test.go create mode 100644 internal/pkg/modules/export_test.go create mode 100644 internal/pkg/modules/fallback.go create mode 100644 internal/pkg/modules/markdown.go create mode 100644 internal/pkg/modules/markdown_test.go create mode 100644 internal/pkg/modules/markers.go create mode 100644 internal/pkg/modules/notice.go create mode 100644 internal/pkg/modules/notify.go create mode 100644 internal/pkg/modules/ntfy.go create mode 100644 internal/pkg/modules/testdata/card/p1-auto.txt create mode 100644 internal/pkg/modules/testdata/card/p1-box.txt create mode 100644 internal/pkg/modules/testdata/card/p1-compact.txt create mode 100644 internal/pkg/modules/testdata/card/p2-auto.txt create mode 100644 internal/pkg/modules/testdata/card/p2-box.txt create mode 100644 internal/pkg/modules/testdata/card/p2-compact.txt create mode 100644 internal/pkg/modules/testdata/card/p3-auto.txt create mode 100644 internal/pkg/modules/testdata/card/p3-box.txt create mode 100644 internal/pkg/modules/testdata/card/p3-compact.txt create mode 100644 internal/pkg/modules/testdata/card/p4-auto.txt create mode 100644 internal/pkg/modules/testdata/card/p4-box.txt create mode 100644 internal/pkg/modules/testdata/card/p4-compact.txt create mode 100644 internal/pkg/modules/testdata/card/p5-auto.txt create mode 100644 internal/pkg/modules/testdata/card/p5-box.txt create mode 100644 internal/pkg/modules/testdata/card/p5-compact.txt create mode 100644 internal/pkg/modules/testdata/markdown/subset.md create mode 100644 internal/pkg/modules/testdata/markdown/subset.txt create mode 100644 internal/pkg/modules/testdata/notify/full.json create mode 100644 internal/pkg/modules/testdata/notify/full.txt create mode 100644 internal/pkg/modules/testdata/notify/long.json create mode 100644 internal/pkg/modules/testdata/notify/long.txt create mode 100644 internal/pkg/modules/testdata/notify/markdown.json create mode 100644 internal/pkg/modules/testdata/notify/markdown.txt create mode 100644 internal/pkg/modules/testdata/notify/minimal.json create mode 100644 internal/pkg/modules/testdata/notify/minimal.txt create mode 100644 internal/pkg/modules/testdata/ntfy/actions-private.json create mode 100644 internal/pkg/modules/testdata/ntfy/actions-private.txt create mode 100644 internal/pkg/modules/testdata/ntfy/attachment-expired.json create mode 100644 internal/pkg/modules/testdata/ntfy/attachment-expired.txt create mode 100644 internal/pkg/modules/testdata/ntfy/attachment-file.json create mode 100644 internal/pkg/modules/testdata/ntfy/attachment-file.txt create mode 100644 internal/pkg/modules/testdata/ntfy/attachment-untyped.json create mode 100644 internal/pkg/modules/testdata/ntfy/attachment-untyped.txt create mode 100644 internal/pkg/modules/testdata/ntfy/emoji.json create mode 100644 internal/pkg/modules/testdata/ntfy/emoji.txt create mode 100644 internal/pkg/modules/testdata/ntfy/markdown.json create mode 100644 internal/pkg/modules/testdata/ntfy/markdown.txt create mode 100644 internal/pkg/modules/testdata/ntfy/no-title.json create mode 100644 internal/pkg/modules/testdata/ntfy/no-title.txt create mode 100644 internal/pkg/modules/testdata/ntfy/priority-default.json create mode 100644 internal/pkg/modules/testdata/ntfy/priority-default.txt create mode 100644 internal/pkg/modules/testdata/ntfy/priority-high.json create mode 100644 internal/pkg/modules/testdata/ntfy/priority-high.txt create mode 100644 internal/pkg/modules/testdata/ntfy/priority-min.json create mode 100644 internal/pkg/modules/testdata/ntfy/priority-min.txt create mode 100644 internal/pkg/modules/testdata/ntfy/priority-urgent.json create mode 100644 internal/pkg/modules/testdata/ntfy/priority-urgent.txt create mode 100644 internal/pkg/modules/testdata/ntfy/sequence.json create mode 100644 internal/pkg/modules/testdata/ntfy/sequence.txt create mode 100644 internal/pkg/modules/testdata/ntfy/unknown-fields.json create mode 100644 internal/pkg/modules/testdata/ntfy/unknown-fields.txt create mode 100644 internal/pkg/modules/testdata/paper/ntfy-default.json create mode 100644 internal/pkg/modules/testdata/paper/ntfy-high.json create mode 100644 internal/pkg/modules/testdata/paper/ntfy-min.json create mode 100644 internal/pkg/modules/testdata/paper/ntfy-urgent.json create mode 100644 internal/pkg/ntfy/message.go create mode 100644 internal/pkg/ntfy/message_test.go create mode 100644 internal/pkg/receipt/testdata/paper/graph.png create mode 100644 internal/pkg/receipt/testdata/paper/ntfy-default.hex create mode 100644 internal/pkg/receipt/testdata/paper/ntfy-default.json create mode 100644 internal/pkg/receipt/testdata/paper/ntfy-high.hex create mode 100644 internal/pkg/receipt/testdata/paper/ntfy-high.json create mode 100644 internal/pkg/receipt/testdata/paper/ntfy-min.hex create mode 100644 internal/pkg/receipt/testdata/paper/ntfy-min.json create mode 100644 internal/pkg/receipt/testdata/paper/ntfy-urgent.hex create mode 100644 internal/pkg/receipt/testdata/paper/ntfy-urgent.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d247fe..d12d49d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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:`. 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, diff --git a/CLAUDE.md b/CLAUDE.md index 3481339..ca0c609 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 diff --git a/README.md b/README.md index dc2307b..8d78521 100644 --- a/README.md +++ b/README.md @@ -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:`) 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 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 diff --git a/configs/config.example.toml b/configs/config.example.toml index 2ac6e57..64fafd6 100644 --- a/configs/config.example.toml +++ b/configs/config.example.toml @@ -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 diff --git a/docs/api.md b/docs/api.md index 92bcefa..7ca75f1 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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:` 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: `, 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)`. diff --git a/docs/design.md b/docs/design.md index 12b00a9..a752f26 100644 --- a/docs/design.md +++ b/docs/design.md @@ -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:`, later `ntfy:`) 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 diff --git a/docs/plans/formatters.md b/docs/plans/formatters.md index 4d85f22..4bfadd1 100644 --- a/docs/plans/formatters.md +++ b/docs/plans/formatters.md @@ -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=