Breaking: a job with a raw element prints only with a token issued with uberbringer token --raw. Every other token, every existing one included, gets 403 token_scope for it, with the raw elements in details, and keeps every other route. The notify module prints a notification card from a title, message, priority and tags, with topic, click, up to three actions, image, markdown and time as options; it decodes strictly and refuses a payload over its length caps. The ntfy module takes one ntfy message as ntfy sends it, such as the ntfy client's $NTFY_RAW, ignores fields it does not know, cuts text over the caps, and answers 204 for other events and binary bodies. Both print every message plain: one message cannot tell the first of a sequence from a replacement, since a publisher may choose the sequence ID. internal/pkg/ntfy holds ntfy's message types. Both print the same card. The priority picks the form: a dark URGENT rule and a double box, a double box headed HIGH, a single box with the title in its border, or a rule with no box. Tags print as markers in front of the title, the rest on a Tags row; links print as QR codes with their labels; attached PNG, JPEG, GIF and WebP images print after the card. A line-level markdown subset is laid out without a dependency, keeping marks inside code spans and URLs, and emoji are removed after a few typed ones become markers. A card that cannot be laid out prints as a plain receipt, and the server logs the fault once at ERROR and reports it to Sentry once. [ntfy.format] and [ntfy.markers] shape the cards; the markers table is a setting with the user's own keys, also settable as UBERBRINGER_NTFY_MARKERS=name=value,... uberbringer token --modules issues a token limited to those modules' print and preview routes, job status and the module list; each route in the table says which tokens it takes, and a scope claim that could read as absent makes the token invalid. image elements take optional, which also shrinks a too-wide image to the paper; a QR code that could be too wide for the paper prints with smaller modules; box takes title_bold. Submit takes a Meta whose source shows in job status and, with a copy of the request ID, in every worker log line of the job. The four ntfy cards passed on the TM-T88IV, posted as the client recipe posts them, and their bytes are pinned in TestPaperReceipts. docs/api.md describes the modules, the card and the client recipe, with tokens read from a header file; docs/swagger.json is regenerated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
21 KiB
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] qrdefaults 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=
- From Design 3 (sources): a simple Notice input (the notify module), images marked optional, a cursor taken from ntfy server time, the time/tzdata import, and Submit Meta for traceability.
WHAT SHIPS WHEN (about 5 developer days left to the end of phase 4)
- Boxes and preview: done.
- Notes and modules: done. POST /api/v1/print/note {title, text, items} prints a boxed checklist.
- Notifications: done. POST /api/v1/print/notify {title, message, priority, tags} is for scripts and phone shortcuts. POST /api/v1/print/ntfy takes the ntfy CLI's $NTFY_RAW unchanged, so ntfy printing needs only a client.yml entry and no jq.
- Built-in ntfy subscriber, 5 days. You only change the config. It reconnects safely, removes duplicates, caps the backlog, folds floods into a digest receipt, and holds non-urgent messages during quiet hours for a morning digest.
- Later, on demand: the second-printer pool, user templates, an ntfy-compatible publish endpoint, table/banner/spans, and webhooks.
BACKWARD COMPATIBILITY
- Every existing element, field and response keeps its meaning, and /print stays strictly decoded.
- TestRenderCompat (receipt/testdata/compat) and TestPaperReceipts pin the bytes of existing jobs; later phases keep them passing.
- Emoji are removed only on the module and ntfy paths; /print prints an emoji sequence as one '?'.
WHERE THE JUDGES DISAGREED, AND WHAT THIS PLAN CHOSE
- list: in (phase 2), because the note module needs checklists.
- spans, table, group, banner, nested boxes and goldmark: deferred.
- Geometry checks in the HTTP handler (Renderer.Check): rejected. Layout never fails on a valid job, preview shows the result and line count synchronously, and each module caps its own length.
- Scoped tokens: built in phase 3; design.md records the decision.
- Quiet hours: phase 4, as a morning digest (owner decision).
Open questions
Before phase 4 (config, not design):
- Topics and auth: which topics and quiet-hours window to configure. A dedicated read-only ntfy user with an access token is assumed.
When the second printer arrives:
- Which jobs and ntfy topics go to which printer, and should urgent messages print on both?
Mockups (42 columns, CP437)
The notification cards are built: docs/api.md § Notification cards shows the four priority forms as they printed. Still to come:
All lines are at most 42 columns; every
glyph is a CP437 byte >= 0x20 (checked
with Python cp437). Ruler, not printed:
1 2 3 4
123456789012345678901234567890123456789012
--- 12. Rate-limit digest (phase 4)
┌─ 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 ──┘
One row per held message, in arrival
order. Priority 5 never waits.
Glyphs never used: • (only cp1252 has
it), ► ◄ → ← and other 0x01-0x1F
glyphs (printer control codes), emoji.
Use · ∙ ■ » √ ° instead.
API
All /api/v1 routes keep the existing Bearer JWT, rate limiter and error shape {"error","details"}. Successful print responses keep today's 202 body plus a Location header: {"id":"job_01kbx4n6m3ex8tq0wq3r5vrzq1","status":"queued","source":"print","created_at":"2026-11-29T21:04:05Z"}
==== PHASE 4: configuration ====
Keys go through internal/pkg/config as today: strict keys in the file, an UBERBRINGER_
[ntfy.format] updates = "print" # print | skip: a message replacing one the subscriber printed [ntfy] state_dir = "/var/lib/uberbringer" ntfy.subscriptions name = "home" server = "https://ntfy.sh" topics = ["alerts", "backups"] # ^[-_A-Za-z0-9]{1,64}$, at most 150 token_file = "/etc/uberbringer/ntfy.token" # or user + password_file; exactly one min_priority = 3 # sent to ntfy as ?priority=3,4,5 max_backlog = "1h" # 12h at most (the ntfy cache) rate_limit = 5 # receipts per rate_window; the rest go into one digest rate_window = "10m" bypass_priority = 5 keepalive = "45s" [ntfy.subscriptions.quiet] # optional; quiet hours are off without this table start = "22:00" end = "07:00" # may cross midnight days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] timezone = "Local" min_priority = 5 # prints during the window; the rest are held action = "digest" # digest | drop; digest prints the held messages when the window ends
GET /healthz (phase 4) adds a field. The HTTP status still depends only on the printer: "ntfy":[{"name":"home","state":"connected","connected_since":"2026-11-29T20:58:01Z","last_message_at":"2026-11-29T21:04:05Z","printed":12,"digested":2,"last_error":""}]
- state is one of connecting, connected, backoff or unauthorized.
- Tokens are never returned.
Architecture
LAYERS (each calls only downward)
- server (Fiber v3 handlers) -> modules (payload to receipt.Job) -> receipt (blocks, layout, render, preview) -> escpos (bytes, code pages, interpreter).
- internal/pkg/ntfy holds the ntfy wire types (built) and the subscriber (phase 4). modules imports it for the Message type. serve.go connects the subscriber to modules through a callback, so ntfy never imports modules.
- printqueue takes Submit(job, Meta) (built).
INVARIANTS (all match the current code)
- receipt.Job stays printer-neutral. Blocks are sized at render time from Options.Columns or Profile.Columns(font). The same job therefore prints correctly on a TM-T88IV, TM-T88VII or TM-m50II, and on several printers later.
- Job.Validate stays structural and independent of geometry, so handlePrint keeps its Validate-then-Submit flow. New checks:
- nested problem paths, e.g. elements[0].children[3]
- checkFields: a field that does not apply to a new type is an error
- child rules
- children count toward MaxElements (500)
- one level of nesting only
- Layout never fails on a valid job. Widths clamp, titles are cut with "...", and over-long words split the way wrap() already splits them. The only new render-time failure is the [format].max_lines backstop (default 2000).
- Renderer.Render is still the only path to printer bytes, and still all-or-nothing.
- New code never emits raw ESC/POS. Payload text only ever lands in string fields of elements. The raw element stays available on /print only, to tokens issued with --raw.
- /print stays strictly decoded (DisallowUnknownFields). A byte-compatibility test pins today's bytes.
DATA FLOW
- /print: strict decode -> Validate -> Submit -> worker -> Render.
- Render runs Validate, normalize, layout, loadImages, then builds the bytes, and sends them in one write.
- /preview: strict decode -> Validate -> Renderer.Preview -> escpos.Interpret -> text/plain or JSON.
- Preview uses a placeholder fetcher, so no network.
- /print/{module}: module.Build(body, Env) -> Validate (a failure here is a module bug, 422) -> Submit(job, Meta{Source: "module:"}).
- Subscriber (phase 4): ntfy stream -> skip, dedupe, filter, rate limit -> modules.FromNtfy -> Card -> Validate -> Submit(job, Meta{Source: "ntfy:", Ref: }).
KEY TYPES (the blocks, the preview, the module layer, the notification card and the ntfy wire types are built; docs/api.md and design.md describe them)
modules (built) type Notice; type CardOptions (zero value is the default; Env.Card carries it) func FromNtfy(m ntfy.Message) (Notice, error) // ErrSkip for non-message events and base64 bodies func Card(n Notice, o CardOptions, env Env) (receipt.Job, error) // the job always prints; a *FallbackError comes with the plain receipt, for the caller to log and report
ntfy type Message, Action, Attachment // built type Subscriber // phase 4 func (s *Subscriber) Run(ctx context.Context, handle func(context.Context, Message) error) error
printqueue (built) Submit(job receipt.Job, meta Meta) (Status, error); type Meta struct{ Source, Ref string }; Status.Source
The subscriber marks and skips updates itself (Dedupe and state below); Card prints the notice it is given.
SUBSCRIBER (phase 4, internal/pkg/ntfy)
Connection
- One request per subscription: GET {server}/{t1,t2}/json?since=
&priority=<min..5>. - Auth is Bearer tk_... or Basic. The User-Agent is generic.
- Dial, TLS and response-header timeouts apply, with no overall timeout, because the response is a stream.
Cursor
- The cursor C is ntfy server time in Unix seconds, and is persisted.
- At start: since=C when C is no older than max_backlog; otherwise since = now - max_backlog. With no saved state, since is left out, so only new messages print.
- since= is never used. An unknown or expired id makes ntfy replay the topic's whole history.
- C moves to a message's time only once its Submit has succeeded (or the message was deliberately skipped). It moves to an open or keepalive event's time only when no message is waiting to be retried.
Dedupe and state
- A ring of the last 512 ids is persisted. It drops ntfy 2.31+ same-second repeats and the overlap after a reconnect.
- Updates: the sequence IDs of printed messages are remembered with the ids. A message whose sequence was printed before sets Notice.Updated, so its card shows "(updated)", or with updates = "skip" it is left out. The module routes print every message plain (design.md).
- State is JSON in state_dir, written as temp file, then fsync, then rename. It is written at most once a second, and on shutdown.
Reconnects
- If no line arrives for 2 × keepalive + 15 s (105 s by default), the subscriber reconnects.
- Backoff is 5, 10, 20, 30, 60, then 120 s, with ±20% jitter. It resets after 2 minutes connected.
- A 429 follows Retry-After.
- 401 or 403 sets the state to "unauthorized" and retries every 5 minutes.
- GET /{topic}/auth is called at startup so bad credentials show up early.
Queue full
- On ErrQueueFull the subscriber stops reading the stream (TCP backpressure is fine) and retries the same message, waiting from 1 s up to 30 s.
Rate limit
- A token bucket allows rate_limit receipts per rate_window.
- Messages over the limit go into one digest receipt, printed when tokens return. The digest holds 50 rows; after that, messages are only counted.
- Messages at or above bypass_priority skip the bucket.
Quiet hours
- During a subscription's quiet window, messages below quiet.min_priority are held (action = digest) or dropped (action = drop). Held messages share the digest buffer and print as one "Overnight" digest when the window ends.
Images and logging
- Attachment images are fetched through safehttp like any image URL; the ntfy server is public, so no private-network exception is needed.
- Logs carry the source, ntfy id and job id, never the message text. No notification content goes to Sentry, matching sentryMiddleware's existing rule of attaching no bodies.
Phases
Phase 4: Built-in ntfy subscriber (5 days)
Goal. No client code and no extra programs: add ntfy.subscriptions to the config and the phone's ntfy app becomes the only client. Restarts and outages must not lose a flood's worth of paper or reprint old messages, and nothing but urgent messages prints during quiet hours.
Work.
internal/pkg/ntfy
- subscriber.go:
- The JSON-stream client, reading lines through bufio with a 1 MiB cap.
- The since cursor, the stall watchdog, backoff with jitter and Retry-After, the /auth precheck, and the unauthorized state.
- Run(ctx, handle).
- state.go: the cursor plus the 512-id dedupe ring, written atomically (temp file, fsync, rename), at most once a second and on shutdown.
- ratelimit.go: the token bucket plus the digest buffer, with an injectable clock.
- quiet.go: quiet hours. During the window, messages below min_priority are held (action = digest) or dropped (action = drop); held messages print as one digest when the window ends, sharing the digest buffer and its 50-row cap. Boundaries are computed with time.Date in the configured zone, so windows cross midnight and handle DST. Held messages are persisted with the cursor state, so a restart during the night does not lose them.
- status.go: snapshots for /healthz.
internal/pkg/modules
- digest.go: the digest card (mockup 12), titled "ntfy digest · N held" for rate-limit overflow and "Overnight · N held" for quiet hours.
internal/app/uberbringer
- serve.go: one group.Go(sub.Run) per subscription.
- handle does FromNtfy, Card, Validate, then queue.Submit with Meta{Source:"ntfy:", Ref:id}.
- On ErrQueueFull it retries and pauses the stream. If formatting fails, it prints the fallback receipt.
- Run returns nil on cancel and never fails the errgroup on temporary errors.
internal/pkg/config
- [ntfy] state_dir and ntfy.subscriptions, with validation:
- unique names
- https unless allow_insecure is set
- the topic regex, at most 150 topics
- exactly one of token, token_file, or user + password_file
- max_backlog of 12h or less
- rate_limit greater than 0 (default 5 per 10m)
- quiet: start and end as HH:MM, known day names, a loadable time zone, min_priority 1-5, action digest or drop
- a warning when the token file can be read by group or others
internal/app/uberbringer/server
- /healthz gains the ntfy array without changing how the status code is decided.
Deployment
- install.sh: StateDirectory=uberbringer in the unit, because ProtectSystem=strict makes /var/lib read-only otherwise. Also write [ntfy] state_dir.
- Dockerfile and README: document a /var/lib/uberbringer volume.
- README: a Subscriber section with ntfy.sh security advice (a reserved or access-controlled topic, or a long random name, plus a dedicated read-only ntfy user).
Tests.
internal/pkg/ntfy (fake clock and fake sleeper) Use an httptest server that streams NDJSON open, keepalive and message events. Cases:
- first start sends no since
- reconnect after EOF uses since=
- a stored cursor older than max_backlog is clamped
- a stall triggers a reconnect after 2×keepalive+15s
- backoff follows its sequence and resets after a stable connection
- 429 honours Retry-After
- 401 sets the unauthorized state
- same-second duplicates and reconnect overlap are deduped, also after the state is reloaded from disk
- the cursor never advances past a message whose Submit failed (ErrQueueFull)
- the state file survives a restart, and a partial or corrupt file is treated as no state with a warning
- multi-topic URLs
- min_priority is sent as the priority filter
- the rate limit sends overflow to a digest, priority 5 bypasses it, and the digest caps at 50 rows
- quiet hours: a window crossing midnight, a DST change night, priority 5 printing during the window, held messages printed as one digest at the window's end, action = drop, and held messages surviving a restart
internal/pkg/config
- Table tests for every validation rule.
internal/app/uberbringer/server
- /healthz shows subscription status, and the status code is unchanged when ntfy is down.
Logs
- A test logger asserts no message text is logged.
Done when.
- A message published from the phone prints within a few seconds.
- Stopping uberbringer for 30 minutes while messages are published, then starting it, prints each missed message once (or one digest), with no reprints.
- A stored cursor older than max_backlog never replays older messages.
- A wrong token shows state 'unauthorized' in /healthz while printing keeps working.
- With quiet hours set a few minutes ahead, a priority 3 message published inside the window prints only in the digest at its end, while a priority 5 message prints at once.
- A 24-hour run shows no leaked goroutines.
- The full gate passes (CLAUDE.md lists it).
Phase 5: Later, on demand (1-3 days each; build only when a real need appears)
Goal. Keep the core small. Each item below is independent and waits for real demand or an owner decision.
Work.
- Second printer, for the TM-T88VII and TM-m50II:
- a printqueue Pool with one Queue and worker per printer
- [printers.] config, each table decoded through Viper onto the printer defaults, with the old [printer] table becoming "default" and strict unknown-key checks kept
- ?printer= on print, preview and modules; printer = "name" per subscription; optional priority routes
- /healthz per printer, with the status still following the default printer
- Jobs stay printer-neutral, so nothing in the block or module code changes.
- User templates (Design 2's safety model):
- JSON files with a typed payload schema
- text/template only inside string values; if and each keys
- element keys checked by reflection; templated hex rejected; output capped per field and per job
- every template's example run through Format and Validate at startup
- An ntfy-compatible publish endpoint, POST /ntfy/{topic} and POST /ntfy, outside /api/v1. Auth is a Bearer JWT, or Basic with an empty user and the JWT as password. Tools that send to an ntfy server URL could then print directly.
- More blocks: table (with ╤╪╧ junctions), banner, group, inline spans, rule char.
- Queue.Cancel so message_delete can cancel a still-queued job.
- Webhook sources: /hooks/{name}, with auth always required, HMAC compared with hmac.Equal, and an unknown name rejected with 404 before the body is read.
- Default line spacing per model in escpos.Profile, once calibrated on each model.
Tests.
Each item ships with its own goldens and table tests in the phase 1-4 style. For the printer pool, also:
- a config migration test from [printer] to printers.default
- unknown keys inside [printers.x] still rejected
- two queues printing in parallel
Done when.
Each item is done when its feature has golden or preview coverage, README docs, and a real-paper check where layout changes. Nothing here blocks phases 1-4.