diff --git a/CHANGELOG.md b/CHANGELOG.md index d12d49d..52fcde3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,13 @@ version may break callers; such changes are listed under **Breaking**. 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. +- Every receipt feeds `printer.cut_feed` blank lines (default 3) before + each cut, so that its last line no longer sits right at the cut. + Previews show them before the cut, and they count toward + `format.max_lines`: 3 lines for each cut in each copy, the final cut and + every `cut` element. So a job close to the limit can now fail: 400 lines + in 5 copies was 2000 and is now 2015, and with one `cut` element inside + each copy, 2030. Set `cut_feed = 0` for the old spacing and count. ### Added @@ -43,9 +50,36 @@ version may break callers; such changes are listed under **Breaking**. 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. +- ntfy subscriptions: `[[ntfy.subscriptions]]` tables in the config make + the daemon subscribe to ntfy topics itself and print each message as a + notification card, so no other client is needed. + - After a restart or an outage, the messages missed print once each, up + to `max_backlog` (default 1 hour) back; repeats never print twice. + - A paper budget, `rate_limit` receipts per `rate_window` (default 5 in + 10 minutes), holds the rest of a flood and prints it on one digest + receipt once there is room. By default, priority 5 always prints at + once. + - Optional quiet hours (`[ntfy.subscriptions.quiet]`) print only urgent + messages during a daily window and the rest on one `Overnight` digest + when it ends. + - A message that replaces one the subscription printed is marked + `(updated)`, or left out with `ntfy.format.updates = "skip"`. + - `ntfy.state_dir` keeps each subscription's state across restarts. + `install.sh` writes it into a new config and the systemd unit gains + `StateDirectory=uberbringer`, so `/var/lib/uberbringer` is writable; + the Docker image sets it to that path, for a volume, and runs as user + and group `10001`, so a mounted token file can be given to it. + - A redirect from the server is never followed, so credentials never + go to another address or over plain http; the connection fails, and + its error says that the server redirects and to set `server` to the + address it redirects to. +- `GET /healthz` lists the ntfy subscriptions in an `ntfy` array, with + their state, counts and last error. Its status code still depends on the + printer alone. +- `GET /api/v1/jobs/:id` reports the job's `source`: `print`, + `module:`, or `ntfy:`. The worker's log lines carry + the source and the ID of the request, or of the ntfy message, 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. diff --git a/Dockerfile b/Dockerfile index fd81851..b4f729c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -16,16 +16,25 @@ RUN CGO_ENABLED=0 go build -trimpath \ FROM alpine:3.24 # ca-certificates for fetching https images, tzdata for local log times. +# The user and group have the fixed ID 10001, so that files mounted from the +# host, such as an ntfy token file, can be given to it. /var/lib/uberbringer +# holds the state of the ntfy subscriptions; a named volume mounted there +# takes over its owner, so the daemon can write to it. RUN apk add --no-cache ca-certificates tzdata \ - && addgroup -S uberbringer \ - && adduser -S -D -H -G uberbringer -h /etc/uberbringer uberbringer + && addgroup -S -g 10001 uberbringer \ + && adduser -S -D -H -u 10001 -G uberbringer -h /etc/uberbringer uberbringer \ + && mkdir -p /var/lib/uberbringer \ + && chown uberbringer:uberbringer /var/lib/uberbringer \ + && chmod 0700 /var/lib/uberbringer COPY --from=build /out/uberbringer /usr/local/bin/uberbringer USER uberbringer WORKDIR /etc/uberbringer # Plain HTTP for a reverse proxy in front, which terminates TLS. Mount # config.toml at /etc/uberbringer/config.toml, or set UBERBRINGER_CONFIG to "" # and give the settings as UBERBRINGER_* variables. Either way, bind_ip must be -# 0.0.0.0 and trusted_proxies must hold the proxy's address. -ENV UBERBRINGER_CONFIG=/etc/uberbringer/config.toml +# 0.0.0.0 and trusted_proxies must hold the proxy's address. Mount a volume on +# /var/lib/uberbringer to keep the subscriptions' state across containers. +ENV UBERBRINGER_CONFIG=/etc/uberbringer/config.toml \ + UBERBRINGER_NTFY_STATE_DIR=/var/lib/uberbringer EXPOSE 8080 ENTRYPOINT ["/usr/local/bin/uberbringer"] diff --git a/README.md b/README.md index 8d78521..38a57df 100644 --- a/README.md +++ b/README.md @@ -18,10 +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. +- **Notifications**: subscribe to [ntfy](https://ntfy.sh) topics from the + config and print their messages as they arrive, with no other client, + a paper budget that folds floods into one digest, and quiet hours; or + print them through the ntfy client, 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. @@ -43,6 +45,7 @@ REST API and prints them on an EPSON ESC/POS network receipt printer. - [Quick start](#quick-start) - [API](#api), in [docs/api.md](docs/api.md) - [Configuration](#configuration) +- [ntfy subscriptions](#ntfy-subscriptions) - [Command line](#command-line) - [Development](#development) - [License](#license) @@ -70,6 +73,10 @@ sudo ./install.sh printer.example.com you@example.com 192.168.1.245 - Re-running the script upgrades the install and keeps the config. After editing the config, run `systemctl restart uberbringer`; after changing `webserver.body_limit`, `bind_ip` or `port`, re-run the script instead. +- The service keeps [ntfy subscriptions](#ntfy-subscriptions)' state in + `/var/lib/uberbringer`, the only directory it may write to. A config the + script creates sets `ntfy.state_dir` to it; add that line to an older + config before adding a subscription. - Change the systemd unit with `systemctl edit uberbringer`. - The install log is `/var/log/uberbringer-install.log`. @@ -119,6 +126,26 @@ container health checks, use `GET /` to see whether the daemon is up. `/healthz` answers `503` while the printer is unreachable, so it suits alerting better than restarting the container. +[ntfy subscriptions](#ntfy-subscriptions) keep their state in +`/var/lib/uberbringer`, which the image sets as `ntfy.state_dir`. Mount a +volume there: without one the state lives in the container, and a new +container, after a pull or an upgrade, forgets what was printed and what +was held. + +```sh +docker run -d -p 127.0.0.1:8080:8080 -v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" \ + -v uberbringer-state:/var/lib/uberbringer uberbringer +``` + +Subscriptions are set in `config.toml` only, so a container with one needs +the file. The image runs as user and group `10001`, so give a token file +to that ID, mode `600`, and mount it read-only next to the config: + +```sh +sudo chown 10001:10001 ntfy.token && sudo chmod 600 ntfy.token +docker run ... -v "$PWD/ntfy.token:/etc/uberbringer/ntfy.token:ro" uberbringer +``` + ### From source ```sh @@ -148,7 +175,8 @@ case. A duration is a string such as `"5s"`; a bare number is refused. Every key can also be set by an environment variable named `UBERBRINGER_
_`, such as `UBERBRINGER_PRINTER_ADDRESS` for -`printer.address`, and a variable wins over the file: +`printer.address`, and a variable wins over the file. The exception is +`[[ntfy.subscriptions]]`, a list of tables, which only the file sets. - Values are written without quotes: decimal digits for a number, `true` or `false` for a flag, `5s` for a duration. Lists take comma-separated values, @@ -190,6 +218,10 @@ Settings worth knowing: small gaps in the vertical borders at the printer's default spacing; a value checked on paper closes them. `0` keeps the default, which was checked on a TM-T88IV with `examples/blocks.json` and looks fine. +- `printer.cut_feed` (default `3`): blank lines, 0–255, fed before every + cut, the one after each copy and `cut` elements alike, so that the last + printed line does not sit right at the cut. They show as blank lines + before the cut in previews and count toward `format.max_lines`. - `format.max_lines` (default `2000`): a job that would print more lines, all copies counted, fails instead of printing. It is a backstop against runaway text; `/api/v1/preview` answers such a job with `422`. @@ -202,7 +234,9 @@ Settings worth knowing: 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: + of the `notify` and `ntfy` modules and of the + [ntfy subscriptions](#ntfy-subscriptions), and their + [digests](docs/api.md#digests): | Key | Default | Values | |-----|---------|--------| @@ -211,9 +245,16 @@ Settings worth knowing: | `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 | + | `updates` | `print` | What a [subscription](#ntfy-subscriptions) does with a message that replaces one it printed: `print` marks its title `(updated)`, `skip` leaves it out | - `[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 = ""`. +- `ntfy.state_dir` (no default): the directory the + [ntfy subscriptions](#ntfy-subscriptions) keep their state in, one + `ntfy-.json` file each, readable by the daemon's user only. + Required with a subscription. `install.sh` and the Docker image set it to + `/var/lib/uberbringer`. +- `[[ntfy.subscriptions]]`: see [ntfy subscriptions](#ntfy-subscriptions). - `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`. @@ -243,10 +284,205 @@ Settings worth knowing: 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. + - Each [ntfy subscription](#ntfy-subscriptions) logs with its + `subscription` name, and with the message's `ntfy_id` where there is + one, never with what a message says or its topic: `ntfy connected` at + INFO; `ntfy connection lost` and `ntfy credentials refused` at WARN, + with the cause in `err` and the wait in `retry_in`; `ntfy receipt + queued` at INFO, with the `ref` (the message's ID, or `digest`) and the + `job_id`; `ntfy message waits to print` at WARN while the queue is + full. A card or digest that falls back to a plain receipt is logged at + ERROR as `ntfy card printed its fallback receipt` and reported to + Sentry once, and so is a state file that cannot be written + (`ntfy state not saved`). At DEBUG, each message's fate: held, + dropped in quiet hours, repeated or skipped. - 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`. +## ntfy subscriptions + +The daemon can subscribe to [ntfy](https://ntfy.sh) topics itself and print +each message as a [notification card](docs/api.md#notification-cards), so +the phone's ntfy app, or anything else that publishes, is the only client. +Each `[[ntfy.subscriptions]]` table in `config.toml` is one connection to +one server, for one or more topics: + +```toml +[ntfy] + state_dir = "/var/lib/uberbringer" + +[[ntfy.subscriptions]] + name = "home" + server = "https://ntfy.example.com" + topics = ["alerts", "backups"] + token_file = "/etc/uberbringer/ntfy.token" + +[ntfy.subscriptions.quiet] + start = "22:00" + end = "07:00" +``` + +| Key | Default | Meaning | +|-----|---------|---------| +| `name` | required | 1–32 lowercase letters, digits, `-` and `_`. It names the subscription in `/healthz`, in logs, in its state file and in its jobs' source, `ntfy:`; each must be unique | +| `server` | required | The server's base URL. It must be `https` unless `allow_insecure = true`. A redirect is never followed: the connection fails, and `last_error` says to set the address it points to | +| `allow_insecure` | `false` | `true` allows a plain `http` server, whose credentials and messages cross the network unencrypted | +| `topics` | required | 1–150 topic names, each 1–64 letters, digits, `-` and `_` | +| `token`, `token_file`, or `user` with `password_file` | none | The credentials, at most one kind. A file holds the secret alone; spaces and line breaks around it are ignored, and a file the group or others can read is accepted with a warning. Without any, the subscription reads as anyone may | +| `min_priority` | `1` | The lowest priority that prints; the server filters by it | +| `max_backlog` | `"1h"` | How far back messages missed during a restart or an outage still print, at most `12h`, the time ntfy keeps them by default | +| `rate_limit`, `rate_window` | `5`, `"10m"` | The paper budget: at most this many receipts in any window. Messages over it are held, and print together on one [digest](docs/api.md#digests) once the budget has room | +| `bypass_priority` | `5` | Outside quiet hours, messages of this priority and above print at once, outside the budget. During quiet hours, `quiet.min_priority` decides first | +| `keepalive` | `"45s"` | The server's keepalive interval, 5s–1h. A connection silent for twice this plus 15 s is opened again | + +Quiet hours are off unless the subscription has a +`[ntfy.subscriptions.quiet]` table, which goes right after its +`[[ntfy.subscriptions]]` table: + +| Key | Default | Meaning | +|-----|---------|---------| +| `start`, `end` | `"22:00"`, `"07:00"` | The window, as HH:MM. An end before the start is on the next day; the times hold on the nights the clocks change | +| `days` | every day | The days a window starts on: `mon`, `tue`, `wed`, `thu`, `fri`, `sat`, `sun`. With `["fri"]`, Friday's window runs into Saturday morning | +| `timezone` | `format.timezone` | The zone of `start` and `end` | +| `min_priority` | `5` | The lowest priority that prints during the window | +| `action` | `"digest"` | `digest` holds the other messages and prints them on one `Overnight` digest when the window ends; `drop` leaves them out | + +How a subscription behaves: + +- **First start.** With no state yet, it prints only messages published + from then on, also after a reconnect soon after. +- **Restarts and outages.** It keeps a cursor, the newest server time it + has dealt with, and when it reconnects or starts again it asks for the + messages since then, two minutes earlier to catch late ones. Of those, + it prints only the ones no older than `max_backlog`, measured by ntfy's + own clock as the stream tells it (the time of its first, `open` event, + or else the answer's `Date`), never by this host's, and leaves the + older ones out as they arrive; they stay out, even after a restart with + a longer backlog. It keeps the + IDs of the messages a replay could send again, at least the last 512 + and at most 20,000, so a message the server sends again, after a + reconnect or as ntfy's own repeat, never prints twice, even after a + flood; past 20,000, the next replay starts after the IDs it forgot. +- **Failures.** A dropped connection is opened again after 5, 10, 20, 30, + 60 and then every 120 seconds, each ± 20%, from 5 seconds again once a + connection has lasted two minutes. A `429` waits as long as its + `Retry-After` says. Refused credentials (`401` or `403`) are checked at + startup, and while the server refuses them the subscription is + `unauthorized` in `/healthz` and tries every five minutes. Printing goes + on meanwhile. +- **A full print queue** pauses the subscription: it stops reading the + stream, offers the message again after 1 second, then after twice as + long each time, up to 30 seconds, and moves its cursor only once the + message is queued. A digest that cannot be queued waits the same way. +- **Updates.** ntfy lets a publisher replace a notification with a later + message of the same sequence (`sequence_id`). When a message's sequence + printed before, on a card or a digest row (not only counted on a + digest), and is among the last 512 it remembers, its card says + `(updated)`, or with `ntfy.format.updates = + "skip"` it is left out. The first message of a sequence prints plain, + even when its publisher named the sequence. +- **State.** The cursor, the IDs, the budget and the held messages are in + `/ntfy-.json`, written at most once a second and at + shutdown, through a temporary file and a rename, so a crash leaves the + old file or the new one. A damaged file is ignored with a warning, and + the subscription starts as if new. Held messages survive a restart. +- **Jobs.** Each card and digest is an ordinary job with the source + `ntfy:`. Like any job, one that is still waiting when the daemon + shuts down is marked failed, and is not printed after the restart. + +`/healthz` lists each subscription's state, counts and last error; see +[Health](docs/api.md#health). + +> [!WARNING] +> Whoever can publish to a subscribed topic prints on your printer, and +> with priority 5 past the paper budget. On the public `ntfy.sh`, anyone +> who knows a topic's name can publish to it: reserve the topic so that +> others may not write to it, or at the very least use a long random name. +> Your own ntfy server lets everyone publish too, unless access control is +> on: set `auth-file`, set `auth-default-access` to `deny-all` (or +> `read-only`), since it defaults to `read-write`, and give write access +> only to your publishers. + +On your own ntfy server, with in its `server.yml` + +```yaml +auth-file: /var/lib/ntfy/user.db +auth-default-access: deny-all +``` + +give the printer a user of its own that may only read its topics, and +each publisher one that may only write to them: + +```sh +sudo ntfy user add printer # asks for a password +sudo ntfy access printer alerts read-only # once for each topic +sudo ntfy user add phone +sudo ntfy access phone alerts write-only +``` + +Then create the printer's access token and write it straight into a file +only the daemon can read, so that it never shows on the screen, on a +command line or in your shell history. `ntfy token add` prints the token +on standard error up to ntfy 2.13 and on standard output since 2.14, so +the script takes both, and keeps the token in a shell variable, which +`printf`, a shell builtin, hands to `install` on its standard input. +`install` runs under `umask 077`, so the file is readable by its owner +alone from the moment it is created, also with BusyBox's `install`, +which sets the mode only after writing; it then gets mode 600 and, on the +printer's host, the daemon's user. With ntfy on the same host: + +```sh +out=$(sudo ntfy token add printer 2>&1) +token=$(printf '%s\n' "$out" | grep -o 'tk_[A-Za-z0-9]*') +if [ -z "$token" ]; then + printf 'ntfy made no token:\n%s\n' "$out" | sed 's/tk_[A-Za-z0-9]*/tk_.../g' >&2 +elif printf '%s\n' "$token" | (umask 077; sudo install -m 600 -o uberbringer -g uberbringer /dev/stdin /etc/uberbringer/ntfy.token); then + unset token +else + cat >&2 <<'EOF' +The token was made but not stored. Fix the cause, then run: + printf '%s\n' "$token" | (umask 077; sudo install -m 600 -o uberbringer -g uberbringer /dev/stdin /etc/uberbringer/ntfy.token) && unset token +EOF +fi +unset out +``` + +With ntfy on another host, write the token there into a file of your own, +`ntfy.token` in the current directory: + +```sh +out=$(sudo ntfy token add printer 2>&1) +token=$(printf '%s\n' "$out" | grep -o 'tk_[A-Za-z0-9]*') +if [ -z "$token" ]; then + printf 'ntfy made no token:\n%s\n' "$out" | sed 's/tk_[A-Za-z0-9]*/tk_.../g' >&2 +elif printf '%s\n' "$token" | (umask 077; install -m 600 /dev/stdin ntfy.token); then + unset token +else + cat >&2 <<'EOF' +The token was made but not stored. Fix the cause, then run: + printf '%s\n' "$token" | (umask 077; install -m 600 /dev/stdin ntfy.token) && unset token +EOF +fi +unset out +``` + +Copy it to the printer's host, place it there with +`sudo install -m 600 -o uberbringer -g uberbringer ntfy.token /etc/uberbringer/ntfy.token`, +and delete both copies of `ntfy.token`. + +When no token comes out, the script shows what ntfy said, with any token +in it masked, such as that the user does not exist. When a token was +made but could not be stored, for example because `/etc/uberbringer` is +missing, nothing is written, and the token stays in `$token` until the +printed line stores it: never look it up with `ntfy token list`, which +prints every token in full, and removing one with `ntfy token remove` +needs the token on its command line. If the ntfy web app lets users sign +in (`enable-login: true`, which is off by default), you can also create +the token there under Account and paste it in with `sudoedit`, after +`sudo install -m 600 -o uberbringer -g uberbringer /dev/null /etc/uberbringer/ntfy.token` +has made the empty file. + ## Command line ```text @@ -352,7 +588,7 @@ internal/pkg/config/ Config from TOML and UBERBRINGER_* variables (Viper) 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: note, notify, ntfy; notification cards, markdown -internal/pkg/ntfy/ ntfy's message types +internal/pkg/ntfy/ ntfy's message types; the subscriber: stream, cursor, repeats, paper budget, quiet hours 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 64fafd6..086306e 100644 --- a/configs/config.example.toml +++ b/configs/config.example.toml @@ -63,6 +63,10 @@ # default spacing. box_line_spacing = 0 + # Blank lines fed before each cut (0-255), so that the last printed line + # does not sit right at the cut. + cut_feed = 3 + dial_timeout = "5s" write_timeout = "30s" retries = 3 # resend attempts when the printer is unreachable @@ -79,16 +83,27 @@ timezone = "Local" time_layout = "02 Jan 15:04" +[ntfy] + # The directory the subscriptions below keep their state in, so that a + # restart neither prints a message twice nor loses one. Required with a + # subscription. install.sh writes "/var/lib/uberbringer", and the Docker + # image sets it with UBERBRINGER_NTFY_STATE_DIR. + state_dir = "" + [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. + # How notifications are laid out, from the notify and ntfy modules and + # from the subscriptions. "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 + # A subscription's message that replaces one it printed (same sequence): + # "print" marks its title "(updated)", "skip" leaves it out. + updates = "print" [ntfy.markers] # Markers printed in front of the title for ntfy's tags, at most 16 @@ -97,6 +112,34 @@ # backup = "[B]" # nas01 = "" +# A subscription prints the messages of ntfy topics as they arrive. Each is +# a [[ntfy.subscriptions]] table, and they are set in this file only. Remove +# the "# " in front of the lines to use this one. +# [[ntfy.subscriptions]] +# name = "home" # in /healthz, logs and job sources (ntfy:home) +# server = "https://ntfy.example.com" # redirects are not followed +# allow_insecure = false # true allows a plain http server +# topics = ["alerts", "backups"] +# # At most one of: token = "tk_...", token_file, or user with +# # password_file. A file holds only the secret; keep it mode 0600. +# token_file = "/etc/uberbringer/ntfy.token" +# min_priority = 1 # the lowest priority that prints, 1-5 +# max_backlog = "1h" # how far back missed messages print, up to 12h +# rate_limit = 5 # receipts per rate_window; the rest wait for +# rate_window = "10m" # room and print together on one digest +# bypass_priority = 5 # outside quiet hours, this priority and above +# # print at once, outside the budget +# keepalive = "45s" # the server's keepalive interval +# +# [ntfy.subscriptions.quiet] # quiet hours; off without this table +# start = "22:00" +# end = "07:00" # an end before the start is on the next day +# days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] # days the window starts on +# timezone = "" # "" is format.timezone +# min_priority = 5 # prints during the window; the rest are held +# action = "digest" # digest prints what was held when the window +# # ends; drop leaves it out + [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 7ca75f1..2c62f16 100644 --- a/docs/api.md +++ b/docs/api.md @@ -20,6 +20,7 @@ the daemon. - [`notify`](#notify) - [`ntfy`](#ntfy) - [Notification cards](#notification-cards) + - [Digests](#digests) ## API @@ -68,7 +69,7 @@ included, carry `Cache-Control: no-store`. | POST | `/api/v1/preview/:module` | Show the lines that receipt prints, without printing it | | GET | `/api/v1/modules` | List the modules | | GET | `/api/v1/jobs/:id` | Job status | -| GET | `/healthz` | Printer and queue health (no auth) | +| GET | `/healthz` | Printer, queue and subscription health (no auth) | | GET | `/openapi.json` | This API's OpenAPI 3.1 document (no auth) | | GET | `/` | Version information (no auth) | @@ -131,8 +132,9 @@ curl -H @"$HOME/.uberbringer-auth" https://printer.example.com/api/v1/jobs/job_0 `status` is `queued`, `printing`, `done` or `failed`. A failed job includes an `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. +`/api/v1/print`, `module:` for a [module](#modules) route, or +`ntfy:` for an [ntfy subscription](../README.md#ntfy-subscriptions) +in the config. The last `queue.history` finished jobs are kept. ### Preview a receipt @@ -153,12 +155,16 @@ curl -X POST https://printer.example.com/api/v1/preview \ │ !!! ACHTUNG !!! │ └─────────────────────┘ [qr: https://example.com] + + + - - - - - - - partial cut - - - - - - - - ``` - The preview is read back from the bytes the job renders to, so it shows what the printer receives: wrapping, folded characters, `?` for missing - ones and the final cut. + ones, the blank lines [`printer.cut_feed`](../README.md#configuration) + feeds before a cut (3 by default) and the final cut. - Centred and right-aligned text is indented as the printer places it, counted in Font A columns. Text at a larger size shows each character once. @@ -172,11 +178,12 @@ With `Accept: application/json` the answer carries the styles too. For {"type": "qr", "data": "https://example.com"}]`: ```json -{"columns": 42, "codepage": "cp437", "line_count": 3, +{"columns": 42, "codepage": "cp437", "line_count": 6, "lines": [{"kind": "text", "text": "Total ............................. £12.50", "runs": [{"from": 0, "to": 5, "bold": true}, {"from": 36, "to": 42, "bold": true}]}, {"kind": "text", "text": " Thanks ?"}, {"kind": "qr", "text": "[qr: https://example.com]", "data": "https://example.com"}, + {"kind": "text", "text": ""}, {"kind": "text", "text": ""}, {"kind": "text", "text": ""}, {"kind": "cut", "text": " - - - - - - - partial cut - - - - - - - -", "data": "partial"}], "warnings": ["elements[1]: 1 character not in cp437 printed as ?"]} ``` @@ -210,6 +217,28 @@ when the worker renders it, before anything is sent; its `error` reads A printer that accepts connections but does not answer status requests is reported as `"status": "unknown"` with HTTP `200`. +With [ntfy subscriptions](../README.md#ntfy-subscriptions) configured, an +`ntfy` array lists each one, in the order of the config. The status code +still depends on the printer alone, so a subscription that cannot connect +never turns `/healthz` to `503`: + +```json +"ntfy": [{"name": "home", "state": "connected", "connected_since": "2026-11-29T20:58:01Z", + "last_message_at": "2026-11-29T21:04:05Z", "printed": 12, "digested": 2, "held": 0, "last_error": ""}] +``` + +| Field | Meaning | +|-------|---------| +| `state` | `connecting`, `connected`, `backoff` while it waits to reconnect after a failure, or `unauthorized` when the server refused its credentials; it then tries again every five minutes | +| `connected_since` | When the current connection opened; absent while there is none | +| `last_message_at` | When the last message arrived; absent until one has | +| `printed` | Messages printed on a card of their own since the daemon started | +| `digested` | Messages held for a [digest](#digests) since the daemon started | +| `held` | Messages waiting for the next digest | +| `last_error` | Why the last connection failed, such as `HTTP 401: the server refused the credentials` or `no data for 1m45s`; empty once one opens | + +Credentials, topic names and message text never appear. + Details: - **Brief problems are re-checked.** A printer that looks not ready is read @@ -282,7 +311,8 @@ rendered. A job is `{"elements": [...], "copies": 1}`. `copies` is 1–5, and each copy is cut separately. A partial cut is added after the last element unless that -element is already a `cut`. Boxes, rules, key-value rows and lists are +element is already a `cut`. Before every cut, `printer.cut_feed` blank lines +feed (3 by default), so that the last line does not sit right at the cut. Boxes, rules, key-value rows and lists are described under [Blocks](#blocks). ### `text` @@ -652,6 +682,9 @@ curl -X POST https://printer.example.com/api/v1/print/notify \ [qr: https://grafana.lan/d/disk] Open dashboard + + + - - - - - - - partial cut - - - - - - - - ``` @@ -704,6 +737,9 @@ attachment expires: Open dashboard [image 384 dots: sPs71M8A2Tq9.png] + + + - - - - - - - partial cut - - - - - - - - ``` @@ -728,6 +764,8 @@ attachment expires: - 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. + An [ntfy subscription](../README.md#ntfy-subscriptions), which remembers + what it printed, marks such a message `(updated)`. - 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 @@ -850,6 +888,36 @@ 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. +A card an [ntfy subscription](../README.md#ntfy-subscriptions) prints for +a message that replaces one it printed before, of the same `sequence_id`, +has `(updated)` after its title, unless `ntfy.format.updates = "skip"` +leaves such messages out. + +#### Digests + +An ntfy subscription prints the messages it held back on one digest: those +over its rate limit as soon as the limit has room again, and those held in +quiet hours when the window ends. A row gives each message's time, its tag +markers and its title, or the first line of a message without one, or else +its topic, cut to 60 characters, in the order they arrived; the bottom +border holds the time from the first held message to the digest. + +```text +┌─ ntfy digest · 6 held ─────────────────┐ +│ 21:05 [!] Disk almost full │ +│ 21:05 [!] Disk almost full (updated) │ +│ 21:06 (!) Backup FAILED on nas01 │ +│ 21:07 Watchtower │ +│ 21:07 Jellyseerr │ +│ 21:09 [x] grafana is DOWN │ +└───────────────────────── 21:04-21:14 ──┘ +``` + +A digest that holds a message from quiet hours is titled +`Overnight · N held`. It lists 50 messages and counts the rest on a last +row, `... and 13 more`. A digest that cannot be laid out prints as a plain +list of its rows, logged and reported like a card's fallback. + #### Markers Up to two tags with a marker print it in front of the title, each marker diff --git a/docs/design.md b/docs/design.md index a752f26..6e604f9 100644 --- a/docs/design.md +++ b/docs/design.md @@ -43,6 +43,13 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue ( resends the same bytes and does not render again. A send that fails part-way can print part of a receipt twice. That is accepted, because retries are what let a job survive a printer that is briefly offline. +- **Blank paper before the cut (owner, 2026-11-30).** The cut, `GS V 66 0`, + feeds the last printed line just past the cutter, so the cut fell right + under it. `printer.cut_feed` blank lines (3) now feed before every cut. + They are `ESC d` lines rather than `GS V`'s extra motion units, because + a line is the same on every model while the motion unit is not. The + renderer's option is 0 unless set, so receipts whose bytes tests pin + keep their bytes; the daemon's default is 3. - **Text in, code page out.** Clients send UTF-8, which is transcoded to `printer.codepage`. The default is CP437, for the box drawing and shading the owner prints (owner, 2026-11-29). Control characters are stripped, so @@ -107,7 +114,7 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue ( 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. + the ntfy subscriptions 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 @@ -182,8 +189,9 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue ( `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 + (`print`, `module:` or `ntfy:`) and a reference, the + request ID on the HTTP routes and the message's ID, or `digest`, for a + subscription. 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 @@ -285,22 +293,133 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue ( the operator's own reverse proxy, whose address goes in `webserver.trusted_proxies`. +- **ntfy subscriptions run in the daemon.** ntfy is an input: its + notifications are printed (owner, 2026-11-29). The owner's server is + self-hosted at a public URL and attachments come from a public host, so + image fetches need no private-network exception. Each + `[[ntfy.subscriptions]]` table is one `ntfy.Subscriber`, run as one + goroutine of the daemon's errgroup that never fails it: connection and + print failures are retried, and `Run` returns nil when the daemon stops. + The subscriber hands messages and digests to a handler in + `internal/app`, which builds them with `modules` and submits them, so + `ntfy` never imports `modules`. + - One connection per subscription reads `GET //json` as a + stream: dial, TLS and header timeouts, no overall one. A loop owns all + state and one goroutine per connection reads lines, so the loop can + stop reading (TCP backpressure) while the print queue is full, and + every timer (reconnect, stall, retry, digest, save) is one deadline + in it. + - The cursor is ntfy server time, never `since=`: an unknown or + expired ID makes ntfy replay the topic's whole history. ntfy sends + `open` before the replay, so only a keepalive or a dealt-with message + moves the cursor, except on a first start without `since`, where + nothing is replayed and `open`'s time is safe. ntfy dates a message + before it stores its attachment, so one can arrive after others dated + later; a reconnect therefore asks for two minutes before the cursor. + The IDs of the messages a replay could send again, those dated at or + after where a replay can start, are kept, so the repeats of a flood + drop, as do ntfy 2.31+'s same-second repeats; the last 512 are kept + anyway, and 20,000 in all at most. When that cap forgets IDs a replay + could still send, the floor rises past them. + - A saved floor bounds every replay from below. A first start sets it to + `open`'s time, so a reconnect soon after never reaches before the + start. `max_backlog`, at most ntfy's 12-hour cache, clamps a replay + by the server's clock, never the host's, so a host clock that is off, + or is stepped, can neither widen a replay nor lose messages. A + connection asks for its replay unclamped; its `open` event, which ntfy + sends first, before any replay, tells ntfy's own clock, the one it + dates messages by. The answer's `Date` stands in only when the open + event has no time, since a proxy in front of ntfy may write it from a + clock of its own. The time since the clock was read is measured on + the monotonic clock. The replay's messages + older than the backlog are then left out as they arrive. Each + connection learns the clock afresh, so nothing learned earlier, before + a step of the host's clock, carries over; keepalives do not count, + since they can wait in the connection while a full queue pauses + reading. The clamp raises the floor at once, so a later start with a + longer backlog never prints what it left out, even if no keepalive + came before the daemon stopped. An unclamped request after a long + outage costs only a larger replay, bounded by the server's cache. + - Redirects are never followed. Go would resend the credentials to the + same host over plain `http`, and a redirect to another host or port, + such as the printer's raw port, would carry the request there and + print what came back; a `3xx` is a failed connection whose error + says to set the address it points to. + - The cursor moves past a message only once it is queued, held or + deliberately left out. A message queued but not yet printed when the + daemon stops is lost, as any waiting job is: the queue stays in + memory, because ESC/POS cannot say what printed. + - State is one JSON file per subscription in `ntfy.state_dir`, written + atomically (temporary file, fsync, rename) at most once a second and + at shutdown, mode 0600 since held messages carry titles. A damaged + file means a fresh start with a warning. `state_dir` has no default, + since the daemon also runs on Windows; `install.sh` writes the unit's + `StateDirectory`, `/var/lib/uberbringer`, and the image sets the same + path. + - Credentials are optional, at most one kind, so that a long random + topic on a public server works without an account. Refused + credentials show at startup through `//auth`, then as + `unauthorized` in `/healthz`, retried every five minutes. Failures + back off 5 s to 120 s with ±20% jitter, a `429` waits for its + `Retry-After`, and a stream silent for twice the keepalive plus 15 s + is reconnected. + - `/healthz` lists the subscriptions but its status code still depends + on the printer alone. `last_error` is built from the failure without + the request URL, which names the topics, and a topic on a public + server can be a secret. + - Which priorities print is set per subscription with `min_priority` + (default all), which the server filters by. How priorities 1 and 2 + print, compact by default, is `ntfy.format.style`, shared by every + source of cards. + - Subscriptions come from the file only: a list of tables has no + environment variable, and each entry starts from its own defaults, + which Viper cannot give the entries of a list. +- **The paper budget is a strict window (owner, 2026-11-30).** At most + `rate_limit` receipts print in any `rate_window` (5 in 10 minutes by + default), digests included, so a flood never prints more than that, + even in its first minutes. Messages over it are held and print on one + digest once the window has room, and outside quiet hours, while a + digest is waiting, later messages join it, so they print in order. + Outside quiet hours, `bypass_priority` (5) and above print at once; + during them, `quiet.min_priority` decides first. The receipt times are + saved, so a restart cannot reset the budget. A digest lists 50 + messages and counts the rest; only those with a row count as printed + for updates. +- **Quiet hours print a morning digest (owner, 2026-11-30).** During a + subscription's daily window only `quiet.min_priority` (5) and above + print; the rest are held in the same digest buffer and print as one + `Overnight` digest when the window ends, or are dropped with + `action = "drop"`. A window's bounds are the instants the zone's clocks + show its times of day, so a window crossing midnight or a change of + clocks keeps them. A bound the clocks skip is the first instant after + the gap, and one they show twice is the one Go's `time.Date` gives; + days are taken at noon, which every zone has. The zone defaults to + `format.timezone`, the zone the cards print in. Held messages are saved + with the state. +- **A subscription marks updates by what it printed (owner, 2026-11-30).** + A message is an update when its sequence (`sequence_id`, or its ID) + printed before, on a card or a digest row, among the last 512 sequences + remembered. So the first message of a sequence its publisher named + prints plain, and the routes, which remember nothing, never mark + updates. `ntfy.format.updates = "skip"` leaves updates out instead. +- **The subscriber is tested on a virtual clock (owner, 2026-11-30).** + `testing/synctest` runs it against an in-memory ntfy server: + reconnects, stalls, backoff, `Retry-After`, quiet nights across clock + changes and a 24-hour soak with floods, repeats, refusals, a full queue + and a restart, in seconds. `synctest.Test` fails if a goroutine + outlives the test, so the soak replaces a 24-hour leak run on + hardware; a short test over real sockets covers `net/http`'s own + goroutines. Both run in every `go test`. + ## 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 three phases are +blocks. The plan is `docs/plans/formatters.md`. Its first four 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 - attachments come from a public host, so image fetches need no - private-network exception. -- Which priorities print is configurable per subscription. By default every - priority prints, and priorities 1 and 2 print in a compact form. -- Labels are in English. The footer's time zone and date format come from - the config. +the `note` module; the `notify` and `ntfy` modules and scoped tokens; and +the ntfy subscriptions. What is left, phase 5, is built only when a need +appears. Labels are in English, and the footer's time zone and date format +come from the config (owner, 2026-11-29). ## Deferred @@ -313,9 +432,10 @@ Next is the built-in ntfy subscriber. Decided so far (owner, 2026-11-29): built): - Jobs stored with GORM on SQLite, so queued jobs, statuses and history survive a restart. Release builds use `CGO_ENABLED=0`, so the SQLite - driver must be pure Go (for example `github.com/glebarez/sqlite`), and the - systemd unit needs a `StateDirectory` because its file system is - read-only. The plan must also say how to tell which receipts printed + driver must be pure Go (for example `github.com/glebarez/sqlite`), and + the database belongs in the unit's `StateDirectory`, + `/var/lib/uberbringer`, the only directory it may write. The plan must + also say how to tell which receipts printed before a crash, so a restart never prints a receipt twice. - A print preview as an image: a digital test print of a job that shows what the paper would look like, without printing. Formatters phase 1 adds diff --git a/docs/plans/formatters.md b/docs/plans/formatters.md index 4bfadd1..81b0f89 100644 --- a/docs/plans/formatters.md +++ b/docs/plans/formatters.md @@ -1,314 +1,35 @@ # Plan: CP437 blocks, modules and ntfy printing -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) - -- **ntfy server:** self-hosted at a public URL. The subscriber authenticates - with a token. Attachments come from a public host, so no private-network - exception in safehttp is needed. -- **Which priorities print:** configurable per subscription (minimum priority, - and whether priorities 1-2 print in the compact form). Default: all - priorities, 1-2 compact. -- **Text folding on /print:** yes. Characters the code page lacks fold to - ASCII look-alikes (smart quotes, dashes, ellipsis) and an emoji sequence - prints as one '?'. -- **Language:** English labels ('URGENT', 'HIGH', 'Tags:', '... N more - lines'). Footer time zone and format come from config, default local time - and "02 Jan 15:04". - -## Decisions (owner, 2026-11-30) - -- **Links:** every link prints as a QR code: the click URL and the view - actions, deduplicated, at most 3. `[ntfy.format] qr` defaults to "all". -- **Image attachments** print (`images = true`). -- **Edited messages** print again, marked "(updated)" (`updates = "print"`). -- **Paper budget:** 5 receipts per 10 minutes per subscription by default, - configurable; the rest fold into one digest receipt. Priority 5 always - prints. -- **Quiet hours:** wanted, as a morning digest, and part of phase 4. During - a configured window only priority 5 prints; everything else is held and - printed as one digest receipt when the window ends. Window, days and time - zone come from config (default 22:00-07:00 every day, local time); off - unless configured. - -## Overview - -FOUNDATION -The plan starts from Design 1 (components): layout blocks inside the existing element list, small Go modules that turn a plain payload into an ordinary receipt.Job, and ntfy as one of those modules. It is cut down to the vocabulary that notes and notifications actually need: -- box, rule and kv in phase 1 -- list in phase 2 -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=