Add ntfy subscriptions with digests, quiet hours and a cut feed
[[ntfy.subscriptions]] tables make the daemon subscribe to ntfy topics itself and print each message as a notification card, so the phone's ntfy app is the only client. Each subscription is one ntfy.Subscriber in the daemon's errgroup: one event loop owns its state, and one goroutine per connection reads the JSON stream. internal/app hands its messages to modules.FromNtfy, Card, Validate and Submit with the source ntfy:<name> and the message's ID as ref, so ntfy never imports modules. The cursor is ntfy server time, never an ID. ntfy sends open before the replay, so only keepalives and messages dealt with move it, and a reconnect asks for two minutes before it, since a message is dated before its attachment is stored. The IDs of the messages a replay could send again are kept, at least the last 512 and 20,000 at most, so a flood in the overlap never reprints; when the cap forgets IDs a replay could send, the floor rises past them. A saved floor bounds replays: a first start sets it to the open event's time, and max_backlog (default 1h, at most 12h), measured by the server's clock as each connection tells it (its open event, else its Date, then the monotonic clock), never the host's, so replays are requested unclamped and filtered as they arrive, raises it when it clamps, so what it left out stays out. The state, with the held messages and the receipt times, is written atomically at most once a second and at shutdown. Redirects are never followed, so credentials never go to another address or over plain http. A stalled stream reconnects after twice the keepalive plus 15 s, failures back off 5 to 120 s with jitter, a 429 waits for Retry-After, and refused credentials, checked at startup through /auth, show as unauthorized and retry every 5 minutes. A full print queue pauses reading and retries the message from 1 s to 30 s, and the cursor moves past it only once it is queued. The paper budget is a strict window: at most rate_limit receipts (5) in any rate_window (10m), digests included; the rest are held and print on one digest card once there is room, and outside quiet hours bypass_priority (5) and above print at once. Quiet hours hold everything below their min_priority for one Overnight digest when the window ends, or drop it; windows cross midnight and keep their times of day when clocks change, also where the change skips midnight or a window's end. A message whose sequence printed before, on a card or a digest row, is marked (updated), or skipped with ntfy.format.updates = "skip"; the first of a sequence its publisher named prints plain. /healthz lists the subscriptions without changing how its status code is decided, and no credential, topic or message text reaches it, the logs or a config error. Subscriptions come from the file only, with strict keys and per-entry defaults; credentials are optional, at most one kind. ntfy.state_dir is required with a subscription: the unit gains StateDirectory=uberbringer, install.sh writes the path into a new config, and the Docker image sets it for a volume and runs as the fixed user 10001. README explains how to lock a self-hosted ntfy server down so that only your publishers can print. Breaking: printer.cut_feed (default 3) feeds blank lines before every cut, so the last line no longer sits right at the cut. They count toward format.max_lines once per copy, so a job within 3 lines a copy of the limit now fails. The renderer's option is 0 unless set, so the pinned receipts keep their bytes. testing/synctest drives the subscriber on a virtual clock, including a 24-hour soak with floods, repeats, refusals, a full queue, quiet hours and a restart that fails on any leaked goroutine; it replaces a 24-hour run on hardware. Tests over real sockets cover net/http's goroutines and redirects to plain http and to another port. Checked on the TM-T88IV against a live ntfy server: a phone message, quiet hours with priorities 3 and 5 and the Overnight digest, a stale cursor, a 30-minute outage with an update, a wrong token, and the three-line cut feed. The digest and the cut-feed card are pinned in TestPaperReceipts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1335ed0687
commit
fb76284129
52 files changed
+6464
-390
No files matched your search
@@ -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_<SECTION>_<KEY>`, 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-<name>.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:<name>`; 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
|
||||
`<state_dir>/ntfy-<name>.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:<name>`. 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
|
||||
|
||||
Reference in new issue
Block a user